<type>xml</type>
</dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin.applications</groupId>
- <artifactId>statistics-manager-config</artifactId>
- <type>xml</type>
- <classifier>config</classifier>
- </dependency>
-
<dependency>
<groupId>org.opendaylight.openflowplugin.model</groupId>
<artifactId>model-flow-base</artifactId>
<bundle>mvn:org.opendaylight.openflowplugin.applications/inventory-manager/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.openflowplugin.applications/forwardingrules-manager/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.controller/liblldp/{{VERSION}}</bundle>
- <configfile finalname="${config.configfile.directory}/${config.statistics.manager.configfile}">mvn:org.opendaylight.openflowplugin.applications/statistics-manager-config/{{VERSION}}/xml/config</configfile>
</feature>
</features>
switch (mod.getModificationType()) {
case DELETE:
- remove(key, mod.getDataBefore(), nodeIdent);
+ if (mod.getDataAfter() == null) {
+ remove(key, mod.getDataBefore(), nodeIdent);
+ }
break;
case SUBTREE_MODIFIED:
- update(key, mod.getDataBefore(), mod.getDataAfter(), nodeIdent);
+ //NO-OP since we donot need to reconciliate on Node-updated
break;
case WRITE:
if (mod.getDataBefore() == null) {
add(key, mod.getDataAfter(), nodeIdent);
- } else {
- update(key, mod.getDataBefore(), mod.getDataAfter(), nodeIdent);
}
break;
default:
}
}
-
- public void update(InstanceIdentifier<FlowCapableNode> identifier,
- FlowCapableNode original, FlowCapableNode update, InstanceIdentifier<FlowCapableNode> nodeIdent) {
- if(compareInstanceIdentifierTail(identifier,II_TO_FLOW_CAPABLE_NODE)){
- LOG.warn("Node updated: {}",nodeIdent.firstKeyOf(Node.class).getId().getValue());
- //donot need to do anything as we are not considering updates here
- if (!nodeIdent.isWildcarded()) {
- // then force registration to local node cache and reconcile
- flowNodeConnected(nodeIdent, true);
- }
- }
- }
-
-
public void add(InstanceIdentifier<FlowCapableNode> identifier, FlowCapableNode add,
InstanceIdentifier<FlowCapableNode> nodeIdent) {
if(compareInstanceIdentifierTail(identifier,II_TO_FLOW_CAPABLE_NODE)){
package org.opendaylight.openflowplugin.applications.frsync;
import com.google.common.util.concurrent.ListenableFuture;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
* @param flowcapableNodePath path to openflow augmentation of node
* @param configTree configured node
* @param operationalTree device reflection
+ * @param dsType type of DS change
* @return synchronization outcome
*/
ListenableFuture<Boolean> syncup(InstanceIdentifier<FlowCapableNode> flowcapableNodePath,
- FlowCapableNode configTree, FlowCapableNode operationalTree) throws InterruptedException;
+ FlowCapableNode configTree, FlowCapableNode operationalTree,
+ LogicalDatastoreType dsType) throws InterruptedException;
}
import org.opendaylight.openflowplugin.applications.frsync.dao.FlowCapableNodeOdlDao;
import org.opendaylight.openflowplugin.applications.frsync.dao.FlowCapableNodeSnapshotDao;
import org.opendaylight.openflowplugin.applications.frsync.impl.strategy.SyncPlanPushStrategyFlatBatchImpl;
+import org.opendaylight.openflowplugin.applications.frsync.util.RetryRegistry;
import org.opendaylight.openflowplugin.applications.frsync.util.SemaphoreKeeperGuavaImpl;
import org.opendaylight.openflowplugin.common.wait.SimpleTaskRetryLooper;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flat.batch.service.rev160321.SalFlatBatchService;
private ListenerRegistration<NodeListener> dataTreeConfigChangeListener;
private ListenerRegistration<NodeListener> dataTreeOperationalChangeListener;
-
public ForwardingRulesSyncProvider(final BindingAwareBroker broker,
final DataBroker dataBroker,
final RpcConsumerRegistry rpcRegistry) {
.setFlatBatchService(flatBatchService)
.setTableForwarder(tableForwarder);
- final SyncReactorImpl syncReactorImpl = new SyncReactorImpl(syncPlanPushStrategy);
- final SyncReactor syncReactorGuard = new SyncReactorGuardDecorator(syncReactorImpl,
+ final RetryRegistry retryRegistry = new RetryRegistry();
+
+ final SyncReactor syncReactorImpl = new SyncReactorImpl(syncPlanPushStrategy);
+ final SyncReactor syncReactorRetry = new SyncReactorRetryDecorator(syncReactorImpl, retryRegistry);
+ final SyncReactor syncReactorGuard = new SyncReactorGuardDecorator(syncReactorRetry,
new SemaphoreKeeperGuavaImpl<InstanceIdentifier<FlowCapableNode>>(1, true));
- final SyncReactor cfgReactor = new SyncReactorFutureWithCompressionDecorator(syncReactorGuard, syncThreadPool);
- final SyncReactor operReactor = new SyncReactorFutureWithCompressionDecorator(syncReactorGuard, syncThreadPool);
+ final SyncReactor reactor = new SyncReactorFutureZipDecorator(syncReactorGuard, syncThreadPool);
final FlowCapableNodeSnapshotDao configSnapshot = new FlowCapableNodeSnapshotDao();
final FlowCapableNodeSnapshotDao operationalSnapshot = new FlowCapableNodeSnapshotDao();
final FlowCapableNodeDao operationalDao = new FlowCapableNodeCachedDao(operationalSnapshot,
new FlowCapableNodeOdlDao(dataService, LogicalDatastoreType.OPERATIONAL));
- final NodeListener<FlowCapableNode> nodeListenerConfig = new SimplifiedConfigListener(cfgReactor, configSnapshot, operationalDao);
- final NodeListener<Node> nodeListenerOperational = new SimplifiedOperationalListener(operReactor, operationalSnapshot, configDao);
+ final NodeListener<FlowCapableNode> nodeListenerConfig =
+ new SimplifiedConfigListener(reactor, configSnapshot, operationalDao);
+ final NodeListener<Node> nodeListenerOperational =
+ new SimplifiedOperationalRetryListener(reactor, operationalSnapshot, configDao, retryRegistry);
try {
SimpleTaskRetryLooper looper1 = new SimpleTaskRetryLooper(STARTUP_LOOP_TICK, STARTUP_LOOP_MAX_RETRIES);
final Optional<FlowCapableNode> operationalNode = operationalDao.loadByNodeId(nodeId);
if (!operationalNode.isPresent()) {
LOG.info("Skip syncup, {} operational is not present", nodeId.getValue());
- return Optional.absent();// we try to reconfigure switch is alive
+ return Optional.absent();
}
final DataObjectModification<FlowCapableNode> configModification = modification.getRootNode();
FlowCapableNode dataBefore, FlowCapableNode dataAfter, FlowCapableNode operationalNode)
throws InterruptedException {
LOG.trace("onNodeAdded {}", nodePath);
-
- final ListenableFuture<Boolean> endResult =
- reactor.syncup(nodePath, dataAfter, operationalNode);
+ final ListenableFuture<Boolean> endResult = reactor.syncup(nodePath, dataAfter, operationalNode, dsType());
return endResult;
}
FlowCapableNode dataBefore, FlowCapableNode dataAfter, FlowCapableNode operationalNodeNode)
throws InterruptedException {
LOG.trace("onNodeUpdated {}", nodePath);
-
- final ListenableFuture<Boolean> endResult =
- reactor.syncup(nodePath, dataAfter, dataBefore);
+ final ListenableFuture<Boolean> endResult = reactor.syncup(nodePath, dataAfter, dataBefore, dsType());
return endResult;
}
protected ListenableFuture<Boolean> onNodeDeleted(InstanceIdentifier<FlowCapableNode> nodePath,
FlowCapableNode dataBefore, FlowCapableNode operationalNode) throws InterruptedException {
LOG.trace("onNodeDeleted {}", nodePath);
-
- final ListenableFuture<Boolean> endResult =
- reactor.syncup(nodePath, null, dataBefore);
+ final ListenableFuture<Boolean> endResult = reactor.syncup(nodePath, null, dataBefore, dsType());
return endResult;
}
public class SimplifiedOperationalListener extends AbstractFrmSyncListener<Node> {
private static final Logger LOG = LoggerFactory.getLogger(SimplifiedOperationalListener.class);
- private final SyncReactor reactor;
- private FlowCapableNodeSnapshotDao operationalSnapshot;
- private FlowCapableNodeDao configDao;
+ protected final SyncReactor reactor;
+ protected final FlowCapableNodeSnapshotDao operationalSnapshot;
+ protected final FlowCapableNodeDao configDao;
- public SimplifiedOperationalListener(SyncReactor reactor,
- FlowCapableNodeSnapshotDao operationalSnapshot, FlowCapableNodeDao configDao) {
+ public SimplifiedOperationalListener(SyncReactor reactor, FlowCapableNodeSnapshotDao operationalSnapshot,
+ FlowCapableNodeDao configDao) {
this.reactor = reactor;
this.operationalSnapshot = operationalSnapshot;
this.configDao = configDao;
*/
protected Optional<ListenableFuture<Boolean>> processNodeModification(
DataTreeModification<Node> modification) throws ReadFailedException, InterruptedException {
- updateCache(modification);
- if (isAdd(modification) || isAddLogical(modification)) {
+ updateCache(modification);
+ if (isReconciliationNeeded(modification)) {
return reconciliation(modification);
}
- // TODO: else = explicit reconciliation required
-
return skipModification(modification);
}
* Remove if delete. Update only if FlowCapableNode Augmentation modified.
*
* @param modification Datastore modification
+ * @return true for cache update, false for cache remove
*/
- protected void updateCache(DataTreeModification<Node> modification) {
- try {
- boolean isDelete = isDelete(modification) || isDeleteLogical(modification);
- if (isDelete) {
- operationalSnapshot.updateCache(nodeId(modification), Optional.<FlowCapableNode>absent());
- return;
- }
-
- operationalSnapshot.updateCache(nodeId(modification), Optional.fromNullable(flowCapableNodeAfter(modification)));
- } catch(Exception e) {
- LOG.error("update cache failed {}", nodeId(modification), e);
+ protected boolean updateCache(DataTreeModification<Node> modification) {
+ if (isDelete(modification) || isDeleteLogical(modification)) {
+ operationalSnapshot.updateCache(nodeId(modification), Optional.<FlowCapableNode>absent());
+ return false;
}
+ operationalSnapshot.updateCache(nodeId(modification), Optional.fromNullable(flowCapableNodeAfter(modification)));
+ return true;
}
- protected Optional<ListenableFuture<Boolean>> skipModification(DataTreeModification<Node> modification) {
+ private Optional<ListenableFuture<Boolean>> skipModification(DataTreeModification<Node> modification) {
LOG.trace("Skipping Inventory Operational modification {}, before {}, after {}", nodeIdValue(modification),
modification.getRootNode().getDataBefore() == null ? "null" : "nonnull",
modification.getRootNode().getDataAfter() == null ? "null" : "nonnull");
- return Optional.absent();// skip otherwise event
+ return Optional.absent();
}
/**
* ModificationType.DELETE
*/
- protected boolean isDelete(DataTreeModification<Node> modification) {
+ private boolean isDelete(DataTreeModification<Node> modification) {
if (ModificationType.DELETE == modification.getRootNode().getModificationType()) {
LOG.trace("Delete {} (physical)", nodeIdValue(modification));
return true;
/**
* All connectors disappeared from operational store (logical delete).
*/
- protected boolean isDeleteLogical(DataTreeModification<Node> modification) {
+ private boolean isDeleteLogical(DataTreeModification<Node> modification) {
final DataObjectModification<Node> rootNode = modification.getRootNode();
if (!safeConnectorsEmpty(rootNode.getDataBefore()) && safeConnectorsEmpty(rootNode.getDataAfter())) {
LOG.trace("Delete {} (logical)", nodeIdValue(modification));
return false;
}
- protected boolean isAdd(DataTreeModification<Node> modification) {
+ private boolean isAdd(DataTreeModification<Node> modification) {
final DataObjectModification<Node> rootNode = modification.getRootNode();
final Node dataAfter = rootNode.getDataAfter();
final Node dataBefore = rootNode.getDataBefore();
/**
* All connectors appeared in operational store (logical add).
*/
- protected boolean isAddLogical(DataTreeModification<Node> modification) {
+ private boolean isAddLogical(DataTreeModification<Node> modification) {
final DataObjectModification<Node> rootNode = modification.getRootNode();
if (safeConnectorsEmpty(rootNode.getDataBefore()) && !safeConnectorsEmpty(rootNode.getDataAfter())) {
LOG.trace("Add {} (logical)", nodeIdValue(modification));
return false;
}
- protected Optional<ListenableFuture<Boolean>> reconciliation(
- DataTreeModification<Node> modification) throws InterruptedException {
- final NodeId nodeId = nodeId(modification);
-
- LOG.debug("Reconciliation: {}", nodeId.getValue());
+ protected boolean isReconciliationNeeded(DataTreeModification<Node> modification) {
+ return isAdd(modification) || isAddLogical(modification);
+ }
+ private Optional<ListenableFuture<Boolean>> reconciliation(DataTreeModification<Node> modification) throws InterruptedException {
+ final NodeId nodeId = nodeId(modification);
final Optional<FlowCapableNode> nodeConfiguration = configDao.loadByNodeId(nodeId);
- final InstanceIdentifier<FlowCapableNode> nodePath = InstanceIdentifier.create(Nodes.class)
- .child(Node.class, new NodeKey(nodeId(modification))).augmentation(FlowCapableNode.class);
- if (nodeConfiguration.isPresent())
- return Optional.of(reactor.syncup(nodePath, nodeConfiguration.get(), flowCapableNodeAfter(modification)));
- else
+ if (nodeConfiguration.isPresent()) {
+ LOG.debug("Reconciliation: {}", nodeId.getValue());
+ final InstanceIdentifier<FlowCapableNode> nodePath = InstanceIdentifier.create(Nodes.class)
+ .child(Node.class, new NodeKey(nodeId(modification))).augmentation(FlowCapableNode.class);
+ return Optional.of(reactor.syncup(nodePath, nodeConfiguration.get(), flowCapableNodeAfter(modification), dsType()));
+ } else {
return skipModification(modification);
+ }
}
static FlowCapableNode flowCapableNodeAfter(DataTreeModification<Node> modification) {
final DataObjectModification<Node> rootNode = modification.getRootNode();
final Node dataAfter = rootNode.getDataAfter();
-
if (dataAfter != null) {
return dataAfter.getId();
}
--- /dev/null
+/**
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.openflowplugin.applications.frsync.impl;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
+import org.opendaylight.openflowplugin.applications.frsync.SyncReactor;
+import org.opendaylight.openflowplugin.applications.frsync.dao.FlowCapableNodeDao;
+import org.opendaylight.openflowplugin.applications.frsync.dao.FlowCapableNodeSnapshotDao;
+import org.opendaylight.openflowplugin.applications.frsync.util.PathUtil;
+import org.opendaylight.openflowplugin.applications.frsync.util.RetryRegistry;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableStatisticsGatheringStatus;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusEnd;
+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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Modified {@link SimplifiedOperationalListener} for usage of retry mechanism.
+ */
+public class SimplifiedOperationalRetryListener extends SimplifiedOperationalListener {
+
+ private static final Logger LOG = LoggerFactory.getLogger(SimplifiedOperationalRetryListener.class);
+ private final RetryRegistry retryRegistry;
+
+ public SimplifiedOperationalRetryListener(SyncReactor reactor, FlowCapableNodeSnapshotDao operationalSnapshot,
+ FlowCapableNodeDao configDao, RetryRegistry retryRegistry) {
+ super(reactor, operationalSnapshot, configDao);
+ this.retryRegistry = retryRegistry;
+ }
+
+ /**
+ * Adding condition check for retry.
+ *
+ * @param modification operational datastore modification
+ * @return true if reconciliation is needed, false otherwise
+ */
+ protected boolean isReconciliationNeeded(DataTreeModification<Node> modification) {
+ return super.isReconciliationNeeded(modification) || isRegisteredAndConsistentForRetry(modification);
+ }
+
+ /**
+ * If node is removed unregister for retry in addition.
+ *
+ * @param modification operational datastore modification
+ * @return true for cache update, false for cache remove and retry unregister
+ */
+ protected boolean updateCache(DataTreeModification<Node> modification) {
+ boolean nodeUpdated = super.updateCache(modification);
+ if (!nodeUpdated) { // node removed if not updated
+ retryRegistry.unregisterIfRegistered(nodeId(modification));
+ }
+ return nodeUpdated;
+ }
+
+ /**
+ * Check if retry should be proceeded.
+ *
+ * @param modification operational modification
+ * @return true if device is registered for retry and actual modification is consistent, false otherwise
+ */
+ @VisibleForTesting
+ boolean isRegisteredAndConsistentForRetry(DataTreeModification<Node> modification) {
+ final NodeId nodeId = PathUtil.digNodeId(modification.getRootPath().getRootIdentifier());
+
+ if (!retryRegistry.isRegistered(nodeId)) {
+ return false;
+ }
+
+ final FlowCapableStatisticsGatheringStatus gatheringStatus = modification.getRootNode().getDataAfter()
+ .getAugmentation(FlowCapableStatisticsGatheringStatus.class);
+
+ if (gatheringStatus == null) {
+ LOG.trace("Statistics gathering never started for: {}", nodeId.getValue());
+ return false;
+ }
+
+ final SnapshotGatheringStatusEnd gatheringStatusEnd = gatheringStatus.getSnapshotGatheringStatusEnd();
+
+ if (gatheringStatusEnd == null) {
+ LOG.trace("Statistics gathering is not over yet for: {}", nodeId.getValue());
+ return false;
+ }
+
+ if (!gatheringStatusEnd.isSucceeded()) {
+ LOG.debug("Statistics gathering was not successful for: {}", nodeId.getValue());
+ return false;
+ }
+
+ try {
+ Date timestampOfRegistration = retryRegistry.getRegistration(nodeId);;
+ final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(RetryRegistry.DATE_AND_TIME_FORMAT);
+ Date timestampOfStatistics = simpleDateFormat.parse(gatheringStatusEnd.getEnd().getValue());
+ if (timestampOfStatistics.after(timestampOfRegistration)) {
+ LOG.debug("Fresh operational present for: {} -> going retry!", nodeId.getValue());
+ return true;
+ }
+ } catch (ParseException e) {
+ LOG.error("Timestamp parsing error {}", e);
+ }
+ LOG.debug("Fresh operational not present for: {}", nodeId.getValue());
+ return false;
+ }
+}
import java.util.concurrent.Callable;\r
import java.util.concurrent.TimeUnit;\r
import java.util.concurrent.TimeoutException;\r
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;\r
import org.opendaylight.openflowplugin.applications.frsync.SyncReactor;\r
import org.opendaylight.openflowplugin.applications.frsync.util.PathUtil;\r
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;\r
}\r
\r
public ListenableFuture<Boolean> syncup(final InstanceIdentifier<FlowCapableNode> flowcapableNodePath,\r
- final FlowCapableNode configTree, final FlowCapableNode operationalTree) throws InterruptedException {\r
+ final FlowCapableNode configTree, final FlowCapableNode operationalTree,\r
+ final LogicalDatastoreType dsType) throws InterruptedException {\r
final NodeId nodeId = PathUtil.digNodeId(flowcapableNodePath);\r
LOG.trace("syncup {}", nodeId.getValue());\r
\r
final String oldThreadName = updateThreadName(nodeId);\r
\r
try {\r
- final Boolean ret = doSyncupInFuture(flowcapableNodePath, configTree, operationalTree)\r
+ final Boolean ret = doSyncupInFuture(flowcapableNodePath, configTree, operationalTree, dsType)\r
.get(10000, TimeUnit.MILLISECONDS);\r
LOG.trace("ret {} {}", nodeId.getValue(), ret);\r
return true;\r
}\r
}\r
});\r
- \r
+\r
return syncup;\r
}\r
\r
protected ListenableFuture<Boolean> doSyncupInFuture(final InstanceIdentifier<FlowCapableNode> flowcapableNodePath,\r
- final FlowCapableNode configTree, final FlowCapableNode operationalTree)\r
- throws InterruptedException {\r
+ final FlowCapableNode configTree, final FlowCapableNode operationalTree,\r
+ final LogicalDatastoreType dsType) throws InterruptedException {\r
final NodeId nodeId = PathUtil.digNodeId(flowcapableNodePath);\r
LOG.trace("doSyncupInFuture {}", nodeId.getValue());\r
\r
- return delegate.syncup(flowcapableNodePath, configTree, operationalTree);\r
+ return delegate.syncup(flowcapableNodePath, configTree, operationalTree, dsType);\r
}\r
\r
static String threadName() {\r
+++ /dev/null
-/**\r
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-\r
-package org.opendaylight.openflowplugin.applications.frsync.impl;\r
-\r
-import com.google.common.util.concurrent.Futures;\r
-import com.google.common.util.concurrent.ListenableFuture;\r
-import com.google.common.util.concurrent.ListeningExecutorService;\r
-import java.util.HashMap;\r
-import java.util.Map;\r
-import java.util.concurrent.Semaphore;\r
-import javax.annotation.concurrent.GuardedBy;\r
-import org.apache.commons.lang3.tuple.Pair;\r
-import org.opendaylight.openflowplugin.applications.frsync.SyncReactor;\r
-import org.opendaylight.openflowplugin.applications.frsync.util.PathUtil;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;\r
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;\r
-import org.slf4j.Logger;\r
-import org.slf4j.LoggerFactory;\r
-\r
-/**\r
- * Enriches {@link SyncReactorFutureDecorator} with state compression.\r
- */\r
-public class SyncReactorFutureWithCompressionDecorator extends SyncReactorFutureDecorator {\r
-\r
- private static final Logger LOG = LoggerFactory.getLogger(SyncReactorFutureWithCompressionDecorator.class);\r
-\r
- @GuardedBy("compressionGuard")\r
- final Map<InstanceIdentifier<FlowCapableNode>, Pair<FlowCapableNode, FlowCapableNode>> compressionQueue =\r
- new HashMap<>();\r
- final Semaphore compressionGuard = new Semaphore(1, false);\r
-\r
- public SyncReactorFutureWithCompressionDecorator(SyncReactor delegate, ListeningExecutorService executorService) {\r
- super(delegate, executorService);\r
- }\r
-\r
- public ListenableFuture<Boolean> syncup(final InstanceIdentifier<FlowCapableNode> flowcapableNodePath,\r
- final FlowCapableNode configTree, final FlowCapableNode operationalTree) throws InterruptedException {\r
- final NodeId nodeId = PathUtil.digNodeId(flowcapableNodePath);\r
- LOG.trace("syncup {}", nodeId.getValue());\r
-\r
- try {\r
- compressionGuard.acquire();\r
-\r
- final boolean newFutureNecessary = updateCompressionState(flowcapableNodePath, configTree, operationalTree);\r
- if (newFutureNecessary) {\r
- super.syncup(flowcapableNodePath, configTree, operationalTree);\r
- }\r
- return Futures.immediateFuture(true);\r
- } finally {\r
- compressionGuard.release();\r
- }\r
- }\r
-\r
- protected ListenableFuture<Boolean> doSyncupInFuture(final InstanceIdentifier<FlowCapableNode> flowcapableNodePath,\r
- final FlowCapableNode configTree, final FlowCapableNode operationalTree)\r
- throws InterruptedException {\r
- final NodeId nodeId = PathUtil.digNodeId(flowcapableNodePath);\r
- LOG.trace("doSyncupInFuture {}", nodeId.getValue());\r
-\r
- final Pair<FlowCapableNode, FlowCapableNode> lastCompressionState =\r
- removeLastCompressionState(flowcapableNodePath);\r
- if (lastCompressionState == null) {\r
- return Futures.immediateFuture(true);\r
- } else {\r
- return super.doSyncupInFuture(flowcapableNodePath,\r
- lastCompressionState.getLeft(), lastCompressionState.getRight());\r
- }\r
- }\r
-\r
- protected boolean updateCompressionState(final InstanceIdentifier<FlowCapableNode> flowcapableNodePath,\r
- final FlowCapableNode configTree, final FlowCapableNode operationalTree) {\r
- final Pair<FlowCapableNode, FlowCapableNode> previous = compressionQueue.get(flowcapableNodePath);\r
- if (previous != null) {\r
- final FlowCapableNode previousOperational = previous.getRight();\r
- compressionQueue.put(flowcapableNodePath, Pair.of(configTree, previousOperational));\r
- return false;\r
- } else {\r
- compressionQueue.put(flowcapableNodePath, Pair.of(configTree, operationalTree));\r
- return true;\r
- }\r
- }\r
-\r
- protected Pair<FlowCapableNode/* config */, FlowCapableNode/* operational */> removeLastCompressionState(\r
- final InstanceIdentifier<FlowCapableNode> flowcapableNodePath) {\r
- try {\r
- try {\r
- compressionGuard.acquire();\r
- } catch (InterruptedException e) {\r
- return null;\r
- }\r
-\r
- return compressionQueue.remove(flowcapableNodePath);\r
- } finally {\r
- compressionGuard.release();\r
- }\r
- }\r
-}\r
--- /dev/null
+/**
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.openflowplugin.applications.frsync.impl;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Semaphore;
+import javax.annotation.concurrent.GuardedBy;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.openflowplugin.applications.frsync.SyncReactor;
+import org.opendaylight.openflowplugin.applications.frsync.util.PathUtil;
+import org.opendaylight.openflowplugin.applications.frsync.util.ZipQueueEntry;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Enriches {@link SyncReactorFutureDecorator} with state compression.
+ */
+public class SyncReactorFutureZipDecorator extends SyncReactorFutureDecorator {
+
+ private static final Logger LOG = LoggerFactory.getLogger(SyncReactorFutureZipDecorator.class);
+
+ @GuardedBy("compressionGuard")
+ protected final Map<InstanceIdentifier<FlowCapableNode>, ZipQueueEntry> compressionQueue = new HashMap<>();
+ protected final Semaphore compressionGuard = new Semaphore(1, false);
+
+ public SyncReactorFutureZipDecorator(SyncReactor delegate, ListeningExecutorService executorService) {
+ super(delegate, executorService);
+ }
+
+ public ListenableFuture<Boolean> syncup(final InstanceIdentifier<FlowCapableNode> flowcapableNodePath,
+ final FlowCapableNode configTree, final FlowCapableNode operationalTree,
+ final LogicalDatastoreType dsType) throws InterruptedException {
+ final NodeId nodeId = PathUtil.digNodeId(flowcapableNodePath);
+ LOG.trace("syncup zip {}", nodeId.getValue());
+
+ try {
+ compressionGuard.acquire();
+
+ final boolean newFutureNecessary = updateCompressionState(flowcapableNodePath, configTree, operationalTree, dsType);
+ if (newFutureNecessary) {
+ super.syncup(flowcapableNodePath, configTree, operationalTree, dsType);
+ }
+ return Futures.immediateFuture(true);
+ } finally {
+ compressionGuard.release();
+ }
+ }
+
+ protected ListenableFuture<Boolean> doSyncupInFuture(final InstanceIdentifier<FlowCapableNode> flowcapableNodePath,
+ final FlowCapableNode configTree, final FlowCapableNode operationalTree,
+ final LogicalDatastoreType dsType) throws InterruptedException {
+ final NodeId nodeId = PathUtil.digNodeId(flowcapableNodePath);
+ LOG.trace("doSyncupInFuture zip {}", nodeId.getValue());
+
+ final ZipQueueEntry lastCompressionState = removeLastCompressionState(flowcapableNodePath);
+ if (lastCompressionState == null) {
+ return Futures.immediateFuture(true);
+ } else {
+ return super.doSyncupInFuture(flowcapableNodePath,
+ lastCompressionState.getLeft(), lastCompressionState.getRight(), dsType);
+ }
+ }
+
+ /**
+ * If there is config delta in compression queue for the device and new configuration is coming,
+ * update its zip queue entry. Create/replace zip queue entry for the device with operational delta otherwise.
+ */
+ protected boolean updateCompressionState(final InstanceIdentifier<FlowCapableNode> flowcapableNodePath,
+ final FlowCapableNode configTree, final FlowCapableNode operationalTree,
+ final LogicalDatastoreType dsType) {
+ final ZipQueueEntry previousEntry = compressionQueue.get(flowcapableNodePath);
+
+ if (previousEntry != null && dsType == LogicalDatastoreType.CONFIGURATION
+ && previousEntry.getDsType() == LogicalDatastoreType.CONFIGURATION) {
+ putOptimizedConfigDelta(flowcapableNodePath, configTree, previousEntry);
+ } else {
+ putLatestOperationalDelta(flowcapableNodePath, configTree, operationalTree, dsType);
+ }
+ return previousEntry == null;
+ }
+
+ private void putOptimizedConfigDelta(InstanceIdentifier<FlowCapableNode> flowcapableNodePath, FlowCapableNode configTree,
+ ZipQueueEntry previous) {
+ compressionQueue.put(flowcapableNodePath, new ZipQueueEntry(configTree, previous.getRight(), previous.getDsType()));
+ }
+
+ private void putLatestOperationalDelta(InstanceIdentifier<FlowCapableNode> flowcapableNodePath, FlowCapableNode configTree,
+ FlowCapableNode operationalTree, LogicalDatastoreType dsType) {
+ compressionQueue.put(flowcapableNodePath, new ZipQueueEntry(configTree, operationalTree, dsType));
+ }
+
+ private ZipQueueEntry removeLastCompressionState(
+ final InstanceIdentifier<FlowCapableNode> flowcapableNodePath) {
+ try {
+ try {
+ compressionGuard.acquire();
+ } catch (InterruptedException e) {
+ return null;
+ }
+
+ return compressionQueue.remove(flowcapableNodePath);
+ } finally {
+ compressionGuard.release();
+ }
+ }
+
+ @VisibleForTesting
+ Map<InstanceIdentifier<FlowCapableNode>, ZipQueueEntry> getCompressionQueue() {
+ return compressionQueue;
+ }
+}
\ No newline at end of file
import java.util.concurrent.Semaphore;\r
import java.util.concurrent.TimeUnit;\r
import javax.annotation.Nullable;\r
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;\r
import org.opendaylight.openflowplugin.applications.frsync.SemaphoreKeeper;\r
import org.opendaylight.openflowplugin.applications.frsync.SyncReactor;\r
import org.opendaylight.openflowplugin.applications.frsync.util.PathUtil;\r
}\r
\r
public ListenableFuture<Boolean> syncup(final InstanceIdentifier<FlowCapableNode> flowcapableNodePath,\r
- final FlowCapableNode configTree, final FlowCapableNode operationalTree) throws InterruptedException {\r
+ final FlowCapableNode configTree, final FlowCapableNode operationalTree,\r
+ final LogicalDatastoreType dsType) throws InterruptedException {\r
final NodeId nodeId = PathUtil.digNodeId(flowcapableNodePath);\r
LOG.trace("syncup {}", nodeId.getValue());\r
\r
formatNanos(stampAfterGuard - stampBeforeGuard),\r
guard, threadName());\r
}\r
- \r
+\r
final ListenableFuture<Boolean> endResult =\r
- delegate.syncup(flowcapableNodePath, configTree, operationalTree);//TODO handle InteruptedException\r
- \r
+ delegate.syncup(flowcapableNodePath, configTree, operationalTree, dsType);//TODO handle InteruptedException\r
+\r
Futures.addCallback(endResult, new FutureCallback<Boolean>() {\r
@Override\r
public void onSuccess(@Nullable final Boolean result) {\r
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.openflowplugin.applications.frsync.SyncPlanPushStrategy;
import org.opendaylight.openflowplugin.applications.frsync.SyncReactor;
import org.opendaylight.openflowplugin.applications.frsync.impl.strategy.SynchronizationDiffInput;
@Override
public ListenableFuture<Boolean> syncup(final InstanceIdentifier<FlowCapableNode> nodeIdent,
- final FlowCapableNode configTree, final FlowCapableNode operationalTree) {
+ final FlowCapableNode configTree, final FlowCapableNode operationalTree,
+ final LogicalDatastoreType dsType) {
LOG.trace("syncup {} cfg:{} oper:{}", nodeIdent, configTree == null ? "is null" : "non null", operationalTree == null ? "is null" : "non null");
final SyncCrudCounters counters = new SyncCrudCounters();
);
}
+ LOG.trace("syncup errors: {}", input.getErrors());
return input.isSuccessful();
}
});
--- /dev/null
+/**
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.openflowplugin.applications.frsync.impl;
+
+import com.google.common.base.Function;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.openflowplugin.applications.frsync.SyncReactor;
+import org.opendaylight.openflowplugin.applications.frsync.util.PathUtil;
+import org.opendaylight.openflowplugin.applications.frsync.util.RetryRegistry;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Adding retry mechanism in case of unsuccessful syncup.
+ */
+public class SyncReactorRetryDecorator implements SyncReactor{
+
+ private static final Logger LOG = LoggerFactory.getLogger(SyncReactorRetryDecorator.class);
+
+ private final SyncReactor delegate;
+ private final RetryRegistry retryRegistry;
+
+ public SyncReactorRetryDecorator (final SyncReactor delegate, RetryRegistry retryRegistry) {
+ this.delegate = delegate;
+ this.retryRegistry = retryRegistry;
+ }
+
+ public ListenableFuture<Boolean> syncup (final InstanceIdentifier<FlowCapableNode> flowcapableNodePath,
+ final FlowCapableNode configTree, final FlowCapableNode operationalTree,
+ final LogicalDatastoreType dsType) throws InterruptedException {
+
+ final NodeId nodeId = PathUtil.digNodeId(flowcapableNodePath);
+ LOG.trace("syncup retry {}", nodeId.getValue());
+
+ if (dsType == LogicalDatastoreType.CONFIGURATION && retryRegistry.isRegistered(nodeId)) {
+ LOG.trace("Config change ignored because device is in retry [{}]", nodeId);
+ return Futures.immediateFuture(Boolean.FALSE);
+ }
+
+ ListenableFuture<Boolean> syncupResult = delegate.syncup(flowcapableNodePath, configTree, operationalTree, dsType);
+
+ return Futures.transform(syncupResult, new Function<Boolean, Boolean>() {
+ @Override
+ public Boolean apply(Boolean result) {
+ LOG.trace("syncup ret in retry {}", result);
+ if (result) {
+ retryRegistry.unregisterIfRegistered(nodeId);
+ return true;
+ } else {
+ retryRegistry.register(nodeId);
+ // TODO elicit statistics gathering if not running actually
+ // triggerStatisticsGathering(nodeId);
+ return false;
+ }
+ }
+ });
+ }
+}
--- /dev/null
+/**
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.openflowplugin.applications.frsync.util;
+
+import java.util.Date;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Holder of registration request for fresh operational.
+ */
+public class RetryRegistry {
+
+ private static final Logger LOG = LoggerFactory.getLogger(RetryRegistry.class);
+ private final Map<NodeId, Date> registration = new ConcurrentHashMap<>();
+ public static final String DATE_AND_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
+
+ public Date register(NodeId nodeId) {
+ Date timestamp = new Date();
+ registration.put(nodeId, timestamp);
+ if (timestamp != null) {
+ LOG.debug("Registered for next consistent operational: {}", nodeId.getValue());
+ }
+ return timestamp;
+ }
+
+ public Date unregisterIfRegistered(NodeId nodeId) {
+ Date timestamp = registration.remove(nodeId);
+ if (timestamp != null) {
+ LOG.debug("Unregistered for next consistent operational: {}", nodeId.getValue());
+ }
+ return timestamp;
+ }
+
+ public boolean isRegistered(NodeId nodeId) {
+ return registration.get(nodeId) != null;
+ }
+
+ public Date getRegistration(NodeId nodeId) {
+ return registration.get(nodeId);
+ }
+
+}
--- /dev/null
+/**
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.openflowplugin.applications.frsync.util;
+
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
+
+/**
+ * Simple compression queue entry for {@link org.opendaylight.openflowplugin.applications.frsync.impl.SyncReactorFutureZipDecorator}.
+ */
+public class ZipQueueEntry {
+ private FlowCapableNode after;
+ private FlowCapableNode before;
+ private LogicalDatastoreType dsTypeBefore;
+
+ public ZipQueueEntry(final FlowCapableNode after, final FlowCapableNode before, final LogicalDatastoreType dsTypeBefore) {
+ this.after = after;
+ this.before = before;
+ this.dsTypeBefore = dsTypeBefore;
+
+ }
+
+ public FlowCapableNode getLeft() {
+ return after;
+ }
+
+ public FlowCapableNode getRight() {
+ return before;
+ }
+
+ public LogicalDatastoreType getDsType() {
+ return dsTypeBefore;
+ }
+
+}
@RunWith(MockitoJUnitRunner.class)
public class SimplifiedConfigListenerTest {
+ private static final NodeId NODE_ID = new NodeId("testNode");
+ private InstanceIdentifier<FlowCapableNode> fcNodePath;
+ private SimplifiedConfigListener nodeListenerConfig;
+ private LogicalDatastoreType dsType = LogicalDatastoreType.CONFIGURATION;
+
@Mock
private SyncReactor reactor;
@Mock
- private DataBroker db;
+ private ReadOnlyTransaction roTx;
@Mock
private DataTreeModification<FlowCapableNode> dataTreeModification;
@Mock
- private ReadOnlyTransaction roTx;
- @Mock
private DataObjectModification<FlowCapableNode> configModification;
-
- private InstanceIdentifier<FlowCapableNode> nodePath;
- private SimplifiedConfigListener nodeListenerConfig;
+ @Mock
+ private FlowCapableNode dataBefore;
+ @Mock
+ private FlowCapableNode dataAfter;
@Before
public void setUp() throws Exception {
- final FlowCapableNodeSnapshotDao configSnaphot = new FlowCapableNodeSnapshotDao();
- final FlowCapableNodeSnapshotDao operationalSnaphot = new FlowCapableNodeSnapshotDao();
- final FlowCapableNodeDao operationalDao = new FlowCapableNodeCachedDao(operationalSnaphot,
+ final DataBroker db = Mockito.mock(DataBroker.class);
+ final FlowCapableNodeSnapshotDao configSnapshot = new FlowCapableNodeSnapshotDao();
+ final FlowCapableNodeSnapshotDao operationalSnapshot = new FlowCapableNodeSnapshotDao();
+ final FlowCapableNodeDao operationalDao = new FlowCapableNodeCachedDao(operationalSnapshot,
new FlowCapableNodeOdlDao(db, LogicalDatastoreType.OPERATIONAL));
-
- nodeListenerConfig = new SimplifiedConfigListener(reactor, configSnaphot, operationalDao);
- nodePath = InstanceIdentifier.create(Nodes.class)
- .child(Node.class, new NodeKey(new NodeId("testNode")))
+ nodeListenerConfig = new SimplifiedConfigListener(reactor, configSnapshot, operationalDao);
+ fcNodePath = InstanceIdentifier.create(Nodes.class).child(Node.class, new NodeKey(NODE_ID))
.augmentation(FlowCapableNode.class);
+
+ final DataTreeIdentifier<FlowCapableNode> dataTreeIdentifier =
+ new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, fcNodePath);
+
+ Mockito.when(db.newReadOnlyTransaction()).thenReturn(roTx);
+ Mockito.when(dataTreeModification.getRootPath()).thenReturn(dataTreeIdentifier);
+ Mockito.when(dataTreeModification.getRootNode()).thenReturn(configModification);
+ Mockito.when(reactor.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(), Matchers.<FlowCapableNode>any(),
+ Matchers.<FlowCapableNode>any(), Matchers.<LogicalDatastoreType>any())).thenReturn(Futures.immediateFuture(Boolean.TRUE));
}
@Test
}
@Test
- public void testOnDataTreeChanged() throws Exception {
- final FlowCapableNode configTree = Mockito.mock(FlowCapableNode.class);
- final FlowCapableNode operationalTree = Mockito.mock(FlowCapableNode.class);
- final DataTreeIdentifier<FlowCapableNode> dataTreeIdentifier =
- new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, nodePath);
+ public void testOnDataTreeChangedSyncupAdd() throws InterruptedException {
+ Mockito.when(roTx.read(LogicalDatastoreType.OPERATIONAL, fcNodePath))
+ .thenReturn(Futures.immediateCheckedFuture(Optional.of(dataBefore)));
+ Mockito.when(configModification.getDataAfter()).thenReturn(dataAfter);
- Mockito.when(dataTreeModification.getRootPath()).thenReturn(dataTreeIdentifier);
- Mockito.when(dataTreeModification.getRootNode()).thenReturn(configModification);
- Mockito.when(configModification.getDataAfter()).thenReturn(configTree);
- Mockito.when(db.newReadOnlyTransaction()).thenReturn(roTx);
- Mockito.doReturn(Futures.immediateCheckedFuture(Optional.of(operationalTree))).when(
- roTx).read(LogicalDatastoreType.OPERATIONAL, nodePath);
- Mockito.when(reactor.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(),Matchers.<FlowCapableNode>any(),Matchers.<FlowCapableNode>any()))
- .thenReturn(Futures.immediateFuture(Boolean.TRUE));
+ nodeListenerConfig.onDataTreeChanged(Collections.singleton(dataTreeModification));
+
+ Mockito.verify(reactor).syncup(fcNodePath, dataAfter, dataBefore, dsType);
+ Mockito.verifyNoMoreInteractions(reactor);
+ Mockito.verify(roTx).close();
+ }
+
+ @Test
+ public void testOnDataTreeChangedSyncupUpdate() throws InterruptedException {
+ Mockito.when(roTx.read(LogicalDatastoreType.OPERATIONAL, fcNodePath))
+ .thenReturn(Futures.immediateCheckedFuture(Optional.of(dataBefore)));
+ Mockito.when(configModification.getDataBefore()).thenReturn(dataBefore);
+ Mockito.when(configModification.getDataAfter()).thenReturn(dataAfter);
+
+ nodeListenerConfig.onDataTreeChanged(Collections.singleton(dataTreeModification));
+
+ Mockito.verify(reactor).syncup(fcNodePath, dataAfter, dataBefore, dsType);
+ Mockito.verifyNoMoreInteractions(reactor);
+ Mockito.verify(roTx).close();
+ }
+
+ @Test
+ public void testOnDataTreeChangedSyncupDelete() throws InterruptedException {
+ Mockito.when(roTx.read(LogicalDatastoreType.OPERATIONAL, fcNodePath))
+ .thenReturn(Futures.immediateCheckedFuture(Optional.of(dataBefore)));
+ Mockito.when(configModification.getDataBefore()).thenReturn(dataBefore);
+
+ nodeListenerConfig.onDataTreeChanged(Collections.singleton(dataTreeModification));
+
+ Mockito.verify(reactor).syncup(fcNodePath, null, dataBefore, dsType);
+ Mockito.verifyNoMoreInteractions(reactor);
+ Mockito.verify(roTx).close();
+ }
+
+ @Test
+ public void testOnDataTreeChangedSkip() {
+ Mockito.when(roTx.read(LogicalDatastoreType.OPERATIONAL, fcNodePath)).
+ thenReturn(Futures.immediateCheckedFuture(Optional.absent()));
nodeListenerConfig.onDataTreeChanged(Collections.singleton(dataTreeModification));
- Mockito.verify(reactor).syncup(nodePath, configTree, operationalTree);
+ Mockito.verifyZeroInteractions(reactor);
Mockito.verify(roTx).close();
}
}
\ No newline at end of file
import com.google.common.base.Optional;
import com.google.common.util.concurrent.Futures;
import java.util.Collections;
+import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.runners.MockitoJUnitRunner;
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.DataObjectModification.ModificationType;
import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
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.yangtools.yang.binding.InstanceIdentifier;
@RunWith(MockitoJUnitRunner.class)
public class SimplifiedOperationalListenerTest {
- public static final NodeId NODE_ID = new NodeId("testNode");
+ private static final NodeId NODE_ID = new NodeId("testNode");
+ private InstanceIdentifier<FlowCapableNode> fcNodePath;
+ private SimplifiedOperationalListener nodeListenerOperational;
+ private final LogicalDatastoreType dsType = LogicalDatastoreType.OPERATIONAL;
+
@Mock
private SyncReactor reactor;
@Mock
@Mock
private DataTreeModification<Node> dataTreeModification;
@Mock
+ private DataObjectModification<Node> operationalModification;
+ @Mock
private FlowCapableNode configNode;
@Mock
+ private Node operationalNode;
+ @Mock
private FlowCapableNode fcOperationalNode;
- private InstanceIdentifier<Node> nodePath;
- private InstanceIdentifier<FlowCapableNode> fcNodePath;
- private SimplifiedOperationalListener nodeListenerOperational;
-
@Before
public void setUp() throws Exception {
final DataBroker db = Mockito.mock(DataBroker.class);
- final DataObjectModification<Node> operationalModification = Mockito.mock(DataObjectModification.class);
- final Node operationalNode = Mockito.mock(Node.class);
-
- final FlowCapableNodeSnapshotDao configSnaphot = new FlowCapableNodeSnapshotDao();
- final FlowCapableNodeSnapshotDao operationalSnaphot = new FlowCapableNodeSnapshotDao();
- final FlowCapableNodeDao configDao = new FlowCapableNodeCachedDao(configSnaphot,
+ final FlowCapableNodeSnapshotDao configSnapshot = new FlowCapableNodeSnapshotDao();
+ final FlowCapableNodeSnapshotDao operationalSnapshot = new FlowCapableNodeSnapshotDao();
+ final FlowCapableNodeDao configDao = new FlowCapableNodeCachedDao(configSnapshot,
new FlowCapableNodeOdlDao(db, LogicalDatastoreType.CONFIGURATION));
- nodeListenerOperational = new SimplifiedOperationalListener(reactor, operationalSnaphot, configDao);
- nodePath = InstanceIdentifier.create(Nodes.class).child(Node.class, new NodeKey(NODE_ID));
+
+ nodeListenerOperational = new SimplifiedOperationalListener(reactor, operationalSnapshot, configDao);
+ InstanceIdentifier<Node> nodePath = InstanceIdentifier.create(Nodes.class).child(Node.class, new NodeKey(NODE_ID));
fcNodePath = nodePath.augmentation(FlowCapableNode.class);
final DataTreeIdentifier<Node> dataTreeIdentifier =
new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, nodePath);
- Mockito.when(operationalNode.getId()).thenReturn(NODE_ID);
Mockito.when(db.newReadOnlyTransaction()).thenReturn(roTx);
- Mockito.when(operationalNode.getAugmentation(FlowCapableNode.class)).thenReturn(fcOperationalNode);
+ Mockito.when(operationalNode.getId()).thenReturn(NODE_ID);
Mockito.when(dataTreeModification.getRootPath()).thenReturn(dataTreeIdentifier);
Mockito.when(dataTreeModification.getRootNode()).thenReturn(operationalModification);
- Mockito.when(operationalModification.getDataAfter()).thenReturn(operationalNode);
+ Mockito.when(operationalNode.getAugmentation(FlowCapableNode.class)).thenReturn(fcOperationalNode);
}
@Test
}
@Test
- public void testOnDataTreeChangedSyncup() throws Exception {
- Mockito.when(reactor.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(),Matchers.<FlowCapableNode>any(),
- Matchers.<FlowCapableNode>any())).thenReturn(Futures.immediateFuture(Boolean.TRUE));
+ public void testOnDataTreeChangedSyncupAdd() throws InterruptedException {
Mockito.when(roTx.read(LogicalDatastoreType.CONFIGURATION, fcNodePath))
.thenReturn(Futures.immediateCheckedFuture(Optional.of(configNode)));
+ Mockito.when(reactor.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(), Matchers.<FlowCapableNode>any(),
+ Matchers.<FlowCapableNode>any(), Matchers.<LogicalDatastoreType>any())).thenReturn(Futures.immediateFuture(Boolean.TRUE));
+ Mockito.when(operationalModification.getDataAfter()).thenReturn(operationalNode);
nodeListenerOperational.onDataTreeChanged(Collections.singleton(dataTreeModification));
- Mockito.verify(reactor, Mockito.times(1)).syncup(fcNodePath, configNode, fcOperationalNode);
+ Mockito.verify(reactor).syncup(fcNodePath, configNode, fcOperationalNode, dsType);
+ Mockito.verifyNoMoreInteractions(reactor);
Mockito.verify(roTx).close();
}
@Test
- public void testOnDataTreeChangedSkip() throws Exception {
+ public void testOnDataTreeChangedAddSkip() {
// Related to bug 5920 -> https://bugs.opendaylight.org/show_bug.cgi?id=5920
Mockito.when(roTx.read(LogicalDatastoreType.CONFIGURATION, fcNodePath))
.thenReturn(Futures.immediateCheckedFuture(Optional.absent()));
+ Mockito.when(operationalModification.getDataAfter()).thenReturn(operationalNode);
nodeListenerOperational.onDataTreeChanged(Collections.singleton(dataTreeModification));
Mockito.verifyZeroInteractions(reactor);
Mockito.verify(roTx).close();
}
+
+ @Test
+ public void testOnDataTreeChangedSyncupDeletePhysical() {
+ Mockito.when(operationalModification.getDataBefore()).thenReturn(operationalNode);
+ Mockito.when(dataTreeModification.getRootNode().getModificationType()).thenReturn(ModificationType.DELETE);
+
+ nodeListenerOperational.onDataTreeChanged(Collections.singleton(dataTreeModification));
+
+ Mockito.verifyZeroInteractions(reactor);
+ }
+
+ @Test
+ public void testOnDataTreeChangedSyncupDeleteLogical() {
+ Mockito.when(operationalModification.getDataBefore()).thenReturn(operationalNode);
+ List<NodeConnector> nodeConnectorList = Mockito.mock(List.class);
+ Mockito.when(operationalNode.getNodeConnector()).thenReturn(nodeConnectorList);
+
+ nodeListenerOperational.onDataTreeChanged(Collections.singleton(dataTreeModification));
+
+ Mockito.verifyZeroInteractions(reactor);
+ }
}
--- /dev/null
+/**
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.openflowplugin.applications.frsync.impl;
+
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.Futures;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Collections;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Matchers;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
+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.DataTreeIdentifier;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
+import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.openflowplugin.applications.frsync.SyncReactor;
+import org.opendaylight.openflowplugin.applications.frsync.dao.FlowCapableNodeCachedDao;
+import org.opendaylight.openflowplugin.applications.frsync.dao.FlowCapableNodeDao;
+import org.opendaylight.openflowplugin.applications.frsync.dao.FlowCapableNodeOdlDao;
+import org.opendaylight.openflowplugin.applications.frsync.dao.FlowCapableNodeSnapshotDao;
+import org.opendaylight.openflowplugin.applications.frsync.util.RetryRegistry;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.DateAndTime;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableStatisticsGatheringStatus;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.snapshot.gathering.status.grouping.SnapshotGatheringStatusEnd;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+/**
+ * Test for {@link SimplifiedOperationalRetryListener}.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class SimplifiedOperationalRetryListenerTest {
+
+ private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(RetryRegistry.DATE_AND_TIME_FORMAT);
+ private static final NodeId NODE_ID = new NodeId("testNode");
+ private InstanceIdentifier<FlowCapableNode> fcNodePath;
+ private SimplifiedOperationalRetryListener nodeListenerOperational;
+ private final String timestampBefore = "0000-12-12T01:01:01.000-07:00";
+ private final String timestampAfter = "9999-12-12T01:01:01.000-07:00";
+ private final LogicalDatastoreType dsType = LogicalDatastoreType.OPERATIONAL;
+
+ @Mock
+ private SyncReactor reactor;
+ @Mock
+ private ReadOnlyTransaction roTx;
+ @Mock
+ private DataTreeModification<Node> dataTreeModification;
+ @Mock
+ private DataObjectModification<Node> operationalModification;
+ @Mock
+ private FlowCapableNode configNode;
+ @Mock
+ private Node operationalNode;
+ @Mock
+ private FlowCapableNode fcOperationalNode;
+ @Mock
+ private RetryRegistry retryRegistry;
+ @Mock
+ private FlowCapableStatisticsGatheringStatus statisticsGatheringStatus;
+ @Mock
+ private SnapshotGatheringStatusEnd snapshotGatheringStatusEnd;
+
+ @Before
+ public void setUp() throws Exception {
+ final DataBroker db = Mockito.mock(DataBroker.class);
+ final FlowCapableNodeSnapshotDao configSnapshot = new FlowCapableNodeSnapshotDao();
+ final FlowCapableNodeSnapshotDao operationalSnapshot = new FlowCapableNodeSnapshotDao();
+ final FlowCapableNodeDao configDao = new FlowCapableNodeCachedDao(configSnapshot,
+ new FlowCapableNodeOdlDao(db, LogicalDatastoreType.CONFIGURATION));
+
+ nodeListenerOperational = new SimplifiedOperationalRetryListener(reactor, operationalSnapshot, configDao, retryRegistry);
+ InstanceIdentifier<Node> nodePath = InstanceIdentifier.create(Nodes.class).child(Node.class, new NodeKey(NODE_ID));
+ fcNodePath = nodePath.augmentation(FlowCapableNode.class);
+
+ final DataTreeIdentifier<Node> dataTreeIdentifier =
+ new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, nodePath);
+
+ Mockito.when(db.newReadOnlyTransaction()).thenReturn(roTx);
+ Mockito.when(operationalNode.getId()).thenReturn(NODE_ID);
+ Mockito.when(dataTreeModification.getRootPath()).thenReturn(dataTreeIdentifier);
+ Mockito.when(dataTreeModification.getRootNode()).thenReturn(operationalModification);
+ Mockito.when(operationalNode.getAugmentation(FlowCapableNode.class)).thenReturn(fcOperationalNode);
+ }
+
+ @Test
+ public void testOnDataTreeChangedRetryNotRegistered() {
+ Mockito.when(operationalModification.getDataBefore()).thenReturn(operationalNode);
+ Mockito.when(operationalModification.getDataAfter()).thenReturn(operationalNode);
+ Mockito.when(retryRegistry.isRegistered(NODE_ID)).thenReturn(false);
+
+ nodeListenerOperational.onDataTreeChanged(Collections.singleton(dataTreeModification));
+
+ Mockito.verifyZeroInteractions(reactor);
+ }
+
+ @Test
+ public void testOnDataTreeChangedRetryButStaticsGatheringNotStarted() {
+ Mockito.when(operationalModification.getDataBefore()).thenReturn(operationalNode);
+ Mockito.when(operationalModification.getDataAfter()).thenReturn(operationalNode);
+ Mockito.when(retryRegistry.isRegistered(NODE_ID)).thenReturn(true);
+ Mockito.when(operationalNode.getAugmentation(FlowCapableStatisticsGatheringStatus.class)).thenReturn(null);
+
+ nodeListenerOperational.onDataTreeChanged(Collections.singleton(dataTreeModification));
+
+ Mockito.verifyZeroInteractions(reactor);
+ }
+
+ @Test
+ public void testOnDataTreeChangedRetryButStaticsGatheringNotFinished() {
+ Mockito.when(operationalModification.getDataBefore()).thenReturn(operationalNode);
+ Mockito.when(operationalModification.getDataAfter()).thenReturn(operationalNode);
+ Mockito.when(retryRegistry.isRegistered(NODE_ID)).thenReturn(true);
+ Mockito.when(operationalNode.getAugmentation(FlowCapableStatisticsGatheringStatus.class)).thenReturn(statisticsGatheringStatus);
+ Mockito.when(statisticsGatheringStatus.getSnapshotGatheringStatusEnd()).thenReturn(null);
+
+ nodeListenerOperational.onDataTreeChanged(Collections.singleton(dataTreeModification));
+
+ Mockito.verifyZeroInteractions(reactor);
+ }
+
+ @Test
+ public void testOnDataTreeChangedRetryButStaticsGatheringNotSuccessful() {
+ Mockito.when(operationalModification.getDataBefore()).thenReturn(operationalNode);
+ Mockito.when(operationalModification.getDataAfter()).thenReturn(operationalNode);
+ Mockito.when(retryRegistry.isRegistered(NODE_ID)).thenReturn(true);
+ Mockito.when(operationalNode.getAugmentation(FlowCapableStatisticsGatheringStatus.class)).thenReturn(statisticsGatheringStatus);
+ Mockito.when(statisticsGatheringStatus.getSnapshotGatheringStatusEnd()).thenReturn(snapshotGatheringStatusEnd);
+ Mockito.when(snapshotGatheringStatusEnd.isSucceeded()).thenReturn(false);
+
+ nodeListenerOperational.onDataTreeChanged(Collections.singleton(dataTreeModification));
+
+ Mockito.verifyZeroInteractions(reactor);
+ }
+
+ @Test
+ public void testOnDataTreeChangedRetryAndFreshOperationalNotPresent() throws ParseException {
+ final DateAndTime timestamp = Mockito.mock(DateAndTime.class);
+ Mockito.when(operationalModification.getDataBefore()).thenReturn(operationalNode);
+ Mockito.when(operationalModification.getDataAfter()).thenReturn(operationalNode);
+ Mockito.when(retryRegistry.isRegistered(NODE_ID)).thenReturn(true);
+ Mockito.when(operationalNode.getAugmentation(FlowCapableStatisticsGatheringStatus.class)).thenReturn(statisticsGatheringStatus);
+ Mockito.when(statisticsGatheringStatus.getSnapshotGatheringStatusEnd()).thenReturn(snapshotGatheringStatusEnd);
+ Mockito.when(snapshotGatheringStatusEnd.isSucceeded()).thenReturn(true);
+ Mockito.when(snapshotGatheringStatusEnd.getEnd()).thenReturn(timestamp);
+ Mockito.when(snapshotGatheringStatusEnd.getEnd().getValue()).thenReturn(timestampBefore);
+ Mockito.when(retryRegistry.getRegistration(NODE_ID)).thenReturn(simpleDateFormat.parse(timestampAfter));
+
+ nodeListenerOperational.onDataTreeChanged(Collections.singleton(dataTreeModification));
+
+ Mockito.verifyZeroInteractions(reactor);
+ }
+
+ @Test
+ public void testOnDataTreeChangedRetryAndFreshOperationalPresent() throws Exception {
+ final DateAndTime timestamp = Mockito.mock(DateAndTime.class);
+ Mockito.when(roTx.read(LogicalDatastoreType.CONFIGURATION, fcNodePath))
+ .thenReturn(Futures.immediateCheckedFuture(Optional.of(configNode)));
+ Mockito.when(reactor.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(), Matchers.<FlowCapableNode>any(),
+ Matchers.<FlowCapableNode>any(), Matchers.<LogicalDatastoreType>any())).thenReturn(Futures.immediateFuture(Boolean.TRUE));
+ Mockito.when(operationalModification.getDataBefore()).thenReturn(operationalNode);
+ Mockito.when(operationalModification.getDataAfter()).thenReturn(operationalNode);
+ Mockito.when(retryRegistry.isRegistered(NODE_ID)).thenReturn(true);
+ Mockito.when(operationalNode.getAugmentation(FlowCapableStatisticsGatheringStatus.class)).thenReturn(statisticsGatheringStatus);
+ Mockito.when(statisticsGatheringStatus.getSnapshotGatheringStatusEnd()).thenReturn(snapshotGatheringStatusEnd);
+ Mockito.when(snapshotGatheringStatusEnd.isSucceeded()).thenReturn(true);
+ Mockito.when(snapshotGatheringStatusEnd.getEnd()).thenReturn(timestamp);
+ Mockito.when(snapshotGatheringStatusEnd.getEnd().getValue()).thenReturn(timestampAfter);
+ Mockito.when(retryRegistry.getRegistration(NODE_ID)).thenReturn(simpleDateFormat.parse(timestampBefore));
+
+ nodeListenerOperational.onDataTreeChanged(Collections.singleton(dataTreeModification));
+
+ Mockito.verify(reactor).syncup(fcNodePath, configNode, fcOperationalNode, dsType);
+ Mockito.verifyNoMoreInteractions(reactor);
+ Mockito.verify(roTx).close();
+ }
+
+ @Test
+ public void testOnDataTreeChangedRetryAndNodeDeleted() {
+ Mockito.when(operationalModification.getDataBefore()).thenReturn(operationalNode);
+ Mockito.when(dataTreeModification.getRootNode().getModificationType()).thenReturn(DataObjectModification.ModificationType.DELETE);
+
+ nodeListenerOperational.onDataTreeChanged(Collections.singleton(dataTreeModification));
+
+ Mockito.verify(retryRegistry).unregisterIfRegistered(NODE_ID);
+ Mockito.verifyZeroInteractions(reactor);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/**
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.openflowplugin.applications.frsync.impl;
+
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InOrder;
+import org.mockito.Matchers;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.mockito.stubbing.Answer;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test for {@link SyncReactorFutureZipDecorator}.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class SyncReactorFutureZipDecoratorTest {
+
+ private static final Logger LOG = LoggerFactory.getLogger(SyncReactorFutureZipDecoratorTest.class);
+ private static final NodeId NODE_ID = new NodeId("testNode");
+ private SyncReactorFutureZipDecorator reactor;
+ private InstanceIdentifier<FlowCapableNode> fcNodePath;
+ private ListeningExecutorService syncThreadPool;
+
+ @Mock
+ private SyncReactorGuardDecorator delegate;
+
+ @Before
+ public void setUp() {
+ syncThreadPool = FrmExecutors.instance()
+ .newFixedThreadPool(1, new ThreadFactoryBuilder()
+ .setNameFormat(SyncReactorFutureDecorator.FRM_RPC_CLIENT_PREFIX + "%d")
+ .setDaemon(false)
+ .build());
+
+ reactor = new SyncReactorFutureZipDecorator(delegate, syncThreadPool);
+ fcNodePath = InstanceIdentifier.create(Nodes.class).child(Node.class, new NodeKey(NODE_ID))
+ .augmentation(FlowCapableNode.class);
+ }
+
+ @Test
+ public void testSyncupWithOptimizedConfigDeltaCompression() throws Exception {
+ final FlowCapableNode dataBefore = Mockito.mock(FlowCapableNode.class);
+ final FlowCapableNode dataAfter = Mockito.mock(FlowCapableNode.class);
+ final FlowCapableNode dataAfter2 = Mockito.mock(FlowCapableNode.class);
+ final CountDownLatch latchForFirst = new CountDownLatch(1);
+ final CountDownLatch latchForNext = new CountDownLatch(1);
+ final LogicalDatastoreType dsType = LogicalDatastoreType.CONFIGURATION;
+
+ Mockito.when(delegate.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(), Matchers.<FlowCapableNode>any(),
+ Matchers.<FlowCapableNode>any(), Matchers.<LogicalDatastoreType>any())).thenAnswer(new Answer<ListenableFuture<Boolean>>() {
+ @Override
+ public ListenableFuture<Boolean> answer(final InvocationOnMock invocationOnMock) throws Throwable {
+ LOG.info("unlocking next configs");
+ latchForNext.countDown();
+ latchForFirst.await();
+ LOG.info("unlocking first delegate");
+ return Futures.immediateFuture(Boolean.TRUE);
+ }
+ }).thenReturn(Futures.immediateFuture(Boolean.TRUE));
+
+ final List<ListenableFuture<Boolean>> allResults = new ArrayList<>();
+ allResults.add(reactor.syncup(fcNodePath, dataBefore, null, dsType));
+ latchForNext.await();
+
+ allResults.add(reactor.syncup(fcNodePath, dataAfter, dataBefore, dsType));
+ allResults.add(reactor.syncup(fcNodePath, null, dataAfter, dsType));
+ allResults.add(reactor.syncup(fcNodePath, dataAfter2, null, dsType));
+ latchForFirst.countDown();
+
+ Futures.allAsList(allResults).get(1, TimeUnit.SECONDS);
+ LOG.info("all configs done");
+
+ syncThreadPool.shutdown();
+ boolean terminated = syncThreadPool.awaitTermination(1, TimeUnit.SECONDS);
+ if (!terminated) {
+ LOG.info("thread pool not terminated.");
+ syncThreadPool.shutdownNow();
+ }
+ final InOrder inOrder = Mockito.inOrder(delegate);
+ inOrder.verify(delegate).syncup(fcNodePath, dataBefore, null, dsType);
+ inOrder.verify(delegate).syncup(fcNodePath, dataAfter2, dataBefore, dsType);
+ inOrder.verifyNoMoreInteractions();
+ }
+
+ @Test
+ public void testSyncupConfigEmptyQueue() throws Exception {
+ final FlowCapableNode dataBefore = Mockito.mock(FlowCapableNode.class);
+ final FlowCapableNode dataAfter = Mockito.mock(FlowCapableNode.class);
+ final CountDownLatch latchForNext = new CountDownLatch(1);
+ final LogicalDatastoreType dsType = LogicalDatastoreType.CONFIGURATION;
+
+ Mockito.when(delegate.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(), Matchers.<FlowCapableNode>any(),
+ Matchers.<FlowCapableNode>any(), Matchers.<LogicalDatastoreType>any())).thenAnswer(new Answer<ListenableFuture<Boolean>>() {
+ @Override
+ public ListenableFuture<Boolean> answer(final InvocationOnMock invocationOnMock) throws Throwable {
+ LOG.info("unlocking next config");
+ latchForNext.countDown();
+ return Futures.immediateFuture(Boolean.TRUE);
+ }
+ }).thenReturn(Futures.immediateFuture(Boolean.TRUE));
+
+ reactor.syncup(fcNodePath, dataBefore, null, dsType);
+ latchForNext.await();
+ reactor.syncup(fcNodePath, dataAfter, dataBefore, dsType);
+
+ boolean terminated = syncThreadPool.awaitTermination(1, TimeUnit.SECONDS);
+ if (!terminated) {
+ LOG.info("thread pool not terminated.");
+ syncThreadPool.shutdownNow();
+ }
+ final InOrder inOrder = Mockito.inOrder(delegate);
+ inOrder.verify(delegate).syncup(fcNodePath, dataBefore, null, dsType);
+ inOrder.verify(delegate).syncup(fcNodePath, dataAfter, dataBefore, dsType);
+ inOrder.verifyNoMoreInteractions();
+
+ }
+
+ @Test
+ public void testSyncupRewriteZipEntryWithOperationalDelta() throws Exception {
+ final FlowCapableNode configBefore = Mockito.mock(FlowCapableNode.class);
+ final FlowCapableNode configAfter = Mockito.mock(FlowCapableNode.class);
+ final FlowCapableNode configActual = Mockito.mock(FlowCapableNode.class);
+ final FlowCapableNode freshOperational = Mockito.mock(FlowCapableNode.class);
+ final CountDownLatch latchForFirst = new CountDownLatch(1);
+ final CountDownLatch latchForNext = new CountDownLatch(1);
+
+ Mockito.when(delegate.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(), Matchers.<FlowCapableNode>any(),
+ Matchers.<FlowCapableNode>any(), Matchers.<LogicalDatastoreType>any())).thenAnswer(new Answer<ListenableFuture<Boolean>>() {
+ @Override
+ public ListenableFuture<Boolean> answer(final InvocationOnMock invocationOnMock) throws Throwable {
+ LOG.info("unlocking for fresh operational");
+ latchForNext.countDown();
+ latchForFirst.await();
+ LOG.info("unlocking first delegate");
+ return Futures.immediateFuture(Boolean.TRUE);
+ }
+ }).thenReturn(Futures.immediateFuture(Boolean.TRUE));
+
+ reactor.syncup(fcNodePath, configAfter, configBefore, LogicalDatastoreType.CONFIGURATION);
+ latchForNext.await();
+
+ reactor.syncup(fcNodePath, configActual, freshOperational, LogicalDatastoreType.OPERATIONAL);
+ latchForFirst.countDown();
+
+ syncThreadPool.shutdown();
+ boolean terminated = syncThreadPool.awaitTermination(1, TimeUnit.SECONDS);
+ if (!terminated) {
+ LOG.info("thread pool not terminated.");
+ syncThreadPool.shutdownNow();
+ }
+ Mockito.verify(delegate, Mockito.times(1)).syncup(fcNodePath, configActual, freshOperational, LogicalDatastoreType.OPERATIONAL);
+ }
+
+ @After
+ public void tearDown() {
+ syncThreadPool.shutdownNow();
+ }
+}
\ No newline at end of file
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.openflowplugin.applications.frsync.util.SemaphoreKeeperGuavaImpl;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
private static final NodeId NODE_ID = new NodeId("test-node");
private SyncReactorGuardDecorator reactor;
private InstanceIdentifier<FlowCapableNode> fcNodePath;
+ private final LogicalDatastoreType dsType = LogicalDatastoreType.CONFIGURATION;
@Mock
- private SyncReactorImpl delegate;
+ private SyncReactorRetryDecorator delegate;
@Mock
private FlowCapableNode fcConfigNode;
@Mock
@Before
public void setUp() throws Exception {
- reactor = new SyncReactorGuardDecorator(delegate, new SemaphoreKeeperGuavaImpl<InstanceIdentifier<FlowCapableNode>>(1, true));
+ final SemaphoreKeeperGuavaImpl semaphoreKeeper = new SemaphoreKeeperGuavaImpl<InstanceIdentifier<FlowCapableNode>>(1, true);
+ reactor = new SyncReactorGuardDecorator(delegate, semaphoreKeeper);
InstanceIdentifier<Node> nodePath = InstanceIdentifier.create(Nodes.class).child(Node.class, new NodeKey(NODE_ID));
fcNodePath = nodePath.augmentation(FlowCapableNode.class);
@Test
public void testSyncupSuccess() throws Exception {
- Mockito.when(delegate.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(),Matchers.<FlowCapableNode>any(),
- Matchers.<FlowCapableNode>any())).thenReturn(Futures.immediateFuture(Boolean.TRUE));
- reactor.syncup(fcNodePath, fcConfigNode, fcOperationalNode);
- Mockito.verify(delegate).syncup(fcNodePath, fcConfigNode, fcOperationalNode);
+ Mockito.when(delegate.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(), Matchers.<FlowCapableNode>any(),
+ Matchers.<FlowCapableNode>any(), Matchers.<LogicalDatastoreType>any())).thenReturn(Futures.immediateFuture(Boolean.TRUE));
+ reactor.syncup(fcNodePath, fcConfigNode, fcOperationalNode, dsType);
+
+ Mockito.verify(delegate).syncup(fcNodePath, fcConfigNode, fcOperationalNode, dsType);
+ Mockito.verifyNoMoreInteractions(delegate);
}
@Test
public void testSyncupFail() throws Exception {
- Mockito.when(delegate.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(),Matchers.<FlowCapableNode>any(),
- Matchers.<FlowCapableNode>any())).thenReturn(Futures.immediateFailedFuture(new Exception()));
- reactor.syncup(fcNodePath, fcConfigNode, fcOperationalNode);
- Mockito.verify(delegate).syncup(fcNodePath, fcConfigNode, fcOperationalNode);
+ Mockito.when(delegate.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(), Matchers.<FlowCapableNode>any(),
+ Matchers.<FlowCapableNode>any(), Matchers.<LogicalDatastoreType>any())).thenReturn(Futures.immediateFailedFuture(new Exception()));
+
+ reactor.syncup(fcNodePath, fcConfigNode, fcOperationalNode, dsType);
+
+ Mockito.verify(delegate).syncup(fcNodePath, fcConfigNode, fcOperationalNode, dsType);
+ Mockito.verifyNoMoreInteractions(delegate);
}
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.openflowplugin.applications.frsync.SyncPlanPushStrategy;
import org.opendaylight.openflowplugin.applications.frsync.impl.strategy.SynchronizationDiffInput;
import org.opendaylight.openflowplugin.applications.frsync.util.ReconcileUtil;
private static final NodeId NODE_ID = new NodeId("unit-nodeId");
private static final InstanceIdentifier<FlowCapableNode> NODE_IDENT = InstanceIdentifier.create(Nodes.class)
.child(Node.class, new NodeKey(NODE_ID)).augmentation(FlowCapableNode.class);
-
private SyncReactorImpl reactor;
+
@Mock
private DataBroker db;
@Mock
private SyncPlanPushStrategy syncPlanPushStrategy;
-
@Captor
private ArgumentCaptor<Group> groupCaptor;
@Captor
Matchers.<SyncCrudCounters>any()))
.thenReturn(RpcResultBuilder.<Void>success().buildFuture());
- final ListenableFuture<Boolean> syncupResult = reactor.syncup(NODE_IDENT, configFcn, operationalFcn);
+ final ListenableFuture<Boolean> syncupResult = reactor.syncup(NODE_IDENT, configFcn, operationalFcn, LogicalDatastoreType.CONFIGURATION);
try {
Assert.assertTrue(syncupResult.isDone());
final Boolean voidRpcResult = syncupResult.get(2, TimeUnit.SECONDS);
--- /dev/null
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.openflowplugin.applications.frsync.impl;
+
+import com.google.common.util.concurrent.Futures;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Matchers;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.openflowplugin.applications.frsync.util.RetryRegistry;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+/**
+ * Test for {@link SyncReactorRetryDecorator}
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class SyncReactorRetryDecoratorTest {
+
+ private static final NodeId NODE_ID = new NodeId("test-node");
+ private SyncReactorRetryDecorator reactor;
+ private InstanceIdentifier<FlowCapableNode> fcNodePath;
+ final LogicalDatastoreType dsType = LogicalDatastoreType.CONFIGURATION;
+
+ @Mock
+ private SyncReactorImpl delegate;
+ @Mock
+ private RetryRegistry retryRegistry;
+ @Mock
+ private FlowCapableNode fcConfigNode;
+ @Mock
+ private FlowCapableNode fcOperationalNode;
+
+ @Before
+ public void setUp() {
+ reactor = new SyncReactorRetryDecorator(delegate, retryRegistry);
+ InstanceIdentifier<Node> nodePath = InstanceIdentifier.create(Nodes.class).child(Node.class, new NodeKey(NODE_ID));
+ fcNodePath = nodePath.augmentation(FlowCapableNode.class);
+
+ final Node operationalNode = Mockito.mock(Node.class);
+ Mockito.when(operationalNode.getId()).thenReturn(NODE_ID);
+ Mockito.when(operationalNode.getAugmentation(FlowCapableNode.class)).thenReturn(fcOperationalNode);
+ }
+
+ @Test
+ public void testSyncupSuccess() throws InterruptedException {
+ Mockito.when(delegate.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(), Matchers.<FlowCapableNode>any(),
+ Matchers.<FlowCapableNode>any(), Matchers.<LogicalDatastoreType>any())).thenReturn(Futures.immediateFuture(Boolean.TRUE));
+
+ reactor.syncup(fcNodePath, fcConfigNode, fcOperationalNode, dsType);
+
+ Mockito.verify(delegate).syncup(fcNodePath, fcConfigNode, fcOperationalNode, dsType);
+ Mockito.verifyNoMoreInteractions(delegate);
+ Mockito.verify(retryRegistry).unregisterIfRegistered(NODE_ID);
+ }
+
+ @Test
+ public void testSyncupFail() throws InterruptedException {
+ Mockito.when(delegate.syncup(Matchers.<InstanceIdentifier<FlowCapableNode>>any(), Matchers.<FlowCapableNode>any(),
+ Matchers.<FlowCapableNode>any(), Matchers.<LogicalDatastoreType>any())).thenReturn(Futures.immediateFuture(Boolean.FALSE));
+
+ reactor.syncup(fcNodePath, fcConfigNode, fcOperationalNode, dsType);
+
+ Mockito.verify(delegate).syncup(fcNodePath, fcConfigNode, fcOperationalNode, dsType);
+ Mockito.verifyNoMoreInteractions(delegate);
+ Mockito.verify(retryRegistry).register(NODE_ID);
+ }
+
+ @Test
+ public void testSyncupConfigIgnoreInRetry() throws InterruptedException {
+ Mockito.when(retryRegistry.isRegistered(NODE_ID)).thenReturn(true);
+
+ reactor.syncup(fcNodePath, fcConfigNode, fcOperationalNode, dsType);
+
+ Mockito.verifyZeroInteractions(delegate);
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/**
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.openflowplugin.applications.frsync.util;
+
+import java.util.Date;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+
+/**
+ * Test for {@link RetryRegistry}.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class RetryRegistryTest {
+
+ private static final NodeId NODE_ID = new NodeId("testNode");
+ private RetryRegistry retryRegistry;
+
+ @Before
+ public void setUp() throws Exception {
+ retryRegistry = new RetryRegistry();
+ }
+
+ @Test
+ public void testRegister() {
+ Date timestamp = retryRegistry.register(NODE_ID);
+ Assert.assertEquals(true, retryRegistry.isRegistered(NODE_ID));
+ Assert.assertNotNull(timestamp);
+ }
+
+ @Test
+ public void testUnregisterIfRegistered() {
+ retryRegistry.register(NODE_ID);
+ Date timestamp = retryRegistry.unregisterIfRegistered(NODE_ID);
+ Assert.assertEquals(false, retryRegistry.isRegistered(NODE_ID));
+ Assert.assertNotNull(timestamp);
+ }
+
+ @Test
+ public void testUnregisterIfNotRegistered() {
+ Date timestamp = retryRegistry.unregisterIfRegistered(NODE_ID);
+ Assert.assertEquals(false, retryRegistry.isRegistered(NODE_ID));
+ Assert.assertNull(timestamp);
+ }
+
+}
<artifactId>forwardingrules-manager</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>${project.groupId}.applications</groupId>
- <artifactId>forwardingrules-manager-config</artifactId>
- <version>${project.version}</version>
- <classifier>config</classifier>
- <type>xml</type>
- </dependency>
<dependency>
<groupId>${project.groupId}.applications</groupId>
<artifactId>forwardingrules-sync</artifactId>
<artifactId>inventory-manager</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>${project.groupId}.applications</groupId>
- <artifactId>inventory-manager</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>config</classifier>
- </dependency>
<dependency>
<groupId>${project.groupId}.applications</groupId>
<artifactId>lldp-speaker</artifactId>
<artifactId>topology-lldp-discovery</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>${project.groupId}.applications</groupId>
- <artifactId>topology-lldp-discovery</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>config</classifier>
- </dependency>
<dependency>
<groupId>${project.groupId}.applications</groupId>
<artifactId>topology-manager</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>${project.groupId}.applications</groupId>
- <artifactId>topology-manager</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>config</classifier>
- </dependency>
<dependency>
<groupId>${project.groupId}.applications</groupId>
<artifactId>of-switch-config-pusher</artifactId>
<version>${project.version}</version>
</dependency>
- <dependency>
- <groupId>${project.groupId}.applications</groupId>
- <artifactId>of-switch-config-pusher</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>config</classifier>
- </dependency>
- <dependency>
- <groupId>${project.groupId}.applications</groupId>
- <artifactId>statistics-manager-config</artifactId>
- <version>${project.version}</version>
- <classifier>config</classifier>
- <type>xml</type>
- </dependency>
<dependency>
<groupId>${project.groupId}.applications</groupId>
<artifactId>table-miss-enforcer</artifactId>
<type>xml</type>
<classifier>config</classifier>
</dependency>
- <dependency>
- <groupId>${project.groupId}.applications</groupId>
- <artifactId>lldp-speaker</artifactId>
- <version>${project.version}</version>
- <type>xml</type>
- <classifier>config</classifier>
- </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>openflowplugin-controller-config</artifactId>
<groupId>org.opendaylight.openflowplugin.applications</groupId>
<artifactId>statistics-manager</artifactId>
</dependency>
- <dependency>
- <groupId>org.opendaylight.openflowplugin.applications</groupId>
- <artifactId>statistics-manager-config</artifactId>
- <classifier>config</classifier>
- <type>xml</type>
- </dependency>
<dependency>
<groupId>org.opendaylight.openflowplugin</groupId>
<artifactId>openflowplugin-blueprint-config</artifactId>
--- /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.openflowplugin.api.openflow;
+
+/**
+ * General API for all OFP Context
+ */
+public interface OFPContext {
+
+ /**
+ * distinguished device context states
+ */
+ enum CONTEXT_STATE {
+ /**
+ * initial phase
+ */
+ INITIALIZATION,
+ /**
+ * standard phase
+ */
+ WORKING,
+ /**
+ * termination phase
+ */
+ TERMINATION
+ }
+
+ CONTEXT_STATE getState();
+
+}
--- /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.openflowplugin.api.openflow;
+
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
+
+/**
+ * Generic API for all managers
+ */
+public interface OFPManager {
+
+ <T extends OFPContext> T gainContext(final DeviceInfo deviceInfo);
+
+}
import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceDisconnectedHandler;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
* Each OpenFlow session is tracked by a Connection Context. These attach to a particular Device Context in such a way,
* that there is at most one primary session associated with a Device Context.
* </p>
- * Created by Martin Bobak <mbobak@cisco.com> on 25.2.2015.
*/
public interface ConnectionContext {
* change internal state to {@link ConnectionContext.CONNECTION_STATE#WORKING}
*/
void changeStateToWorking();
+
+ /**
+ * Create and return basic device info
+ * @return
+ */
+ DeviceInfo getDeviceInfo();
+
+ /**
+ * This method creates a basic device information. Should be called after nodeId and features are set in connection context
+ */
+ void handshakeSuccessful();
}
import io.netty.util.Timeout;
import java.math.BigInteger;
import java.util.List;
-import javax.annotation.CheckForNull;
-import javax.annotation.Nullable;
import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
+import org.opendaylight.openflowplugin.api.openflow.OFPContext;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceReplyProcessor;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
import org.opendaylight.openflowplugin.api.openflow.registry.ItemLifeCycleRegistry;
-import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
-import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
-import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
-import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
-import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
/**
* <p>
* Context can have at any point in time. Should this quota be exceeded, any further attempt to make
* a request to the switch will fail immediately, with proper error indication.
* </p>
- * Created by Martin Bobak <mbobak@cisco.com> on 25.2.2015.
*/
public interface DeviceContext extends AutoCloseable,
DeviceReplyProcessor,
- PortNumberCache,
TxFacade,
- XidSequencer {
-
- void setStatisticsRpcEnabled(boolean isStatisticsRpcEnabled);
-
- /**
- * distinguished device context states
- */
- enum DEVICE_CONTEXT_STATE {
- /**
- * initial phase of talking to switch
- */
- INITIALIZATION,
- /**
- * standard phase - interacting with switch
- */
- WORKING,
- /**
- * termination phase of talking to switch
- */
- TERMINATION
- }
-
- /**
- * Method returns current device context state.
- *
- * @return {@link DeviceContext.DEVICE_CONTEXT_STATE}
- */
- DEVICE_CONTEXT_STATE getDeviceContextState();
+ XidSequencer,
+ OFPContext,
+ DeviceRegistry{
/**
* Method close all auxiliary connections and primary connection.
*/
DeviceState getDeviceState();
- /**
- * Method has to activate (MASTER) or deactivate (SLAVE) TransactionChainManager.
- * TransactionChainManager represents possibility to write or delete Node subtree data
- * for actual Controller Cluster Node. We are able to have an active TxManager only if
- * newRole is {@link OfpRole#BECOMESLAVE}.
- * Parameters are used as marker to be sure it is change to SLAVE from MASTER or from
- * MASTER to SLAVE and the last parameter "cleanDataStore" is used for validation only.
- * @param oldRole - old role for quick validation for needed processing
- * @param role - NewRole expect to be {@link OfpRole#BECOMESLAVE} or {@link OfpRole#BECOMEMASTER}
- * @return RoleChangeTxChainManager future for activation/deactivation
- * @deprecated replaced by method onDeviceTakeClusterLeadership and onDevicLostClusterLeadership
- */
- @Deprecated
- ListenableFuture<Void> onClusterRoleChange(@Nullable OfpRole oldRole, @CheckForNull OfpRole role);
-
- /**
- * Method has to activate TransactionChainManager and prepare all Contexts from Device Contects suite
- * to Taking ClusterLeadership role {@link OfpRole#BECOMEMASTER} (e.g. Routed RPC registration, StatPolling ...)
- * @return DeviceInitialization furure
- */
- ListenableFuture<Void> onDeviceTakeClusterLeadership();
-
- /**
- * Method has to deactivate TransactionChainManager and prepare all Contexts from Device Contects suite
- * to Lost ClusterLeadership role {@link OfpRole#BECOMESLAVE} (e.g. Stop RPC rounting, stop StatPolling ...)
- * @return RoleChangeTxChainManager future for deactivation
- */
- ListenableFuture<Void> onDeviceLostClusterLeadership();
+ DeviceInfo getDeviceInfo();
/**
* Method has to close TxManager ASAP we are notified about Closed Connection
*/
ConnectionContext getAuxiliaryConnectiobContexts(BigInteger cookie);
- /**
- * Method exposes flow registry used for storing flow ids identified by calculated flow hash.
- *
- * @return
- */
- DeviceFlowRegistry getDeviceFlowRegistry();
-
- /**
- * Method exposes device group registry used for storing group ids.
- *
- * @return
- */
- DeviceGroupRegistry getDeviceGroupRegistry();
-
- /**
- * Method exposes device meter registry used for storing meter ids.
- *
- * @return
- */
- DeviceMeterRegistry getDeviceMeterRegistry();
-
/**
* @return translator library
*/
ItemLifeCycleRegistry getItemLifeCycleSourceRegistry();
- void setRpcContext(RpcContext rpcContext);
-
- RpcContext getRpcContext();
-
- void setStatisticsContext(StatisticsContext statisticsContext);
-
- StatisticsContext getStatisticsContext();
-
@Override
void close();
}
--- /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.openflowplugin.api.openflow.device;
+
+import java.math.BigInteger;
+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.NodeKey;
+import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
+
+/**
+ * API defining basic device information
+ */
+public interface DeviceInfo {
+
+ /**
+ * @return id of encapsulated node
+ */
+ NodeId getNodeId();
+
+ /**
+ * @return {@link Node} instance identifier
+ */
+ KeyedInstanceIdentifier<Node, NodeKey> getNodeInstanceIdentifier();
+
+ /**
+ * @return version
+ */
+ Short getVersion();
+
+ /**
+ * @return datapathId
+ */
+ BigInteger getDatapathId();
+
+}
package org.opendaylight.openflowplugin.api.openflow.device;
-import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
+import com.google.common.util.concurrent.ListenableFuture;
+import org.opendaylight.openflowplugin.api.openflow.OFPManager;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceConnectedHandler;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceDisconnectedHandler;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceLifecycleSupervisor;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.translator.TranslatorLibrarian;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
/**
* This interface is responsible for instantiating DeviceContext and
* registering transaction chain for each DeviceContext. Each device
* has its own device context managed by this manager.
- * Created by Martin Bobak <mbobak@cisco.com> on 25.2.2015.
*/
public interface DeviceManager extends DeviceConnectedHandler, DeviceDisconnectedHandler, DeviceLifecycleSupervisor,
- DeviceInitializationPhaseHandler, DeviceTerminationPhaseHandler, TranslatorLibrarian, AutoCloseable {
+ DeviceInitializationPhaseHandler, DeviceTerminationPhaseHandler, TranslatorLibrarian, AutoCloseable, OFPManager {
+
/**
- * Sets notification publish service
+ * invoked after all services injected
+ */
+ void initialize();
+
+ /**
+ * Method has to activate (MASTER) or deactivate (SLAVE) TransactionChainManager.
+ * TransactionChainManager represents possibility to write or delete Node subtree data
+ * for actual Controller Cluster Node. We are able to have an active TxManager only if
+ * newRole is {@link OfpRole#BECOMESLAVE}.
+ * Parameters are used as marker to be sure it is change to SLAVE from MASTER or from
+ * MASTER to SLAVE and the last parameter "cleanDataStore" is used for validation only.
*
- * @param notificationPublishService
+ * @param deviceInfo which device
+ * @param role - NewRole expect to be {@link OfpRole#BECOMESLAVE} or {@link OfpRole#BECOMEMASTER}
+ * @return RoleChangeTxChainManager future for activation/deactivation
*/
- void setNotificationPublishService(NotificationPublishService notificationPublishService);
+ ListenableFuture<Void> onClusterRoleChange(final DeviceInfo deviceInfo, final OfpRole role);
/**
- * invoked after all services injected
+ * Register device synchronize listeners
+ * @param deviceSynchronizeListener are notified if device is synchronized or not
*/
- void initialize();
+ void addDeviceSynchronizeListener(final DeviceSynchronizeListener deviceSynchronizeListener);
+
+ /**
+ * Notify all registered listeners about synchronized status
+ * @param deviceInfo which device
+ * @param deviceSynchronized true if device is synchronized
+ */
+ void notifyDeviceSynchronizeListeners(final DeviceInfo deviceInfo, final boolean deviceSynchronized);
+
+ /**
+ * Register device valid listeners
+ * @param deviceValidListener are notified if device is valid or not
+ */
+ void addDeviceValidListener(final DeviceValidListener deviceValidListener);
/**
- * Returning device context from map maintained in device manager
- * This prevent to send whole device context to another context
- * If device context not exists for nodeId it will return null
- * @param nodeId
- * @return device context or null
+ * Notify all registered listeners about valid status
+ * @param deviceInfo which device
+ * @param deviceValid true if device is valid
*/
- DeviceContext getDeviceContextFromNodeId(NodeId nodeId);
+ void notifyDeviceValidListeners(final DeviceInfo deviceInfo, final boolean deviceValid);
- void setStatisticsRpcEnabled(boolean isStatisticsRpcEnabled);
}
--- /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.openflowplugin.api.openflow.device;
+
+import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
+import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
+import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
+
+/**
+ * Flows, Groups and Meter registry
+ */
+public interface DeviceRegistry {
+
+ /**
+ * Method exposes flow registry used for storing flow ids identified by calculated flow hash.
+ *
+ * @return
+ */
+ DeviceFlowRegistry getDeviceFlowRegistry();
+
+ /**
+ * Method exposes device group registry used for storing group ids.
+ *
+ * @return
+ */
+ DeviceGroupRegistry getDeviceGroupRegistry();
+
+ /**
+ * Method exposes device meter registry used for storing meter ids.
+ *
+ * @return
+ */
+ DeviceMeterRegistry getDeviceMeterRegistry();
+
+}
package org.opendaylight.openflowplugin.api.openflow.device;
-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.NodeKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
-
/**
- * Created by Martin Bobak <mbobak@cisco.com> on 25.2.2015.
+ * Holder of device's structure
*/
-public interface DeviceState {
-
- /**
- * @return id of encapsulated node
- */
- NodeId getNodeId();
-
- /**
- * @return {@link Node} instance identifier
- */
- KeyedInstanceIdentifier<Node, NodeKey> getNodeInstanceIdentifier();
-
- /**
- * @return the features of corresponding switch
- */
- GetFeaturesOutput getFeatures();
+public interface DeviceState extends DeviceSynchronizeListener, DeviceValidListener {
/**
* @return true if this session is valid
*/
boolean isValid();
- /**
- * @param valid the valid to set
- */
- void setValid(boolean valid);
-
- /**
- * Return node current OF protocol version
- *
- * @return
- */
- short getVersion();
-
/**
* Return true if we have relevant meter information
* from device
void setQueueStatisticsAvailable(boolean available);
- void setDeviceSynchronized(boolean deviceSynchronized);
-
boolean isStatisticsPollingEnabled();
void setStatisticsPollingEnabledProp(boolean statPollEnabled);
--- /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.openflowplugin.api.openflow.device;
+
+/**
+ * API for device synchronized listeners
+ */
+public interface DeviceSynchronizeListener {
+
+ void deviceIsSynchronized(final DeviceInfo deviceInfo, final boolean isSynchronized);
+
+}
--- /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.openflowplugin.api.openflow.device;
+
+/**
+ * API for device synchronized listeners
+ */
+public interface DeviceValidListener {
+
+ void deviceIsValid(final DeviceInfo deviceInfo, final boolean isValid);
+
+}
/**
* Translates from input to output
* @param input
- * @param deviceState
+ * @param deviceInfo
* @param connectionDistinguisher
* @return message of output type
*/
- O translate(I input, DeviceState deviceState, Object connectionDistinguisher);
+ O translate(I input, DeviceInfo deviceInfo, Object connectionDistinguisher);
}
+++ /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.openflowplugin.api.openflow.device;
-
-import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
-
-/**
- * keeps mapping between port number (protocol based) and {@link NodeConnectorRef}
- */
-public interface PortNumberCache {
-
- /**
- * @param portNumber
- * @return corresponding nodeConnectorRef if present
- */
- @Nullable
- @Deprecated
- NodeConnectorRef lookupNodeConnectorRef(Long portNumber);
-
- /**
- * @param portNumber protocol port number
- * @param nodeConnectorRef corresponding value of {@link NodeConnectorRef}
- */
- @Deprecated
- void storeNodeConnectorRef(@Nonnull Long portNumber, @Nonnull NodeConnectorRef nodeConnectorRef);
-}
import javax.annotation.CheckForNull;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
/**
* openflowplugin-api
/**
* Method represents an initialization cycle for {@link DeviceContext} preparation for use.
*
- * @param nodeId
+ * @param deviceInfo
* @throws Exception - needs to be catch in ConnectionHandler implementation
*/
- void onDeviceContextLevelUp(@CheckForNull NodeId nodeId) throws Exception;
+ void onDeviceContextLevelUp(@CheckForNull DeviceInfo deviceInfo) throws Exception;
}
import javax.annotation.CheckForNull;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
/**
* Interface represent handler for dead device connection annihilating cycle.
/**
* Method represents a termination cycle for {@link DeviceContext}.
*
- * @param deviceContext - {@link DeviceContext}
+ * @param deviceInfo - {@link DeviceInfo}
*/
- void onDeviceContextLevelDown(@CheckForNull DeviceContext deviceContext);
+ void onDeviceContextLevelDown(@CheckForNull DeviceInfo deviceInfo);
}
package org.opendaylight.openflowplugin.api.openflow.lifecycle;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
/**
* This API is for all listeners who wish to know about device context in cluster
/**
* Notification about start phase in device context, right after successful handshake
- * @param nodeId
+ * @param deviceInfo
* @param success or failure
*/
- void deviceStartInitializationDone(final NodeId nodeId, final boolean success);
+ void deviceStartInitializationDone(final DeviceInfo deviceInfo, final boolean success);
/**
* Notification about start phase in device context, after all other contexts initialized properly
- * @param nodeId
+ * @param deviceInfo
* @param success
*/
- void deviceInitializationDone(final NodeId nodeId, final boolean success);
+ void deviceInitializationDone(final DeviceInfo deviceInfo, final boolean success);
}
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
+import org.opendaylight.openflowplugin.api.openflow.OFPManager;
+import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
-import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
+import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-
-import javax.annotation.Nonnull;
-import java.util.concurrent.TimeUnit;
/**
* This class is a binder between all managers
/**
* Returns device context from device manager device contexts maps
- * @param nodeId node identification
- * @return null if context doesn't exists
+ *
+ * @param deviceInfo@return null if context doesn't exists
+ */
+ DeviceContext getDeviceContext(DeviceInfo deviceInfo);
+
+
+ /**
+ * Setter for device manager once set it cant be unset or overwritten
+ * @param manager
*/
- DeviceContext getDeviceContext(final NodeId nodeId);
+ void setSafelyManager(OFPManager manager);
/**
* Registers ont time listener for notify when services rpc, statistics are done stop or start
* @param manager service change listener
- * @param nodeId node identification
+ * @param deviceInfo node identification
*/
- void addOneTimeListenerWhenServicesChangesDone(final ServiceChangeListener manager, final NodeId nodeId);
+ void addOneTimeListenerWhenServicesChangesDone(final ServiceChangeListener manager, final DeviceInfo deviceInfo);
/**
- * Returns device of version
- * @param nodeId node identification
- * @return null if device context doesn't exists
+ * Returns statistics context from statistics managers contexts maps
+ *
+ * @param deviceInfo@return null if context doesn't exists
*/
- Short gainVersionSafely(final NodeId nodeId);
+ StatisticsContext getStatisticsContext(DeviceInfo deviceInfo);
/**
* Set new timeout for {@link io.netty.util.HashedWheelTimer}
/**
* Interrupt connection for the node
- * @param nodeId node identification
+ * @param deviceInfo node identification
*/
- void closeConnection(final NodeId nodeId);
+ void closeConnection(final DeviceInfo deviceInfo);
- /**
- * Setter for device manager once set it cant be unset or overwritten
- * @param deviceManager should be set in OpenFlowPluginProviderImpl
- */
- void setSafelyDeviceManager(final DeviceManager deviceManager);
-
- /**
- * Setter for statistics manager once set it cant be unset or overwritten
- * @param statisticsManager should be set in OpenFlowPluginProviderImpl
- */
- void setSafelyStatisticsManager(final StatisticsManager statisticsManager);
+ ConnectionContext.CONNECTION_STATE gainConnectionStateSafely(DeviceInfo deviceInfo);
/**
* Xid from outboundqueue
- * @param nodeId
+ * @param deviceInfo
* @return
*/
- Long reserveXidForDeviceMessage(final NodeId nodeId);
+ Long reserveXidForDeviceMessage(final DeviceInfo deviceInfo);
+
+ NotificationPublishService getNotificationPublishService();
+
+ void setNotificationPublishService(NotificationPublishService notificationPublishService);
}
package org.opendaylight.openflowplugin.api.openflow.lifecycle;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
/**
/**
* Notification when initialization for role context is done
- * @param nodeId
+ * @param deviceInfo
* @param success or failure
*/
- void roleInitializationDone(final NodeId nodeId, final boolean success);
+ void roleInitializationDone(final DeviceInfo deviceInfo, final boolean success);
/**
* Notification when the role change on device is done
- * @param nodeId
+ * @param deviceInfo
* @param success
* @param newRole
* @param initializationPhase
*/
- void roleChangeOnDevice(final NodeId nodeId, final boolean success, final OfpRole newRole, final boolean initializationPhase);
+ void roleChangeOnDevice(final DeviceInfo deviceInfo, final boolean success, final OfpRole newRole, final boolean initializationPhase);
}
package org.opendaylight.openflowplugin.api.openflow.lifecycle;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
/**
* This API is defined for listening when services (Statistics and RPCs) are fully stopped
/**
* Notification when services (rpc, statistics) are started or stopped working
- * @param nodeId
+ * @param deviceInfo
* @param success
*/
- void servicesChangeDone(NodeId nodeId, boolean success);
+ void servicesChangeDone(DeviceInfo deviceInfo, boolean success);
}
package org.opendaylight.openflowplugin.api.openflow.md.core;
+import com.google.common.collect.Lists;
import java.util.List;
import java.util.concurrent.Future;
-
import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext;
import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
import org.opendaylight.yangtools.yang.binding.DataObject;
-import com.google.common.collect.Lists;
-
/**
* @author mirehak
*/
package org.opendaylight.openflowplugin.api.openflow.md.core;
+import com.google.common.base.Preconditions;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
import org.opendaylight.yangtools.yang.binding.DataContainer;
import org.opendaylight.yangtools.yang.binding.Notification;
-import com.google.common.base.Preconditions;
-
/**
*
*/
package org.opendaylight.openflowplugin.api.openflow.md.core.session;
import java.util.concurrent.Future;
-
import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput;
import org.opendaylight.yangtools.yang.common.RpcResult;
/**
import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor;
import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher;
-import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener;
+import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.binding.DataContainer;
import java.util.Collection;
import java.util.List;
import java.util.Map;
-
import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator;
import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
*/
package org.opendaylight.openflowplugin.api.openflow.md.util;
+import com.google.common.collect.Iterators;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
-import com.google.common.collect.Iterators;
-
/**
* Zipper groups together a list of queues and exposes one poll method. Polling iterates through
* all groups and returns first not-null result of poll method on each queue. If after polling each
*/
package org.opendaylight.openflowplugin.api.openflow.role;
+import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
+import org.opendaylight.openflowplugin.api.openflow.OFPContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SalRoleService;
-import javax.annotation.Nonnull;
-
/**
- * Rewrote whole role context to prevent errors to change role on cluster
+ * Role context for change role on cluster
*/
-public interface RoleContext extends RequestContextStack, AutoCloseable {
+public interface RoleContext extends RequestContextStack, AutoCloseable, OFPContext {
/**
* Initialization method is responsible for a registration of
* Actual nodeId
* @return
*/
- NodeId getNodeId();
+ DeviceInfo getDeviceInfo();
/**
* Returns true if main entity is registered
*/
package org.opendaylight.openflowplugin.api.openflow.role;
+import org.opendaylight.openflowplugin.api.openflow.OFPManager;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceLifecycleSupervisor;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
* Created by kramesha on 8/31/15.
*/
public interface RoleManager extends DeviceLifecycleSupervisor, DeviceInitializationPhaseHandler, AutoCloseable,
- DeviceTerminationPhaseHandler {
+ DeviceTerminationPhaseHandler, OFPManager {
String ENTITY_TYPE = "openflow";
String TX_ENTITY_TYPE = "ofTransaction";
*/
package org.opendaylight.openflowplugin.api.openflow.rpc;
+import org.opendaylight.openflowplugin.api.openflow.OFPContext;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
import org.opendaylight.yangtools.yang.binding.RpcService;
* tracks the state of any user requests and how they map onto protocol requests. It uses
* {@link org.opendaylight.openflowplugin.api.openflow.device.RequestContext} to perform requests.
* <p>
- * Created by Martin Bobak <mbobak@cisco.com> on 25.2.2015.
*/
-public interface RpcContext extends RequestContextStack, AutoCloseable {
+public interface RpcContext extends RequestContextStack, AutoCloseable, OFPContext {
<S extends RpcService> void registerRpcServiceImplementation(Class<S> serviceClass, S serviceInstance);
<S extends RpcService> S lookupRpcService(Class<S> serviceClass);
@Override
void close();
+
+ void setStatisticsRpcEnabled(boolean isStatisticsRpcEnabled);
+
+ boolean isStatisticsRpcEnabled();
}
package org.opendaylight.openflowplugin.api.openflow.rpc;
+import org.opendaylight.openflowplugin.api.openflow.OFPManager;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceLifecycleSupervisor;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
/**
* The RPC Manager will maintain an RPC Context for each online switch. RPC context for device is created when
- * {@link org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler#onDeviceContextLevelUp(NodeId)}
+ * {@link org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler#onDeviceContextLevelUp(org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo)}
* is called.
* <p>
* Created by Martin Bobak <mbobak@cisco.com> on 25.2.2015.
*/
-public interface RpcManager extends DeviceLifecycleSupervisor, DeviceInitializationPhaseHandler, AutoCloseable, DeviceTerminationPhaseHandler {
+public interface RpcManager extends DeviceLifecycleSupervisor, DeviceInitializationPhaseHandler, AutoCloseable, DeviceTerminationPhaseHandler, OFPManager {
+ void setStatisticsRpcEnabled(boolean statisticsRpcEnabled);
}
package org.opendaylight.openflowplugin.api.openflow.statistics;
-import com.google.common.base.Optional;
import com.google.common.util.concurrent.ListenableFuture;
import io.netty.util.Timeout;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import java.util.Optional;
+import org.opendaylight.openflowplugin.api.openflow.OFPContext;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
/**
- * Created by Martin Bobak <mbobak@cisco.com> on 27.2.2015.
+ * Context for statistics
*/
-public interface StatisticsContext extends RequestContextStack, AutoCloseable {
+public interface StatisticsContext extends RequestContextStack, AutoCloseable, OFPContext {
+ /**
+ * Gather data from device
+ * @return true if gathering was successful
+ */
ListenableFuture<Boolean> gatherDynamicData();
+ /**
+ * Initial data gathering
+ * @return true if gathering was successful
+ */
+ ListenableFuture<Boolean> initialGatherDynamicData();
+
/**
* Method has to be called from DeviceInitialization Method, otherwise
* we are not able to poll anything. Statistics Context normally initialize
*/
ItemLifecycleListener getItemLifeCycleListener();
- /**
- * Statistics Context has to be able to return own DeviceCtx
- * @return {@link DeviceContext}
- */
- DeviceContext getDeviceContext();
-
@Override
void close();
package org.opendaylight.openflowplugin.api.openflow.statistics;
-import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
+import org.opendaylight.openflowplugin.api.openflow.OFPManager;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceLifecycleSupervisor;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
/**
- * Created by Martin Bobak <mbobak@cisco.com> on 26.2.2015.
+ * Manager to start or stop scheduling statistics
*/
public interface StatisticsManager extends DeviceLifecycleSupervisor, DeviceInitializationPhaseHandler,
- DeviceTerminationPhaseHandler, AutoCloseable {
+ DeviceTerminationPhaseHandler, AutoCloseable, OFPManager {
- void startScheduling(NodeId nodeId);
- void stopScheduling(NodeId nodeId);
+ void startScheduling(DeviceInfo deviceInfo);
+ void stopScheduling(DeviceInfo deviceInfo);
@Override
void close();
type non-zero-uint32-type;
default 2000;
}
+
+ leaf thread-pool-min-threads {
+ description "Mininum (starting) number of threads in thread pool";
+ type uint16;
+ default 1;
+ }
+
+ leaf thread-pool-max-threads {
+ description "Maximum number of threads in thread pool";
+ type non-zero-uint16-type;
+ default 32000;
+ }
+
+ leaf thread-pool-timeout {
+ description "After how much time (in seconds) of inactivity will be threads in pool terminated";
+ type uint32;
+ default 60;
+ }
}
}
\ No newline at end of file
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
+import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
+import org.opendaylight.openflowplugin.api.openflow.OFPManager;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.DeviceContextChangeListener;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.RoleChangeListener;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.ServiceChangeListener;
+import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
+import org.opendaylight.openflowplugin.api.openflow.rpc.RpcManager;
+import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
+import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
+import org.opendaylight.openflowplugin.impl.util.MdSalRegistrationUtils;
import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*/
-public final class LifecycleConductorImpl implements LifecycleConductor, RoleChangeListener, DeviceContextChangeListener {
+final class LifecycleConductorImpl implements LifecycleConductor, RoleChangeListener, DeviceContextChangeListener, ExtensionConverterProviderKeeper {
private static final Logger LOG = LoggerFactory.getLogger(LifecycleConductorImpl.class);
private static final int TICKS_PER_WHEEL = 500;
private static final long TICK_DURATION = 10; // 0.5 sec.
private final HashedWheelTimer hashedWheelTimer = new HashedWheelTimer(TICK_DURATION, TimeUnit.MILLISECONDS, TICKS_PER_WHEEL);
+ private ExtensionConverterProvider extensionConverterProvider;
private DeviceManager deviceManager;
- private final MessageIntelligenceAgency messageIntelligenceAgency;
- private ConcurrentHashMap<NodeId, ServiceChangeListener> serviceChangeListeners = new ConcurrentHashMap<>();
private StatisticsManager statisticsManager;
+ private RpcManager rpcManager;
+ private final MessageIntelligenceAgency messageIntelligenceAgency;
+ private ConcurrentHashMap<DeviceInfo, ServiceChangeListener> serviceChangeListeners = new ConcurrentHashMap<>();
+ private NotificationPublishService notificationPublishService;
- public LifecycleConductorImpl(final MessageIntelligenceAgency messageIntelligenceAgency) {
- Preconditions.checkNotNull(messageIntelligenceAgency);
- this.messageIntelligenceAgency = messageIntelligenceAgency;
+ LifecycleConductorImpl(final MessageIntelligenceAgency messageIntelligenceAgency) {
+ this.messageIntelligenceAgency = Preconditions.checkNotNull(messageIntelligenceAgency);
}
- public void setSafelyDeviceManager(final DeviceManager deviceManager) {
- if (this.deviceManager == null) {
- this.deviceManager = deviceManager;
- }
+ @Override
+ public ExtensionConverterProvider getExtensionConverterProvider() {
+ return extensionConverterProvider;
+ }
+
+ @Override
+ public void setExtensionConverterProvider(ExtensionConverterProvider extensionConverterProvider) {
+ this.extensionConverterProvider = extensionConverterProvider;
}
- public void setSafelyStatisticsManager(final StatisticsManager statisticsManager) {
- if (this.statisticsManager == null) {
- this.statisticsManager = statisticsManager;
+ @Override
+ public void setSafelyManager(final OFPManager manager){
+ if (manager instanceof RpcManager) {
+ if (rpcManager != null) {
+ LOG.info("RPC manager {} is already defined in conductor. ", manager);
+ return;
+ }
+ this.rpcManager = (RpcManager) manager;
+ } else {
+ if (manager instanceof StatisticsManager) {
+ if (statisticsManager != null) {
+ LOG.info("Statistics manager {} is already defined in conductor. ", manager);
+ return;
+ }
+ this.statisticsManager = (StatisticsManager) manager;
+ } else {
+ if (manager instanceof DeviceManager) {
+ if (deviceManager != null) {
+ LOG.info("Device manager {} is already defined in conductor. ", manager);
+ return;
+ }
+ this.deviceManager = (DeviceManager) manager;
+ }
+ }
}
}
- public void addOneTimeListenerWhenServicesChangesDone(final ServiceChangeListener manager, final NodeId nodeId){
- LOG.debug("Listener {} for service change for node {} registered.", manager, nodeId);
- serviceChangeListeners.put(nodeId, manager);
+ @Override
+ public void addOneTimeListenerWhenServicesChangesDone(final ServiceChangeListener manager, final DeviceInfo deviceInfo){
+ LOG.debug("Listener {} for service change for node {} registered.", manager, deviceInfo.getNodeId());
+ serviceChangeListeners.put(deviceInfo, manager);
}
@VisibleForTesting
- void notifyServiceChangeListeners(final NodeId nodeId, final boolean success){
+ void notifyServiceChangeListeners(final DeviceInfo deviceInfo, final boolean success){
if (serviceChangeListeners.size() == 0) {
return;
}
LOG.debug("Notifying registered listeners for service change, no. of listeners {}", serviceChangeListeners.size());
- for (final Map.Entry<NodeId, ServiceChangeListener> nodeIdServiceChangeListenerEntry : serviceChangeListeners.entrySet()) {
- if (nodeIdServiceChangeListenerEntry.getKey().equals(nodeId)) {
- LOG.debug("Listener {} for service change for node {} was notified. Success was set on {}", nodeIdServiceChangeListenerEntry.getValue(), nodeId, success);
- nodeIdServiceChangeListenerEntry.getValue().servicesChangeDone(nodeId, success);
- serviceChangeListeners.remove(nodeId);
+ for (final Map.Entry<DeviceInfo, ServiceChangeListener> nodeIdServiceChangeListenerEntry : serviceChangeListeners.entrySet()) {
+ if (nodeIdServiceChangeListenerEntry.getKey().equals(deviceInfo)) {
+ LOG.debug("Listener {} for service change for node {} was notified. Success was set on {}", nodeIdServiceChangeListenerEntry.getValue(), deviceInfo, success);
+ nodeIdServiceChangeListenerEntry.getValue().servicesChangeDone(deviceInfo, success);
+ serviceChangeListeners.remove(deviceInfo);
}
}
}
@Override
- public void roleInitializationDone(final NodeId nodeId, final boolean success) {
+ public void roleInitializationDone(final DeviceInfo deviceInfo, final boolean success) {
if (!success) {
- LOG.warn("Initialization phase for node {} in role context was NOT successful, closing connection.", nodeId);
- closeConnection(nodeId);
+ LOG.warn("Initialization phase for node {} in role context was NOT successful, closing connection.", deviceInfo);
+ closeConnection(deviceInfo);
} else {
- LOG.info("initialization phase for node {} in role context was successful, continuing to next context.", nodeId);
+ LOG.info("initialization phase for node {} in role context was successful, continuing to next context.", deviceInfo);
}
}
- public void closeConnection(final NodeId nodeId) {
- LOG.debug("Close connection called for node {}", nodeId);
- final DeviceContext deviceContext = getDeviceContext(nodeId);
+ public void closeConnection(final DeviceInfo deviceInfo) {
+ LOG.debug("Close connection called for node {}", deviceInfo);
+ final DeviceContext deviceContext = getDeviceContext(deviceInfo);
if (null != deviceContext) {
+ deviceManager.notifyDeviceValidListeners(deviceInfo, false);
deviceContext.shutdownConnection();
}
}
@Override
- public void roleChangeOnDevice(final NodeId nodeId, final boolean success, final OfpRole newRole, final boolean initializationPhase) {
+ public void roleChangeOnDevice(final DeviceInfo deviceInfo, final boolean success, final OfpRole newRole, final boolean initializationPhase) {
- final DeviceContext deviceContext = getDeviceContext(nodeId);
+ final DeviceContext deviceContext = getDeviceContext(deviceInfo);
if (null == deviceContext) {
LOG.warn("Something went wrong, device context for nodeId: {} doesn't exists");
return;
}
if (!success) {
- LOG.warn("Role change to {} in role context for node {} was NOT successful, closing connection", newRole, nodeId);
- closeConnection(nodeId);
+ LOG.warn("Role change to {} in role context for node {} was NOT successful, closing connection", newRole, deviceInfo);
+ closeConnection(deviceInfo);
} else {
if (initializationPhase) {
LOG.debug("Initialization phase skipping starting services.");
return;
}
- LOG.info("Role change to {} in role context for node {} was successful, starting/stopping services.", newRole, nodeId);
+ LOG.info("Role change to {} in role context for node {} was successful.", newRole, deviceInfo);
+
+ final String logText;
if (OfpRole.BECOMEMASTER.equals(newRole)) {
- statisticsManager.startScheduling(nodeId);
+ logText = "Start";
+ statisticsManager.startScheduling(deviceInfo);
+ MdSalRegistrationUtils.registerMasterServices(
+ rpcManager.gainContext(deviceInfo),
+ deviceContext,
+ OfpRole.BECOMEMASTER,
+ this.extensionConverterProvider);
+ if (((RpcContext)rpcManager.gainContext(deviceInfo)).isStatisticsRpcEnabled()) {
+ MdSalRegistrationUtils.registerStatCompatibilityServices(
+ rpcManager.gainContext(deviceInfo),
+ deviceManager.gainContext(deviceInfo),
+ notificationPublishService,
+ new AtomicLong());
+ }
} else {
- statisticsManager.stopScheduling(nodeId);
+ logText = "Stopp";
+ statisticsManager.stopScheduling(deviceInfo);
+ MdSalRegistrationUtils.registerSlaveServices(
+ rpcManager.gainContext(deviceInfo),
+ OfpRole.BECOMESLAVE);
}
- final ListenableFuture<Void> onClusterRoleChange = deviceContext.onClusterRoleChange(null, newRole);
+ final ListenableFuture<Void> onClusterRoleChange = deviceManager.onClusterRoleChange(deviceInfo, newRole);
Futures.addCallback(onClusterRoleChange, new FutureCallback<Void>() {
@Override
public void onSuccess(@Nullable final Void aVoid) {
- LOG.info("Starting/Stopping services for node {} was successful", nodeId);
- if (newRole.equals(OfpRole.BECOMESLAVE)) notifyServiceChangeListeners(nodeId, true);
+ LOG.info("{}ing services for node {} was successful", logText, deviceInfo);
+ if (newRole.equals(OfpRole.BECOMESLAVE)) notifyServiceChangeListeners(deviceInfo, true);
}
@Override
public void onFailure(final Throwable throwable) {
- LOG.warn("Starting/Stopping services for node {} was NOT successful, closing connection", nodeId);
- closeConnection(nodeId);
+ LOG.warn("{}ing services for node {} was NOT successful, closing connection", logText, deviceInfo);
+ closeConnection(deviceInfo);
}
});
}
}
@Override
- public DeviceContext getDeviceContext(final NodeId nodeId){
- return deviceManager.getDeviceContextFromNodeId(nodeId);
+ public DeviceContext getDeviceContext(DeviceInfo deviceInfo){
+ return deviceManager.gainContext(deviceInfo);
}
- public Short gainVersionSafely(final NodeId nodeId) {
- return (null != getDeviceContext(nodeId)) ? getDeviceContext(nodeId).getPrimaryConnectionContext().getFeatures().getVersion() : null;
+ @Override
+ public StatisticsContext getStatisticsContext(DeviceInfo deviceInfo){
+ return statisticsManager.gainContext(deviceInfo);
}
public Timeout newTimeout(@Nonnull TimerTask task, long delay, @Nonnull TimeUnit unit) {
return hashedWheelTimer.newTimeout(task, delay, unit);
}
- public ConnectionContext.CONNECTION_STATE gainConnectionStateSafely(final NodeId nodeId){
- return (null != getDeviceContext(nodeId)) ? getDeviceContext(nodeId).getPrimaryConnectionContext().getConnectionState() : null;
+ @Override
+ public ConnectionContext.CONNECTION_STATE gainConnectionStateSafely(final DeviceInfo deviceInfo){
+ return (null != getDeviceContext(deviceInfo)) ? getDeviceContext(deviceInfo).getPrimaryConnectionContext().getConnectionState() : null;
}
- public Long reserveXidForDeviceMessage(final NodeId nodeId){
- return null != getDeviceContext(nodeId) ? getDeviceContext(nodeId).reserveXidForDeviceMessage() : null;
+ @Override
+ public Long reserveXidForDeviceMessage(final DeviceInfo deviceInfo){
+ return null != getDeviceContext(deviceInfo) ? getDeviceContext(deviceInfo).reserveXidForDeviceMessage() : null;
}
@Override
- public void deviceStartInitializationDone(final NodeId nodeId, final boolean success) {
+ public void deviceStartInitializationDone(final DeviceInfo deviceInfo, final boolean success) {
if (!success) {
- LOG.warn("Initialization phase for node {} in device context was NOT successful, closing connection.", nodeId);
- closeConnection(nodeId);
+ LOG.warn("Initialization phase for node {} in device context was NOT successful, closing connection.", deviceInfo);
+ closeConnection(deviceInfo);
} else {
- LOG.info("initialization phase for node {} in device context was successful. Continuing to next context.", nodeId);
+ LOG.info("initialization phase for node {} in device context was successful. Continuing to next context.", deviceInfo);
}
}
@Override
- public void deviceInitializationDone(final NodeId nodeId, final boolean success) {
+ public void deviceInitializationDone(final DeviceInfo deviceInfo, final boolean success) {
if (!success) {
- LOG.warn("Initialization phase for node {} in device context was NOT successful, closing connection.", nodeId);
- closeConnection(nodeId);
+ LOG.warn("Initialization phase for node {} in device context was NOT successful, closing connection.", deviceInfo);
+ closeConnection(deviceInfo);
} else {
- LOG.info("initialization phase for node {} in device context was successful. All phases initialized OK.", nodeId);
+ LOG.info("initialization phase for node {} in device context was successful. All phases initialized OK.", deviceInfo);
}
}
@VisibleForTesting
- public boolean isServiceChangeListenersEmpty() {
+ boolean isServiceChangeListenersEmpty() {
return this.serviceChangeListeners.isEmpty();
}
+ @Override
+ public NotificationPublishService getNotificationPublishService() {
+ return notificationPublishService;
+ }
+
+ @Override
+ public void setNotificationPublishService(NotificationPublishService notificationPublishService) {
+ this.notificationPublishService = notificationPublishService;
+ }
}
LOG.info("Initializing new OFP southbound.");
OpenflowPortsUtil.init();
- OpenFlowPluginProvider openflowPluginProvider = new OpenFlowPluginProviderImpl(providerConfig.getRpcRequestsQuota(),
- providerConfig.getGlobalNotificationQuota());
+ OpenFlowPluginProvider openflowPluginProvider = new OpenFlowPluginProviderImpl(
+ providerConfig.getRpcRequestsQuota(),
+ providerConfig.getGlobalNotificationQuota(),
+ providerConfig.getThreadPoolMinThreads(),
+ providerConfig.getThreadPoolMaxThreads().getValue(),
+ providerConfig.getThreadPoolTimeout());
openflowPluginProvider.setSwitchConnectionProviders(switchConnectionProviders);
openflowPluginProvider.setDataBroker(dataBroker);
openflowPluginProvider.initialize();
- LOG.info("Configured values, StatisticsPollingOff:{}, SwitchFeaturesMandatory:{}, BarrierCountLimit:{}, BarrierTimeoutLimit:{}, EchoReplyTimeout:{}",
- providerConfig.isIsStatisticsPollingOff(), providerConfig.isSwitchFeaturesMandatory(),
+ LOG.info("Configured values, " +
+ "StatisticsPollingOff:{}, " +
+ "SwitchFeaturesMandatory:{}, " +
+ "BarrierCountLimit:{}, " +
+ "BarrierTimeoutLimit:{}, " +
+ "EchoReplyTimeout:{}, " +
+ "ThreadPoolMinThreads:{}, " +
+ "ThreadPoolMaxThreads:{}, " +
+ "ThreadPoolTimeout:{}",
+ providerConfig.isIsStatisticsPollingOff(),
+ providerConfig.isSwitchFeaturesMandatory(),
providerConfig.getBarrierCountLimit().getValue(),
- providerConfig.getBarrierIntervalTimeoutLimit().getValue(), providerConfig.getEchoReplyTimeout().getValue());
+ providerConfig.getBarrierIntervalTimeoutLimit().getValue(),
+ providerConfig.getEchoReplyTimeout().getValue(),
+ providerConfig.getThreadPoolMinThreads(),
+ providerConfig.getThreadPoolMaxThreads().getValue(),
+ providerConfig.getThreadPoolTimeout());
return openflowPluginProvider;
}
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
+import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.MessageIntelligenceAgencyImpl;
import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.MessageIntelligenceAgencyMXBean;
import org.opendaylight.openflowplugin.impl.util.TranslatorLibraryUtil;
+import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor;
import org.opendaylight.openflowplugin.openflow.md.core.extension.ExtensionConverterManagerImpl;
import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil;
import org.slf4j.Logger;
private boolean isStatisticsRpcEnabled;
private final LifecycleConductor conductor;
+ private final ThreadPoolExecutor threadPool;
- public OpenFlowPluginProviderImpl(final long rpcRequestsQuota, final Long globalNotificationQuota) {
+ public OpenFlowPluginProviderImpl(final long rpcRequestsQuota,
+ final long globalNotificationQuota,
+ final int threadPoolMinThreads,
+ final int threadPoolMaxThreads,
+ final long threadPoolTimeout) {
Preconditions.checkArgument(rpcRequestsQuota > 0 && rpcRequestsQuota <= Integer.MAX_VALUE, "rpcRequestQuota has to be in range <1,%s>", Integer.MAX_VALUE);
this.rpcRequestsQuota = (int) rpcRequestsQuota;
this.globalNotificationQuota = Preconditions.checkNotNull(globalNotificationQuota);
+
+ // Creates a thread pool that creates new threads as needed, but will reuse previously
+ // constructed threads when they are available.
+ // Threads that have not been used for x seconds are terminated and removed from the cache.
+ threadPool = new ThreadPoolLoggingExecutor(
+ Preconditions.checkNotNull(threadPoolMinThreads),
+ Preconditions.checkNotNull(threadPoolMaxThreads),
+ Preconditions.checkNotNull(threadPoolTimeout), TimeUnit.SECONDS,
+ new SynchronousQueue<>(), "ofppool");
+
conductor = new LifecycleConductorImpl(messageIntelligenceAgency);
}
@Override
public void initialize() {
-
Preconditions.checkNotNull(dataBroker, "missing data broker");
Preconditions.checkNotNull(rpcProviderRegistry, "missing RPC provider registry");
Preconditions.checkNotNull(notificationProviderService, "missing notification provider service");
// TODO: rewrite later!
OFSessionUtil.getSessionManager().setExtensionConverterProvider(extensionConverterManager);
- connectionManager = new ConnectionManagerImpl(echoReplyTimeout);
+ connectionManager = new ConnectionManagerImpl(echoReplyTimeout, threadPool);
registerMXBean(messageIntelligenceAgency);
barrierInterval,
barrierCountLimit,
conductor);
+ ((ExtensionConverterProviderKeeper) conductor).setExtensionConverterProvider(extensionConverterManager);
((ExtensionConverterProviderKeeper) deviceManager).setExtensionConverterProvider(extensionConverterManager);
- conductor.setSafelyDeviceManager(deviceManager);
+ conductor.setSafelyManager(deviceManager);
+ conductor.setNotificationPublishService(notificationPublishService);
roleManager = new RoleManagerImpl(entityOwnershipService, dataBroker, conductor);
statisticsManager = new StatisticsManagerImpl(rpcProviderRegistry, isStatisticsPollingOff, conductor);
- conductor.setSafelyStatisticsManager(statisticsManager);
+ conductor.setSafelyManager(statisticsManager);
+
rpcManager = new RpcManagerImpl(rpcProviderRegistry, rpcRequestsQuota, conductor);
+ conductor.setSafelyManager(rpcManager);
roleManager.addRoleChangeListener((RoleChangeListener) conductor);
statisticsManager.setDeviceTerminationPhaseHandler(roleManager);
roleManager.setDeviceTerminationPhaseHandler(deviceManager);
- deviceManager.setStatisticsRpcEnabled(isStatisticsRpcEnabled);
- deviceManager.setNotificationPublishService(notificationPublishService);
+ rpcManager.setStatisticsRpcEnabled(isStatisticsRpcEnabled);
TranslatorLibraryUtil.setBasicTranslatorLibrary(deviceManager);
deviceManager.initialize();
// TODO: needs to close org.opendaylight.openflowplugin.impl.role.OpenflowOwnershipListener after RoleContexts are down
// TODO: must not be executed prior to all living RoleContexts have been closed (via closing living DeviceContexts)
roleManager.close();
+
+ // Manually shutdown all remaining running threads in pool
+ threadPool.shutdown();
}
}
package org.opendaylight.openflowplugin.impl.connection;
+import com.google.common.base.Preconditions;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-
import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.connection.HandshakeContext;
import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceDisconnectedHandler;
import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.SessionStatistics;
+import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
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.NodeKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
+import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private OutboundQueueProvider outboundQueueProvider;
private OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration;
private HandshakeContext handshakeContext;
+ private DeviceInfo deviceInfo;
/**
* @param connectionAdapter
connectionState = CONNECTION_STATE.WORKING;
}
+ @Override
+ public DeviceInfo getDeviceInfo() {
+ return this.deviceInfo;
+ }
+
+ @Override
+ public void handshakeSuccessful() {
+ Preconditions.checkNotNull(nodeId, "Cannot create DeviceInfo if 'NodeId' is not set!");
+ Preconditions.checkNotNull(featuresReply, "Cannot create DeviceInfo if 'features' is not set!");
+ this.deviceInfo = new DeviceInfoImpl(
+ nodeId,
+ DeviceStateUtil.createNodeInstanceIdentifier(nodeId),
+ featuresReply.getVersion(),
+ featuresReply.getDatapathId());
+ }
+
@Override
public void setHandshakeContext(HandshakeContext handshakeContext) {
this.handshakeContext = handshakeContext;
}
+
+
+ private class DeviceInfoImpl implements DeviceInfo {
+
+ final private NodeId nodeId;
+ final private KeyedInstanceIdentifier<Node, NodeKey> nodeII;
+ final private Short version;
+ final private BigInteger datapathId;
+
+ DeviceInfoImpl(
+ final NodeId nodeId,
+ final KeyedInstanceIdentifier<Node, NodeKey> nodeII,
+ final Short version,
+ final BigInteger datapathId) {
+ this.nodeId = nodeId;
+ this.nodeII = nodeII;
+ this.version = version;
+ this.datapathId = datapathId;
+ }
+
+ @Override
+ public NodeId getNodeId() {
+ return nodeId;
+ }
+
+ @Override
+ public KeyedInstanceIdentifier<Node, NodeKey> getNodeInstanceIdentifier() {
+ return nodeII;
+ }
+
+ @Override
+ public Short getVersion() {
+ return version;
+ }
+
+ @Override
+ public BigInteger getDatapathId() {
+ return datapathId;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ DeviceInfoImpl that = (DeviceInfoImpl) o;
+
+ if (!nodeId.equals(that.nodeId)) return false;
+ if (!nodeII.equals(that.nodeII)) return false;
+ if (!version.equals(that.version)) return false;
+ return datapathId.equals(that.datapathId);
+
+ }
+
+ @Override
+ public int hashCode() {
+ int result = nodeId.hashCode();
+ result = 31 * result + nodeII.hashCode();
+ result = 31 * result + version.hashCode();
+ result = 31 * result + datapathId.hashCode();
+ return result;
+ }
+ }
}
package org.opendaylight.openflowplugin.impl.connection;
import java.net.InetAddress;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
+import java.util.concurrent.ThreadPoolExecutor;
import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.impl.connection.listener.SystemNotificationsListenerImpl;
import org.opendaylight.openflowplugin.openflow.md.core.ErrorHandlerSimpleImpl;
import org.opendaylight.openflowplugin.openflow.md.core.HandshakeManagerImpl;
-import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener;
import org.slf4j.Logger;
private final boolean bitmapNegotiationEnabled = true;
private DeviceConnectedHandler deviceConnectedHandler;
private final long echoReplyTimeout;
+ private final ThreadPoolExecutor threadPool;
- public ConnectionManagerImpl(long echoReplyTimeout) {
+ public ConnectionManagerImpl(long echoReplyTimeout, final ThreadPoolExecutor threadPool) {
this.echoReplyTimeout = echoReplyTimeout;
+ this.threadPool = threadPool;
}
-
@Override
public void onSwitchConnected(final ConnectionAdapter connectionAdapter) {
-
- LOG.trace("preparing handshake: {}", connectionAdapter.getRemoteAddress());
-
- final int handshakeThreadLimit = 1;
- final ThreadPoolLoggingExecutor handshakePool = createHandshakePool(
- connectionAdapter.getRemoteAddress().toString(), handshakeThreadLimit);
-
LOG.trace("prepare connection context");
final ConnectionContext connectionContext = new ConnectionContextImpl(connectionAdapter);
final HandshakeManager handshakeManager = createHandshakeManager(connectionAdapter, handshakeListener);
LOG.trace("prepare handshake context");
- HandshakeContext handshakeContext = new HandshakeContextImpl(handshakePool, handshakeManager);
+ HandshakeContext handshakeContext = new HandshakeContextImpl(threadPool, handshakeManager);
handshakeListener.setHandshakeContext(handshakeContext);
connectionContext.setHandshakeContext(handshakeContext);
new OpenflowProtocolListenerInitialImpl(connectionContext, handshakeContext);
connectionAdapter.setMessageListener(ofMessageListener);
- final SystemNotificationsListener systemListener = new SystemNotificationsListenerImpl(connectionContext, echoReplyTimeout);
+ final SystemNotificationsListener systemListener = new SystemNotificationsListenerImpl(connectionContext, echoReplyTimeout, threadPool);
connectionAdapter.setSystemListener(systemListener);
LOG.trace("connection ballet finished");
}
- /**
- * @param connectionIdentifier
- * @param handshakeThreadLimit
- * @return
- */
- private static ThreadPoolLoggingExecutor createHandshakePool(
- final String connectionIdentifier, final int handshakeThreadLimit) {
- return new ThreadPoolLoggingExecutor(handshakeThreadLimit,
- handshakeThreadLimit, 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue<>(HELLO_LIMIT), "OFHandshake-" + connectionIdentifier);
- }
-
/**
* @param connectionAdapter
* @param handshakeListener
return bitmapNegotiationEnabled;
}
-
@Override
public boolean accept(final InetAddress switchAddress) {
// TODO add connection accept logic based on address
connectionContext.changeStateToWorking();
connectionContext.setFeatures(featureOutput);
connectionContext.setNodeId(InventoryDataServiceUtil.nodeIdFromDatapathId(featureOutput.getDatapathId()));
+ connectionContext.handshakeSuccessful();
// fire barrier in order to sweep all handshake and posthandshake messages before continue
final ListenableFuture<RpcResult<BarrierOutput>> barrier = fireBarrier(version, 0L);
import java.net.InetSocketAddress;
import java.util.Date;
import java.util.concurrent.Future;
+import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
@VisibleForTesting
static final long MAX_ECHO_REPLY_TIMEOUT = 2000;
private final long echoReplyTimeout;
+ private final ThreadPoolExecutor threadPool;
- public SystemNotificationsListenerImpl(@Nonnull final ConnectionContext connectionContext, long echoReplyTimeout) {
+ public SystemNotificationsListenerImpl(@Nonnull final ConnectionContext connectionContext,
+ long echoReplyTimeout,
+ @Nonnull final ThreadPoolExecutor threadPool) {
+ this.threadPool = threadPool;
this.connectionContext = Preconditions.checkNotNull(connectionContext);
this.echoReplyTimeout = echoReplyTimeout;
}
@Override
public void onSwitchIdleEvent(final SwitchIdleEvent notification) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- boolean shouldBeDisconnected = true;
+ threadPool.execute(() -> {
+ boolean shouldBeDisconnected = true;
- final InetSocketAddress remoteAddress = connectionContext.getConnectionAdapter().getRemoteAddress();
+ final InetSocketAddress remoteAddress = connectionContext.getConnectionAdapter().getRemoteAddress();
- if (ConnectionContext.CONNECTION_STATE.WORKING.equals(connectionContext.getConnectionState())) {
- FeaturesReply features = connectionContext.getFeatures();
- LOG.info("Switch Idle state occurred, node={}|auxId={}", remoteAddress, features.getAuxiliaryId());
- connectionContext.changeStateToTimeouting();
- EchoInputBuilder builder = new EchoInputBuilder();
- builder.setVersion(features.getVersion());
- Xid xid = new Xid(0L);
- builder.setXid(xid.getValue());
+ if (ConnectionContext.CONNECTION_STATE.WORKING.equals(connectionContext.getConnectionState())) {
+ FeaturesReply features = connectionContext.getFeatures();
+ LOG.info("Switch Idle state occurred, node={}|auxId={}", remoteAddress, features.getAuxiliaryId());
+ connectionContext.changeStateToTimeouting();
+ EchoInputBuilder builder = new EchoInputBuilder();
+ builder.setVersion(features.getVersion());
+ Xid xid = new Xid(0L);
+ builder.setXid(xid.getValue());
- Future<RpcResult<EchoOutput>> echoReplyFuture = connectionContext.getConnectionAdapter().echo(builder.build());
+ Future<RpcResult<EchoOutput>> echoReplyFuture = connectionContext.getConnectionAdapter().echo(builder.build());
- try {
- RpcResult<EchoOutput> echoReplyValue = echoReplyFuture.get(echoReplyTimeout, TimeUnit.MILLISECONDS);
- if (echoReplyValue.isSuccessful()) {
- connectionContext.changeStateToWorking();
- shouldBeDisconnected = false;
- } else {
- for (RpcError replyError : echoReplyValue.getErrors()) {
- Throwable cause = replyError.getCause();
- if (LOG.isWarnEnabled()) {
- LOG.warn("Received EchoReply from [{}] in TIMEOUTING state, Error:{}", remoteAddress, cause.getMessage());
- }
-
- if (LOG.isTraceEnabled()) {
- LOG.trace("Received EchoReply from [{}] in TIMEOUTING state, Error:{}", remoteAddress, cause);
- }
+ try {
+ RpcResult<EchoOutput> echoReplyValue = echoReplyFuture.get(echoReplyTimeout, TimeUnit.MILLISECONDS);
+ if (echoReplyValue.isSuccessful()) {
+ connectionContext.changeStateToWorking();
+ shouldBeDisconnected = false;
+ } else {
+ for (RpcError replyError : echoReplyValue.getErrors()) {
+ Throwable cause = replyError.getCause();
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Received EchoReply from [{}] in TIMEOUTING state, Error:{}", remoteAddress, cause.getMessage());
+ }
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Received EchoReply from [{}] in TIMEOUTING state, Error:{}", remoteAddress, cause);
}
- }
- } catch (Exception e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Exception while waiting for echoReply from [{}] in TIMEOUTING state: {}", remoteAddress, e.getMessage());
- }
- if (LOG.isTraceEnabled()) {
- LOG.trace("Exception while waiting for echoReply from [{}] in TIMEOUTING state: {}", remoteAddress, e);
}
-
}
- }
- if (shouldBeDisconnected) {
- if (LOG.isInfoEnabled()) {
- LOG.info("ConnectionEvent:Closing connection as device is idle. Echo sent at {}. Device:{}, NodeId:{}",
- new Date(System.currentTimeMillis() - echoReplyTimeout), remoteAddress, connectionContext.getNodeId());
+ } catch (Exception e) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Exception while waiting for echoReply from [{}] in TIMEOUTING state: {}", remoteAddress, e.getMessage());
+ }
+
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Exception while waiting for echoReply from [{}] in TIMEOUTING state: {}", remoteAddress, e);
}
- connectionContext.closeConnection(true);
}
}
- }).start();
+ if (shouldBeDisconnected) {
+ if (LOG.isInfoEnabled()) {
+ LOG.info("ConnectionEvent:Closing connection as device is idle. Echo sent at {}. Device:{}, NodeId:{}",
+ new Date(System.currentTimeMillis() - echoReplyTimeout), remoteAddress, connectionContext.getNodeId());
+ }
+
+ connectionContext.closeConnection(true);
+ }
+ });
}
}
package org.opendaylight.openflowplugin.impl.device;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Verify;
-import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicLong;
-import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleKeeper;
-import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
-import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
import org.opendaylight.openflowplugin.extension.api.ConvertorMessageFromOFJava;
import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
import org.opendaylight.openflowplugin.impl.registry.group.DeviceGroupRegistryImpl;
import org.opendaylight.openflowplugin.impl.registry.meter.DeviceMeterRegistryImpl;
-import org.opendaylight.openflowplugin.impl.util.DeviceInitializationUtils;
-import org.opendaylight.openflowplugin.impl.util.MdSalRegistrationUtils;
import org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl;
import org.opendaylight.yang.gen.v1.urn.opendaylight.experimenter.message.service.rev151020.ExperimenterMessageFromDevBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
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.NodeConnectorBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsData;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsDataBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
private final MessageTranslator<PacketInMessage, PacketReceived> packetInTranslator;
private final MessageTranslator<FlowRemoved, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved> flowRemovedTranslator;
private final TranslatorLibrary translatorLibrary;
- private final Map<Long, NodeConnectorRef> nodeConnectorCache;
private final ItemLifeCycleRegistry itemLifeCycleSourceRegistry;
- private RpcContext rpcContext;
private ExtensionConverterProvider extensionConverterProvider;
- private final boolean switchFeaturesMandatory;
- private StatisticsContext statisticsContext;
-
- private final NodeId nodeId;
-
- private volatile DEVICE_CONTEXT_STATE deviceCtxState;
- private boolean isStatisticsRpcEnabled;
+ private final DeviceInfo deviceInfo;
+ private volatile CONTEXT_STATE contextState;
@VisibleForTesting
DeviceContextImpl(@Nonnull final ConnectionContext primaryConnectionContext,
@Nonnull final DataBroker dataBroker,
@Nonnull final LifecycleConductor conductor,
@Nonnull final OutboundQueueProvider outboundQueueProvider,
- @Nonnull final TranslatorLibrary translatorLibrary,
- final boolean switchFeaturesMandatory) {
- this.switchFeaturesMandatory = switchFeaturesMandatory;
+ @Nonnull final TranslatorLibrary translatorLibrary) {
this.primaryConnectionContext = Preconditions.checkNotNull(primaryConnectionContext);
this.deviceState = Preconditions.checkNotNull(deviceState);
this.dataBroker = Preconditions.checkNotNull(dataBroker);
Preconditions.checkNotNull(conductor);
this.outboundQueueProvider = Preconditions.checkNotNull(outboundQueueProvider);
- this.transactionChainManager = new TransactionChainManager(dataBroker, deviceState, conductor);
+ deviceInfo = primaryConnectionContext.getDeviceInfo();
+ this.transactionChainManager = new TransactionChainManager(dataBroker, deviceInfo, conductor);
auxiliaryConnectionContexts = new HashMap<>();
deviceFlowRegistry = new DeviceFlowRegistryImpl();
deviceGroupRegistry = new DeviceGroupRegistryImpl();
deviceMeterRegistry = new DeviceMeterRegistryImpl();
messageSpy = conductor.getMessageIntelligenceAgency();
+
packetInLimiter = new PacketInRateLimiter(primaryConnectionContext.getConnectionAdapter(),
/*initial*/ 1000, /*initial*/2000, messageSpy, REJECTED_DRAIN_FACTOR);
this.translatorLibrary = translatorLibrary;
portStatusTranslator = translatorLibrary.lookupTranslator(
- new TranslatorKey(deviceState.getVersion(), PortGrouping.class.getName()));
+ new TranslatorKey(deviceInfo.getVersion(), PortGrouping.class.getName()));
packetInTranslator = translatorLibrary.lookupTranslator(
- new TranslatorKey(deviceState.getVersion(), PacketIn.class.getName()));
+ new TranslatorKey(deviceInfo.getVersion(), PacketIn.class.getName()));
flowRemovedTranslator = translatorLibrary.lookupTranslator(
- new TranslatorKey(deviceState.getVersion(), FlowRemoved.class.getName()));
-
-
- nodeConnectorCache = new ConcurrentHashMap<>();
+ new TranslatorKey(deviceInfo.getVersion(), FlowRemoved.class.getName()));
itemLifeCycleSourceRegistry = new ItemLifeCycleRegistryImpl();
flowLifeCycleKeeper = new ItemLifeCycleSourceImpl();
itemLifeCycleSourceRegistry.registerLifeCycleSource(flowLifeCycleKeeper);
- deviceCtxState = DEVICE_CONTEXT_STATE.INITIALIZATION;
-
- nodeId = primaryConnectionContext.getNodeId();
+ contextState = CONTEXT_STATE.INITIALIZATION;
}
/**
public void removeAuxiliaryConnectionContext(final ConnectionContext connectionContext) {
final SwitchConnectionDistinguisher connectionDistinguisher = createConnectionDistinguisher(connectionContext);
LOG.debug("auxiliary connection dropped: {}, nodeId:{}", connectionContext.getConnectionAdapter()
- .getRemoteAddress(), nodeId);
+ .getRemoteAddress(), deviceInfo.getNodeId());
auxiliaryConnectionContexts.remove(connectionDistinguisher);
}
}
@Override
- public ReadOnlyTransaction getReadTransaction() {
- return dataBroker.newReadOnlyTransaction();
- }
-
- @Override
- public ListenableFuture<Void> onClusterRoleChange(final OfpRole oldRole, @CheckForNull final OfpRole role) {
- LOG.trace("onClusterRoleChange {} for node:", role, nodeId);
- Preconditions.checkArgument(role != null);
- if (role.equals(oldRole)) {
- LOG.debug("Demanded role change for device {} is not changed. OldRole: {}, NewRole {}", nodeId, oldRole, role);
- return Futures.immediateFuture(null);
- }
- if (OfpRole.BECOMEMASTER.equals(role)) {
- return onDeviceTakeClusterLeadership();
- } else if (OfpRole.BECOMESLAVE.equals(role)) {
- return onDeviceLostClusterLeadership();
- } else {
- LOG.warn("Unknown OFCluster Role {} for Node {}", role, nodeId);
- if (null != rpcContext) {
- MdSalRegistrationUtils.unregisterServices(rpcContext);
- }
- return transactionChainManager.deactivateTransactionManager();
- }
+ public DeviceInfo getDeviceInfo() {
+ return this.deviceInfo;
}
@Override
- public ListenableFuture<Void> onDeviceLostClusterLeadership() {
- LOG.trace("onDeviceLostClusterLeadership for node: {}", nodeId);
- if (null != rpcContext) {
- MdSalRegistrationUtils.registerSlaveServices(rpcContext, OfpRole.BECOMESLAVE);
- }
- return transactionChainManager.deactivateTransactionManager();
- }
-
- @Override
- public ListenableFuture<Void> onDeviceTakeClusterLeadership() {
- LOG.trace("onDeviceTakeClusterLeadership for node: {}", nodeId);
- /* validation */
- if (statisticsContext == null) {
- final String errMsg = String.format("DeviceCtx %s is up but we are missing StatisticsContext", nodeId);
- LOG.warn(errMsg);
- return Futures.immediateFailedFuture(new IllegalStateException(errMsg));
- }
- if (rpcContext == null) {
- final String errMsg = String.format("DeviceCtx %s is up but we are missing RpcContext", nodeId);
- LOG.warn(errMsg);
- return Futures.immediateFailedFuture(new IllegalStateException(errMsg));
- }
- /* Routed RPC registration */
- MdSalRegistrationUtils.registerMasterServices(getRpcContext(), DeviceContextImpl.this, OfpRole.BECOMEMASTER);
-
- if (isStatisticsRpcEnabled) {
- MdSalRegistrationUtils.registerStatCompatibilityServices(getRpcContext(), this,
- notificationPublishService, new AtomicLong());
- }
-
- /* Prepare init info collecting */
- getDeviceState().setDeviceSynchronized(false);
- transactionChainManager.activateTransactionManager();
- /* Init Collecting NodeInfo */
- final ListenableFuture<Void> initCollectingDeviceInfo = DeviceInitializationUtils.initializeNodeInformation(
- DeviceContextImpl.this, switchFeaturesMandatory);
- /* Init Collecting StatInfo */
- final ListenableFuture<Boolean> statPollFuture = Futures.transform(initCollectingDeviceInfo,
- new AsyncFunction<Void, Boolean>() {
-
- @Override
- public ListenableFuture<Boolean> apply(@Nonnull final Void input) throws Exception {
- getStatisticsContext().statListForCollectingInitialization();
- return getStatisticsContext().gatherDynamicData();
- }
- });
-
- return Futures.transform(statPollFuture, new Function<Boolean, Void>() {
-
- @Override
- public Void apply(final Boolean input) {
- if (ConnectionContext.CONNECTION_STATE.RIP.equals(getPrimaryConnectionContext().getConnectionState())) {
- final String errMsg = String.format("We lost connection for Device %s, context has to be closed.",
- getDeviceState().getNodeId());
- LOG.warn(errMsg);
- throw new IllegalStateException(errMsg);
- }
- if (!input) {
- final String errMsg = String.format("Get Initial Device %s information fails",
- getDeviceState().getNodeId());
- LOG.warn(errMsg);
- throw new IllegalStateException(errMsg);
- }
- LOG.debug("Get Initial Device {} information is successful", nodeId);
- getDeviceState().setDeviceSynchronized(true);
- initialSubmitTransaction();
- getDeviceState().setStatisticsPollingEnabledProp(true);
- return null;
- }
- });
+ public ReadOnlyTransaction getReadTransaction() {
+ return dataBroker.newReadOnlyTransaction();
}
@Override
if (itemLifecycleListener != null) {
//1. translate to general flow (table, priority, match, cookie)
final org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved flowRemovedNotification =
- flowRemovedTranslator.translate(flowRemoved, this.getDeviceState(), null);
+ flowRemovedTranslator.translate(flowRemoved, deviceInfo, null);
//2. create registry key
final FlowRegistryKey flowRegKey = FlowRegistryKeyFactory.create(flowRemovedNotification);
//3. lookup flowId
//4. if flowId present:
if (flowDescriptor != null) {
// a) construct flow path
- final KeyedInstanceIdentifier<Flow, FlowKey> flowPath = getDeviceState().getNodeInstanceIdentifier()
+ final KeyedInstanceIdentifier<Flow, FlowKey> flowPath = getDeviceInfo().getNodeInstanceIdentifier()
.augmentation(FlowCapableNode.class)
.child(Table.class, flowDescriptor.getTableKey())
.child(Flow.class, new FlowKey(flowDescriptor.getFlowId()));
notificationPublishService.offerNotification(flowRemovedNotification);
} else {
LOG.debug("flow id not found: nodeId={} tableId={}, priority={}",
- getDeviceState().getNodeId(), flowRegKey.getTableId(), flowRemovedNotification.getPriority());
+ getDeviceInfo().getNodeId(), flowRegKey.getTableId(), flowRemovedNotification.getPriority());
}
}
}
@Override
public void processPortStatusMessage(final PortStatusMessage portStatus) {
messageSpy.spyMessage(portStatus.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS);
- final FlowCapableNodeConnector flowCapableNodeConnector = portStatusTranslator.translate(portStatus, this.getDeviceState(), null);
+ final FlowCapableNodeConnector flowCapableNodeConnector = portStatusTranslator.translate(portStatus, deviceInfo, null);
final KeyedInstanceIdentifier<NodeConnector, NodeConnectorKey> iiToNodeConnector = provideIIToNodeConnector(portStatus.getPortNo(), portStatus.getVersion());
try {
}
private KeyedInstanceIdentifier<NodeConnector, NodeConnectorKey> provideIIToNodeConnector(final long portNo, final short version) {
- final InstanceIdentifier<Node> iiToNodes = deviceState.getNodeInstanceIdentifier();
- final BigInteger dataPathId = deviceState.getFeatures().getDatapathId();
+ final InstanceIdentifier<Node> iiToNodes = deviceInfo.getNodeInstanceIdentifier();
+ final BigInteger dataPathId = deviceInfo.getDatapathId();
final NodeConnectorId nodeConnectorId = NodeStaticReplyTranslatorUtil.nodeConnectorId(dataPathId.toString(), portNo, version);
return iiToNodes.child(NodeConnector.class, new NodeConnectorKey(nodeConnectorId));
}
public void processPacketInMessage(final PacketInMessage packetInMessage) {
messageSpy.spyMessage(packetInMessage.getImplementedInterface(), MessageSpy.STATISTIC_GROUP.FROM_SWITCH);
final ConnectionAdapter connectionAdapter = getPrimaryConnectionContext().getConnectionAdapter();
- final PacketReceived packetReceived = packetInTranslator.translate(packetInMessage, this.getDeviceState(), null);
+ final PacketReceived packetReceived = packetInTranslator.translate(packetInMessage, deviceInfo, null);
if (packetReceived == null) {
LOG.debug("Received a null packet from switch {}", connectionAdapter.getRemoteAddress());
// lookup converter
final ExperimenterDataOfChoice vendorData = notification.getExperimenterDataOfChoice();
final MessageTypeKey<? extends ExperimenterDataOfChoice> key = new MessageTypeKey<>(
- deviceState.getVersion(),
+ deviceInfo.getVersion(),
(Class<? extends ExperimenterDataOfChoice>) vendorData.getImplementedInterface());
final ConvertorMessageFromOFJava<ExperimenterDataOfChoice, MessagePath> messageConverter = extensionConverterProvider.getMessageConverter(key);
if (messageConverter == null) {
LOG.warn("custom converter for {}[OF:{}] not found",
notification.getExperimenterDataOfChoice().getImplementedInterface(),
- deviceState.getVersion());
+ deviceInfo.getVersion());
return;
}
// build notification
try {
messageOfChoice = messageConverter.convert(vendorData, MessagePath.MESSAGE_NOTIFICATION);
final ExperimenterMessageFromDevBuilder experimenterMessageFromDevBld = new ExperimenterMessageFromDevBuilder()
- .setNode(new NodeRef(deviceState.getNodeInstanceIdentifier()))
+ .setNode(new NodeRef(deviceInfo.getNodeInstanceIdentifier()))
.setExperimenterMessageOfChoice(messageOfChoice);
// publish
notificationPublishService.offerNotification(experimenterMessageFromDevBld.build());
public synchronized void close() {
LOG.debug("closing deviceContext: {}, nodeId:{}",
getPrimaryConnectionContext().getConnectionAdapter().getRemoteAddress(),
- getDeviceState().getNodeId());
+ getDeviceInfo().getNodeId());
// NOOP
throw new UnsupportedOperationException("Autocloseble.close will be removed soon");
}
@Override
public void onPublished() {
- Verify.verify(DEVICE_CONTEXT_STATE.INITIALIZATION.equals(deviceCtxState));
- deviceCtxState = DEVICE_CONTEXT_STATE.WORKING;
+ Verify.verify(CONTEXT_STATE.INITIALIZATION.equals(contextState));
+ contextState = CONTEXT_STATE.WORKING;
primaryConnectionContext.getConnectionAdapter().setPacketInFiltering(false);
for (final ConnectionContext switchAuxConnectionContext : auxiliaryConnectionContexts.values()) {
switchAuxConnectionContext.getConnectionAdapter().setPacketInFiltering(false);
return new MultiMsgCollectorImpl(this, requestContext);
}
- @Override
- public NodeConnectorRef lookupNodeConnectorRef(final Long portNumber) {
- return nodeConnectorCache.get(portNumber);
- }
-
- @Override
- public void storeNodeConnectorRef(@Nonnull final Long portNumber, @Nonnull final NodeConnectorRef nodeConnectorRef) {
- nodeConnectorCache.put(
- Preconditions.checkNotNull(portNumber),
- Preconditions.checkNotNull(nodeConnectorRef));
- }
-
@Override
public void updatePacketInRateLimit(final long upperBound) {
packetInLimiter.changeWaterMarks((int) (LOW_WATERMARK_FACTOR * upperBound), (int) (HIGH_WATERMARK_FACTOR * upperBound));
return itemLifeCycleSourceRegistry;
}
- @Override
- public void setRpcContext(final RpcContext rpcContext) {
- this.rpcContext = rpcContext;
- }
-
- @Override
- public RpcContext getRpcContext() {
- return rpcContext;
- }
-
@Override
public void setExtensionConverterProvider(final ExtensionConverterProvider extensionConverterProvider) {
this.extensionConverterProvider = extensionConverterProvider;
return extensionConverterProvider;
}
- @Override
- public void setStatisticsContext(final StatisticsContext statisticsContext) {
- this.statisticsContext = statisticsContext;
- }
-
- @Override
- public StatisticsContext getStatisticsContext() {
- return statisticsContext;
- }
-
@Override
public synchronized void shutdownConnection() {
- LOG.debug("Shutdown method for node {}", nodeId);
- deviceState.setValid(false);
- if (DEVICE_CONTEXT_STATE.TERMINATION.equals(deviceCtxState)) {
- LOG.debug("DeviceCtx for Node {} is in termination process.", nodeId);
+ LOG.debug("Shutdown method for node {}", deviceInfo.getNodeId());
+ if (CONTEXT_STATE.TERMINATION.equals(contextState)) {
+ LOG.debug("DeviceCtx for Node {} is in termination process.", deviceInfo.getNodeId());
return;
}
- deviceCtxState = DEVICE_CONTEXT_STATE.TERMINATION;
+ contextState = CONTEXT_STATE.TERMINATION;
if (ConnectionContext.CONNECTION_STATE.RIP.equals(getPrimaryConnectionContext().getConnectionState())) {
- LOG.debug("ConnectionCtx for Node {} is in RIP state.", deviceState.getNodeId());
+ LOG.debug("ConnectionCtx for Node {} is in RIP state.", deviceInfo.getNodeId());
return;
}
/* Terminate Auxiliary Connection */
deviceMeterRegistry.close();
}
- @Override
- public void setStatisticsRpcEnabled(boolean isStatisticsRpcEnabled) {
- this.isStatisticsRpcEnabled = isStatisticsRpcEnabled;
- }
-
- @Override
- public DEVICE_CONTEXT_STATE getDeviceContextState() {
- return deviceCtxState;
- }
-
@Override
public ListenableFuture<Void> shuttingDownDataStoreTransactions() {
- deviceState.setValid(false);
return transactionChainManager.shuttingDown();
}
TransactionChainManager getTransactionChainManager() {
return this.transactionChainManager;
}
+
+ @Override
+ public CONTEXT_STATE getState() {
+ return this.contextState;
+ }
}
package org.opendaylight.openflowplugin.impl.device;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Verify;
import com.google.common.collect.Iterators;
+import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
-import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import java.util.Collections;
+import java.util.HashSet;
import java.util.Iterator;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
+import org.opendaylight.openflowplugin.api.openflow.OFPContext;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceSynchronizeListener;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceValidListener;
import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
+import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
import org.opendaylight.openflowplugin.impl.connection.OutboundQueueProviderImpl;
import org.opendaylight.openflowplugin.impl.device.listener.OpenflowProtocolListenerFullImpl;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.openflowplugin.impl.util.DeviceInitializationUtils;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private TranslatorLibrary translatorLibrary;
private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
- private NotificationPublishService notificationPublishService;
- private final ConcurrentMap<NodeId, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
+ private final ConcurrentMap<DeviceInfo, DeviceContext> deviceContexts = new ConcurrentHashMap<>();
private final long barrierIntervalNanos;
private final int barrierCountLimit;
private ExtensionConverterProvider extensionConverterProvider;
private ScheduledThreadPoolExecutor spyPool;
+ private Set<DeviceSynchronizeListener> deviceSynchronizedListeners;
+ private Set<DeviceValidListener> deviceValidListeners;
private final LifecycleConductor conductor;
- private boolean isStatisticsRpcEnabled;
public DeviceManagerImpl(@Nonnull final DataBroker dataBroker,
final long globalNotificationQuota, final boolean switchFeaturesMandatory,
this.conductor = lifecycleConductor;
spyPool = new ScheduledThreadPoolExecutor(1);
+ this.deviceSynchronizedListeners = new HashSet<>();
+ this.deviceValidListeners = new HashSet<>();
}
}
@Override
- public void onDeviceContextLevelUp(final NodeId nodeId) throws Exception {
+ public void onDeviceContextLevelUp(@CheckForNull DeviceInfo deviceInfo) throws Exception {
// final phase - we have to add new Device to MD-SAL DataStore
- LOG.debug("Final phase of DeviceContextLevelUp for Node: {} ", nodeId);
- DeviceContext deviceContext = Preconditions.checkNotNull(deviceContexts.get(nodeId));
+ LOG.debug("Final phase of DeviceContextLevelUp for Node: {} ", deviceInfo.getNodeId());
+ DeviceContext deviceContext = Preconditions.checkNotNull(deviceContexts.get(deviceInfo));
((DeviceContextImpl) deviceContext).initialSubmitTransaction();
deviceContext.onPublished();
}
public boolean deviceConnected(@CheckForNull final ConnectionContext connectionContext) throws Exception {
Preconditions.checkArgument(connectionContext != null);
- NodeId nodeId = connectionContext.getNodeId();
+ DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
/**
* This part prevent destroy another device context. Throwing here an exception result to propagate close connection
* in {@link org.opendaylight.openflowplugin.impl.connection.org.opendaylight.openflowplugin.impl.connection.HandshakeContextImpl}
* If context already exist we are in state closing process (connection flapping) and we should not propagate connection close
*/
- if (deviceContexts.containsKey(nodeId)) {
+ if (deviceContexts.containsKey(deviceInfo)) {
LOG.warn("Rejecting connection from node which is already connected and there exist deviceContext for it: {}", connectionContext.getNodeId());
return false;
}
LOG.info("ConnectionEvent: Device connected to controller, Device:{}, NodeId:{}",
- connectionContext.getConnectionAdapter().getRemoteAddress(), nodeId);
+ connectionContext.getConnectionAdapter().getRemoteAddress(), deviceInfo.getNodeId());
// Add Disconnect handler
connectionContext.setDeviceDisconnectedHandler(DeviceManagerImpl.this);
//FIXME: as soon as auxiliary connection are fully supported then this is needed only before device context published
connectionAdapter.setPacketInFiltering(true);
- final Short version = connectionContext.getFeatures().getVersion();
- final OutboundQueueProvider outboundQueueProvider = new OutboundQueueProviderImpl(version);
+ final OutboundQueueProvider outboundQueueProvider = new OutboundQueueProviderImpl(deviceInfo.getVersion());
connectionContext.setOutboundQueueProvider(outboundQueueProvider);
final OutboundQueueHandlerRegistration<OutboundQueueProvider> outboundQueueHandlerRegistration =
connectionAdapter.registerOutboundQueueHandler(outboundQueueProvider, barrierCountLimit, barrierIntervalNanos);
connectionContext.setOutboundQueueHandleRegistration(outboundQueueHandlerRegistration);
- final DeviceState deviceState = createDeviceState(connectionContext);
+ final DeviceState deviceState = new DeviceStateImpl(deviceInfo);
+ this.addDeviceSynchronizeListener(deviceState);
+ this.addDeviceValidListener(deviceState);
+
final DeviceContext deviceContext = new DeviceContextImpl(connectionContext,
deviceState,
dataBroker,
conductor,
outboundQueueProvider,
- translatorLibrary,
- switchFeaturesMandatory);
+ translatorLibrary);
- Verify.verify(deviceContexts.putIfAbsent(nodeId, deviceContext) == null, "DeviceCtx still not closed.");
+ Verify.verify(deviceContexts.putIfAbsent(deviceInfo, deviceContext) == null, "DeviceCtx still not closed.");
((ExtensionConverterProviderKeeper) deviceContext).setExtensionConverterProvider(extensionConverterProvider);
- deviceContext.setStatisticsRpcEnabled(isStatisticsRpcEnabled);
- deviceContext.setNotificationPublishService(notificationPublishService);
+ deviceContext.setNotificationPublishService(conductor.getNotificationPublishService());
updatePacketInRateLimiters();
final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
connectionAdapter, deviceContext);
connectionAdapter.setMessageListener(messageListener);
- deviceState.setValid(true);
+ notifyDeviceValidListeners(deviceInfo, true);
- deviceInitPhaseHandler.onDeviceContextLevelUp(nodeId);
+ deviceInitPhaseHandler.onDeviceContextLevelUp(connectionContext.getDeviceInfo());
- return true;
- }
+ notifyDeviceSynchronizeListeners(deviceInfo, true);
- private static DeviceStateImpl createDeviceState(final @Nonnull ConnectionContext connectionContext) {
- return new DeviceStateImpl(connectionContext.getFeatures(), connectionContext.getNodeId());
+ return true;
}
private void updatePacketInRateLimiters() {
this.translatorLibrary = translatorLibrary;
}
- @Override
- public void setNotificationPublishService(final NotificationPublishService notificationService) {
- notificationPublishService = notificationService;
- }
-
@Override
public void close() {
for (final Iterator<DeviceContext> iterator = Iterators.consumingIterator(deviceContexts.values().iterator());
iterator.hasNext();) {
final DeviceContext deviceCtx = iterator.next();
+ notifyDeviceValidListeners(deviceCtx.getDeviceInfo(), false);
deviceCtx.shutdownConnection();
deviceCtx.shuttingDownDataStoreTransactions();
}
}
@Override
- public void onDeviceContextLevelDown(final DeviceContext deviceContext) {
- LOG.debug("onDeviceContextClosed for Node {}", deviceContext.getDeviceState().getNodeId());
- deviceContexts.remove(deviceContext.getPrimaryConnectionContext().getNodeId(), deviceContext);
+ public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
+ LOG.debug("onDeviceContextClosed for Node {}", deviceInfo.getNodeId());
+ deviceContexts.remove(deviceInfo);
updatePacketInRateLimiters();
}
spyPool.scheduleAtFixedRate(conductor.getMessageIntelligenceAgency(), spyRate, spyRate, TimeUnit.SECONDS);
}
- @Override
- public DeviceContext getDeviceContextFromNodeId(final NodeId nodeId) {
- return deviceContexts.get(nodeId);
- }
-
- @Override
- public void setStatisticsRpcEnabled(boolean isStatisticsRpcEnabled) {
- this.isStatisticsRpcEnabled = isStatisticsRpcEnabled;
- }
-
@Override
public void setExtensionConverterProvider(final ExtensionConverterProvider extensionConverterProvider) {
this.extensionConverterProvider = extensionConverterProvider;
@Override
public void onDeviceDisconnected(final ConnectionContext connectionContext) {
LOG.trace("onDeviceDisconnected method call for Node: {}", connectionContext.getNodeId());
- final NodeId nodeId = connectionContext.getNodeId();
- final DeviceContext deviceCtx = this.deviceContexts.get(nodeId);
+ final DeviceInfo deviceInfo = connectionContext.getDeviceInfo();
+ final DeviceContext deviceCtx = this.deviceContexts.get(deviceInfo);
if (null == deviceCtx) {
- LOG.info("DeviceContext for Node {} was not found. Connection is terminated without OFP context suite.", nodeId);
+ LOG.info("DeviceContext for Node {} was not found. Connection is terminated without OFP context suite.", deviceInfo.getNodeId());
return;
}
/* Connection is not PrimaryConnection so try to remove from Auxiliary Connections */
deviceCtx.removeAuxiliaryConnectionContext(connectionContext);
} else {
+ notifyDeviceValidListeners(deviceInfo, false);
/* Device is disconnected and so we need to close TxManager */
final ListenableFuture<Void> future = deviceCtx.shuttingDownDataStoreTransactions();
Futures.addCallback(future, new FutureCallback<Void>() {
@Override
public void onSuccess(final Void result) {
- LOG.debug("TxChainManager for device {} is closed successful.", nodeId);
- deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceCtx);
+ LOG.debug("TxChainManager for device {} is closed successful.", deviceInfo.getNodeId());
+ deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
}
@Override
public void onFailure(final Throwable t) {
- LOG.warn("TxChainManager for device {} failed by closing.", nodeId, t);
- deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceCtx);
+ LOG.warn("TxChainManager for device {} failed by closing.", deviceInfo.getNodeId(), t);
+ deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
}
});
/* Add timer for Close TxManager because it could fain ind cluster without notification */
- final TimerTask timerTask = new TimerTask() {
-
- @Override
- public void run(final Timeout timeout) throws Exception {
- if (!future.isDone()) {
- LOG.info("Shutting down TxChain for node {} not completed during 10 sec. Continue anyway.", nodeId);
- future.cancel(false);
- }
+ final TimerTask timerTask = timeout -> {
+ if (!future.isDone()) {
+ LOG.info("Shutting down TxChain for node {} not completed during 10 sec. Continue anyway.", deviceInfo.getNodeId());
+ future.cancel(false);
}
};
conductor.newTimeout(timerTask, 10, TimeUnit.SECONDS);
}
@VisibleForTesting
- void addDeviceContextToMap(final NodeId nodeId, final DeviceContext deviceContext){
- deviceContexts.put(nodeId, deviceContext);
+ void addDeviceContextToMap(final DeviceInfo deviceInfo, final DeviceContext deviceContext){
+ deviceContexts.put(deviceInfo, deviceContext);
+ }
+
+ @Override
+ public <T extends OFPContext> T gainContext(final DeviceInfo deviceInfo) {
+ return (T) deviceContexts.get(deviceInfo);
+ }
+
+ @Override
+ public ListenableFuture<Void> onClusterRoleChange(final DeviceInfo deviceInfo, final OfpRole role) {
+ DeviceContext deviceContext = conductor.getDeviceContext(deviceInfo);
+ LOG.trace("onClusterRoleChange {} for node:", role, deviceInfo.getNodeId());
+ if (OfpRole.BECOMEMASTER.equals(role)) {
+ return onDeviceTakeClusterLeadership(deviceInfo);
+ }
+ return ((DeviceContextImpl)deviceContext).getTransactionChainManager().deactivateTransactionManager();
}
+
+ @Override
+ public void addDeviceSynchronizeListener(final DeviceSynchronizeListener deviceSynchronizeListener) {
+ this.deviceSynchronizedListeners.add(deviceSynchronizeListener);
+ }
+
+ @Override
+ public void notifyDeviceSynchronizeListeners(final DeviceInfo deviceInfo, final boolean deviceSynchronized) {
+ for (DeviceSynchronizeListener listener : deviceSynchronizedListeners) {
+ listener.deviceIsSynchronized(deviceInfo, deviceSynchronized);
+ }
+ }
+
+ @Override
+ public void addDeviceValidListener(final DeviceValidListener deviceValidListener) {
+ this.deviceValidListeners.add(deviceValidListener);
+ }
+
+ @Override
+ public void notifyDeviceValidListeners(final DeviceInfo deviceInfo, final boolean deviceValid) {
+ for (DeviceValidListener listener : deviceValidListeners) {
+ listener.deviceIsValid(deviceInfo, deviceValid);
+ }
+ }
+
+ private ListenableFuture<Void> onDeviceTakeClusterLeadership(final DeviceInfo deviceInfo) {
+ LOG.trace("onDeviceTakeClusterLeadership for node: {}", deviceInfo.getNodeId());
+ /* validation */
+ StatisticsContext statisticsContext = conductor.getStatisticsContext(deviceInfo);
+ if (statisticsContext == null) {
+ final String errMsg = String.format("DeviceCtx %s is up but we are missing StatisticsContext", deviceInfo.getDatapathId());
+ LOG.warn(errMsg);
+ return Futures.immediateFailedFuture(new IllegalStateException(errMsg));
+ }
+ DeviceContext deviceContext = conductor.getDeviceContext(deviceInfo);
+ /* Prepare init info collecting */
+ notifyDeviceSynchronizeListeners(deviceInfo, false);
+ ((DeviceContextImpl)deviceContext).getTransactionChainManager().activateTransactionManager();
+ /* Init Collecting NodeInfo */
+ final ListenableFuture<Void> initCollectingDeviceInfo = DeviceInitializationUtils.initializeNodeInformation(
+ deviceContext, switchFeaturesMandatory);
+ /* Init Collecting StatInfo */
+ final ListenableFuture<Boolean> statPollFuture = Futures.transform(initCollectingDeviceInfo,
+ new AsyncFunction<Void, Boolean>() {
+
+ @Override
+ public ListenableFuture<Boolean> apply(@Nonnull final Void input) throws Exception {
+ statisticsContext.statListForCollectingInitialization();
+ return statisticsContext.initialGatherDynamicData();
+ }
+ });
+
+ return Futures.transform(statPollFuture, new Function<Boolean, Void>() {
+
+ @Override
+ public Void apply(final Boolean input) {
+ if (ConnectionContext.CONNECTION_STATE.RIP.equals(conductor.gainConnectionStateSafely(deviceInfo))) {
+ final String errMsg = String.format("We lost connection for Device %s, context has to be closed.",
+ deviceInfo.getNodeId());
+ LOG.warn(errMsg);
+ throw new IllegalStateException(errMsg);
+ }
+ if (!input) {
+ final String errMsg = String.format("Get Initial Device %s information fails",
+ deviceInfo.getNodeId());
+ LOG.warn(errMsg);
+ throw new IllegalStateException(errMsg);
+ }
+ LOG.debug("Get Initial Device {} information is successful", deviceInfo.getNodeId());
+ notifyDeviceSynchronizeListeners(deviceInfo, true);
+ ((DeviceContextImpl)deviceContext).getTransactionChainManager().initialSubmitWriteTransaction();
+ deviceContext.getDeviceState().setStatisticsPollingEnabledProp(true);
+ return null;
+ }
+ });
+ }
+
}
package org.opendaylight.openflowplugin.impl.device;
-import com.google.common.base.Preconditions;
-import javax.annotation.CheckForNull;
-import javax.annotation.Nonnull;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
-import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
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.NodeKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder;
-import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
/**
* openflowplugin-impl
* DeviceState is builded from {@link FeaturesReply} and {@link NodeId}. Both values are inside
* {@link org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext}
*
- * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
- * <p/>
- * Created: Mar 29, 2015
*/
class DeviceStateImpl implements DeviceState {
- private final GetFeaturesOutput featuresOutput;
- private final NodeId nodeId;
- private final KeyedInstanceIdentifier<Node, NodeKey> nodeII;
- private final short version;
+ private final DeviceInfo deviceInfo;
private boolean valid;
private boolean meterIsAvailable;
private boolean groupIsAvailable;
private boolean statPollEnabled;
private boolean queueStatisticsAvailable;
- public DeviceStateImpl(@CheckForNull final FeaturesReply featuresReply, @Nonnull final NodeId nodeId) {
- Preconditions.checkArgument(featuresReply != null);
- featuresOutput = new GetFeaturesOutputBuilder(featuresReply).build();
- this.nodeId = Preconditions.checkNotNull(nodeId);
- nodeII = DeviceStateUtil.createNodeInstanceIdentifier(nodeId);
- version = featuresReply.getVersion();
+ public DeviceStateImpl(final DeviceInfo deviceInfo) {
+ this.deviceInfo = deviceInfo;
statPollEnabled = false;
deviceSynchronized = false;
}
- @Override
- public NodeId getNodeId() {
- return nodeId;
- }
-
- @Override
- public KeyedInstanceIdentifier<Node, NodeKey> getNodeInstanceIdentifier() {
- return nodeII;
- }
-
- @Override
- public GetFeaturesOutput getFeatures() {
- return featuresOutput;
- }
-
@Override
public boolean isValid() {
return valid;
}
- @Override
- public void setValid(final boolean valid) {
- this.valid = valid;
- }
-
- @Override
- public short getVersion() {
- return version;
- }
-
@Override
public boolean isMetersAvailable() {
return meterIsAvailable;
}
- @Override
- public void setDeviceSynchronized(final boolean _deviceSynchronized) {
- deviceSynchronized = _deviceSynchronized;
- }
-
@Override
public boolean isStatisticsPollingEnabled() {
return statPollEnabled;
public void setStatisticsPollingEnabledProp(final boolean statPollEnabled) {
this.statPollEnabled = statPollEnabled;
}
+
+ @Override
+ public void deviceIsSynchronized(final DeviceInfo deviceInfo, final boolean isSynchronized) {
+ if (this.deviceInfo.equals(deviceInfo)) {
+ this.deviceSynchronized = isSynchronized;
+ }
+ }
+
+ @Override
+ public void deviceIsValid(final DeviceInfo deviceInfo, final boolean isValid) {
+ if (this.deviceInfo.equals(deviceInfo)) {
+ this.valid = isValid;
+ }
+ }
}
import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
private final Object txLock = new Object();
private final KeyedInstanceIdentifier<Node, NodeKey> nodeII;
+ private final DeviceInfo deviceInfo;
private final DataBroker dataBroker;
private final LifecycleConductor conductor;
private TransactionChainManagerStatus transactionChainManagerStatus = TransactionChainManagerStatus.SLEEPING;
TransactionChainManager(@Nonnull final DataBroker dataBroker,
- @Nonnull final DeviceState deviceState,
+ @Nonnull final DeviceInfo deviceInfo,
@Nonnull final LifecycleConductor conductor) {
this.dataBroker = Preconditions.checkNotNull(dataBroker);
this.conductor = Preconditions.checkNotNull(conductor);
- this.nodeII = Preconditions.checkNotNull(deviceState.getNodeInstanceIdentifier());
+ this.deviceInfo = deviceInfo;
+ this.nodeII = deviceInfo.getNodeInstanceIdentifier();
this.transactionChainManagerStatus = TransactionChainManagerStatus.SLEEPING;
lastSubmittedFuture = Futures.immediateFuture(null);
- LOG.debug("created txChainManager for {}", nodeII);
+ LOG.debug("created txChainManager for {}", this.nodeII);
}
private NodeId nodeId() {
* registration for this class instance as {@link TransactionChainListener} to provide possibility a make DS
* transactions. Call this method for MASTER role only.
*/
- public void activateTransactionManager() {
+ void activateTransactionManager() {
LOG.trace("activateTransactionManager for node {} transaction submit is set to {}", nodeId(), submitIsEnabled);
synchronized (txLock) {
if (TransactionChainManagerStatus.SLEEPING.equals(transactionChainManagerStatus)) {
* Call this method for SLAVE only.
* @return Future
*/
- public ListenableFuture<Void> deactivateTransactionManager() {
+ ListenableFuture<Void> deactivateTransactionManager() {
final ListenableFuture<Void> future;
synchronized (txLock) {
if (TransactionChainManagerStatus.WORKING.equals(transactionChainManagerStatus)) {
}
if (initCommit) {
LOG.error("Initial commit failed. {}", t);
- conductor.closeConnection(nodeId());
+ conductor.closeConnection(deviceInfo);
}
}
});
import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
+import org.opendaylight.openflowplugin.api.openflow.OFPContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
import org.opendaylight.openflowplugin.api.openflow.role.RoleContext;
import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.SalRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger LOG = LoggerFactory.getLogger(RoleContextImpl.class);
private static final int TIMEOUT = 12;
- private final NodeId nodeId;
+ private final DeviceInfo deviceInfo;
private final EntityOwnershipService entityOwnershipService;
private volatile EntityOwnershipCandidateRegistration entityOwnershipCandidateRegistration = null;
private volatile EntityOwnershipCandidateRegistration txEntityOwnershipCandidateRegistration = null;
private final Semaphore roleChangeGuard = new Semaphore(1, true);
private final LifecycleConductor conductor;
+ private volatile CONTEXT_STATE contextState;
- public RoleContextImpl(final NodeId nodeId, final EntityOwnershipService entityOwnershipService, final Entity entity, final Entity txEntity, final LifecycleConductor lifecycleConductor) {
+ RoleContextImpl(final DeviceInfo deviceInfo, final EntityOwnershipService entityOwnershipService, final Entity entity, final Entity txEntity, final LifecycleConductor lifecycleConductor) {
this.entityOwnershipService = entityOwnershipService;
this.entity = entity;
this.txEntity = txEntity;
- this.nodeId = nodeId;
+ this.deviceInfo = deviceInfo;
this.conductor = lifecycleConductor;
+ contextState = CONTEXT_STATE.INITIALIZATION;
}
@Override
public boolean initialization() {
- LOG.info("Initialization main candidate for node {}", nodeId);
+ LOG.info("Initialization main candidate for node {}", deviceInfo.getNodeId());
+ contextState = CONTEXT_STATE.WORKING;
return registerCandidate(this.entity);
}
@Override
public void unregisterAllCandidates() {
- LOG.info("Role context closed, unregistering all candidates for ownership for node {}", nodeId);
+ LOG.info("Role context closed, unregistering all candidates for ownership for node {}", deviceInfo.getNodeId());
if (isMainCandidateRegistered()) {
unregisterCandidate(this.entity);
}
@Nullable
@Override
public <T> RequestContext<T> createRequestContext() {
- return new AbstractRequestContext<T>(conductor.reserveXidForDeviceMessage(nodeId)) {
+ return new AbstractRequestContext<T>(conductor.reserveXidForDeviceMessage(deviceInfo)) {
@Override
public void close() {
}
}
@Override
- public NodeId getNodeId() {
- return nodeId;
+ public DeviceInfo getDeviceInfo() {
+ return deviceInfo;
}
@Override
@Override
public void close() {
+ contextState = CONTEXT_STATE.TERMINATION;
unregisterAllCandidates();
}
public boolean isMaster(){
return (txEntityOwnershipCandidateRegistration != null && entityOwnershipCandidateRegistration != null);
}
+
+ @Override
+ public CONTEXT_STATE getState() {
+ return contextState;
+ }
}
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.JdkFutureAdapters;
import com.google.common.util.concurrent.ListenableFuture;
-import io.netty.util.Timeout;
import io.netty.util.TimerTask;
-
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
-
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.openflowplugin.api.OFConstants;
+import org.opendaylight.openflowplugin.api.openflow.OFPContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
private DeviceTerminationPhaseHandler deviceTerminationPhaseHandler;
private final DataBroker dataBroker;
private final EntityOwnershipService entityOwnershipService;
- private final ConcurrentMap<NodeId, RoleContext> contexts = new ConcurrentHashMap<>();
+ private final ConcurrentMap<DeviceInfo, RoleContext> contexts = new ConcurrentHashMap<>();
private final ConcurrentMap<Entity, RoleContext> watchingEntities = new ConcurrentHashMap<>();
private final EntityOwnershipListenerRegistration entityOwnershipListenerRegistration;
private final EntityOwnershipListenerRegistration txEntityOwnershipListenerRegistration;
}
@Override
- public void onDeviceContextLevelUp(@CheckForNull final NodeId nodeId) throws Exception {
- final DeviceContext deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(nodeId));
- final RoleContext roleContext = new RoleContextImpl(nodeId, entityOwnershipService, makeEntity(nodeId), makeTxEntity(nodeId), conductor);
+ public void onDeviceContextLevelUp(@CheckForNull final DeviceInfo deviceInfo) throws Exception {
+ final DeviceContext deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(deviceInfo));
+ final RoleContext roleContext = new RoleContextImpl(deviceInfo, entityOwnershipService, makeEntity(deviceInfo.getNodeId()), makeTxEntity(deviceInfo.getNodeId()), conductor);
roleContext.setSalRoleService(new SalRoleServiceImpl(roleContext, deviceContext));
- Verify.verify(contexts.putIfAbsent(nodeId, roleContext) == null, "Role context for master Node %s is still not closed.", nodeId);
+ Verify.verify(contexts.putIfAbsent(deviceInfo, roleContext) == null, "Role context for master Node %s is still not closed.", deviceInfo.getNodeId());
makeDeviceRoleChange(OfpRole.BECOMESLAVE, roleContext, true);
/* First start to watch entity so we don't miss any notification, and then try to register in EOS */
watchingEntities.put(roleContext.getEntity(), roleContext);
- notifyListenersRoleInitializationDone(roleContext.getNodeId(), roleContext.initialization());
- deviceInitializationPhaseHandler.onDeviceContextLevelUp(nodeId);
+ notifyListenersRoleInitializationDone(roleContext.getDeviceInfo(), roleContext.initialization());
+ deviceInitializationPhaseHandler.onDeviceContextLevelUp(deviceInfo);
}
@Override
final RoleContext roleContext = iterator.next();
watchingEntities.remove(roleContext.getEntity());
watchingEntities.remove(roleContext.getTxEntity());
- contexts.remove(roleContext.getNodeId());
+ contexts.remove(roleContext.getDeviceInfo());
if (roleContext.isTxCandidateRegistered()) {
LOG.info("Node {} was holder txEntity, so trying to remove device from operational DS.");
- removeDeviceFromOperationalDS(roleContext.getNodeId());
+ removeDeviceFromOperationalDS(roleContext.getDeviceInfo());
} else {
roleContext.close();
}
}
@Override
- public void onDeviceContextLevelDown(final DeviceContext deviceContext) {
- final NodeId nodeId = deviceContext.getPrimaryConnectionContext().getNodeId();
- LOG.trace("onDeviceContextLevelDown for node {}", nodeId);
- final RoleContext roleContext = contexts.get(nodeId);
+ public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
+ LOG.trace("onDeviceContextLevelDown for node {}", deviceInfo.getNodeId());
+ final RoleContext roleContext = contexts.get(deviceInfo);
if (roleContext != null) {
- LOG.debug("Found roleContext associated to deviceContext: {}, now trying close the roleContext", nodeId);
+ LOG.debug("Found roleContext associated to deviceContext: {}, now trying close the roleContext", deviceInfo.getNodeId());
if (roleContext.isMainCandidateRegistered()) {
roleContext.unregisterCandidate(roleContext.getEntity());
} else {
- contexts.remove(nodeId, roleContext);
+ contexts.remove(deviceInfo.getNodeId(), roleContext);
roleContext.close();
}
}
- deviceTerminationPhaseHandler.onDeviceContextLevelDown(deviceContext);
+ deviceTerminationPhaseHandler.onDeviceContextLevelDown(deviceInfo);
}
@VisibleForTesting
LOG.debug("Received EOS message: wasOwner:{} isOwner:{} hasOwner:{} inJeopardy:{} for entity type {} and node {}",
ownershipChange.wasOwner(), ownershipChange.isOwner(), ownershipChange.hasOwner(), ownershipChange.inJeopardy(),
ownershipChange.getEntity().getType(),
- roleContext != null ? roleContext.getNodeId() : "-> no watching entity, disregarding notification <-");
+ roleContext != null ? roleContext.getDeviceInfo().getNodeId() : "-> no watching entity, disregarding notification <-");
if (roleContext != null) {
if (ownershipChange.getEntity().equals(roleContext.getEntity())) {
if (roleContext.isMainCandidateRegistered()) {
LOG.debug("Main-EntityOwnershipRegistration is active for entity type {} and node {}",
- ownershipChange.getEntity().getType(), roleContext.getNodeId());
+ ownershipChange.getEntity().getType(), roleContext.getDeviceInfo().getNodeId());
if (!ownershipChange.wasOwner() && ownershipChange.isOwner() && !ownershipChange.inJeopardy()) {
// SLAVE -> MASTER
- LOG.debug("SLAVE to MASTER for node {}", roleContext.getNodeId());
+ LOG.debug("SLAVE to MASTER for node {}", roleContext.getDeviceInfo().getNodeId());
if (roleContext.registerCandidate(roleContext.getTxEntity())) {
- LOG.debug("Starting watching tx entity for node {}", roleContext.getNodeId());
+ LOG.debug("Starting watching tx entity for node {}", roleContext.getDeviceInfo().getNodeId());
watchingEntities.putIfAbsent(roleContext.getTxEntity(), roleContext);
}
} else if ((ownershipChange.wasOwner() && !ownershipChange.isOwner()) || (ownershipChange.inJeopardy())) {
// MASTER -> SLAVE
- LOG.debug("MASTER to SLAVE for node {}", roleContext.getNodeId());
- conductor.addOneTimeListenerWhenServicesChangesDone(this, roleContext.getNodeId());
+ LOG.debug("MASTER to SLAVE for node {}", roleContext.getDeviceInfo().getNodeId());
+ conductor.addOneTimeListenerWhenServicesChangesDone(this, roleContext.getDeviceInfo());
makeDeviceRoleChange(OfpRole.BECOMESLAVE, roleContext, false);
}
} else {
LOG.debug("Main-EntityOwnershipRegistration is not active for entity type {} and node {}",
- ownershipChange.getEntity(), roleContext.getNodeId());
+ ownershipChange.getEntity(), roleContext.getDeviceInfo().getNodeId());
watchingEntities.remove(ownershipChange.getEntity(), roleContext);
if (roleContext.isTxCandidateRegistered()) {
- LOG.debug("tx candidate still registered for node {}, probably connection lost, trying to unregister tx candidate", roleContext.getNodeId());
+ LOG.debug("tx candidate still registered for node {}, probably connection lost, trying to unregister tx candidate", roleContext.getDeviceInfo().getNodeId());
roleContext.unregisterCandidate(roleContext.getTxEntity());
if (ownershipChange.wasOwner() && !ownershipChange.isOwner() && !ownershipChange.hasOwner()) {
- LOG.debug("Trying to remove from operational node: {}", roleContext.getNodeId());
- removeDeviceFromOperationalDS(roleContext.getNodeId());
+ LOG.debug("Trying to remove from operational node: {}", roleContext.getDeviceInfo().getNodeId());
+ removeDeviceFromOperationalDS(roleContext.getDeviceInfo());
}
} else {
- final NodeId nodeId = roleContext.getNodeId();
- contexts.remove(nodeId, roleContext);
+ contexts.remove(roleContext.getDeviceInfo(), roleContext);
roleContext.close();
- conductor.closeConnection(nodeId);
+ conductor.closeConnection(roleContext.getDeviceInfo());
}
}
}
if (roleContext.isTxCandidateRegistered()) {
LOG.debug("Tx-EntityOwnershipRegistration is active for entity type {} and node {}",
ownershipChange.getEntity().getType(),
- roleContext.getNodeId());
+ roleContext.getDeviceInfo().getNodeId());
if (ownershipChange.inJeopardy()) {
LOG.warn("Getting 'inJeopardy' flag from EOS. Removing txCandidate and stopping watching txCandidate.");
watchingEntities.remove(roleContext.getTxEntity());
} else {
if (!ownershipChange.wasOwner() && ownershipChange.isOwner()) {
// SLAVE -> MASTER
- LOG.debug("SLAVE to MASTER for node {}", roleContext.getNodeId());
+ LOG.debug("SLAVE to MASTER for node {}", roleContext.getDeviceInfo().getNodeId());
makeDeviceRoleChange(OfpRole.BECOMEMASTER, roleContext, false);
} else if (ownershipChange.wasOwner() && !ownershipChange.isOwner()) {
// MASTER -> SLAVE
- LOG.debug("MASTER to SLAVE for node {}", roleContext.getNodeId());
+ LOG.debug("MASTER to SLAVE for node {}", roleContext.getDeviceInfo().getNodeId());
LOG.warn("Tx-EntityOwnershipRegistration lost leadership entity type {} and node {}",
- ownershipChange.getEntity().getType(), roleContext.getNodeId());
+ ownershipChange.getEntity().getType(), roleContext.getDeviceInfo().getNodeId());
watchingEntities.remove(roleContext.getTxEntity(), roleContext);
watchingEntities.remove(roleContext.getEntity(), roleContext);
roleContext.unregisterCandidate(roleContext.getEntity());
roleContext.unregisterCandidate(roleContext.getTxEntity());
if (!ownershipChange.hasOwner()) {
- LOG.debug("Trying to remove from operational node: {}", roleContext.getNodeId());
- removeDeviceFromOperationalDS(roleContext.getNodeId());
+ LOG.debug("Trying to remove from operational node: {}", roleContext.getDeviceInfo().getNodeId());
+ removeDeviceFromOperationalDS(roleContext.getDeviceInfo());
} else {
- final NodeId nodeId = roleContext.getNodeId();
- contexts.remove(nodeId, roleContext);
+ final NodeId nodeId = roleContext.getDeviceInfo().getNodeId();
+ contexts.remove(roleContext.getDeviceInfo(), roleContext);
roleContext.close();
- conductor.closeConnection(nodeId);
+ conductor.closeConnection(roleContext.getDeviceInfo());
}
}
}
} else {
LOG.debug("Tx-EntityOwnershipRegistration is not active for entity {}", ownershipChange.getEntity().getType());
watchingEntities.remove(roleContext.getTxEntity(), roleContext);
- final NodeId nodeId = roleContext.getNodeId();
- contexts.remove(nodeId, roleContext);
+ contexts.remove(roleContext.getDeviceInfo(), roleContext);
roleContext.close();
- conductor.closeConnection(nodeId);
+ conductor.closeConnection(roleContext.getDeviceInfo());
}
}
Futures.addCallback(roleChangeFuture, new FutureCallback<RpcResult<SetRoleOutput>>() {
@Override
public void onSuccess(@Nullable final RpcResult<SetRoleOutput> setRoleOutputRpcResult) {
- LOG.info("Role {} successfully set on device {}", role, roleContext.getNodeId());
- notifyListenersRoleChangeOnDevice(roleContext.getNodeId(), true, role, init);
+ LOG.info("Role {} successfully set on device {}", role, roleContext.getDeviceInfo().getNodeId());
+ notifyListenersRoleChangeOnDevice(roleContext.getDeviceInfo(), true, role, init);
}
@Override
public void onFailure(@Nonnull final Throwable throwable) {
- LOG.warn("Unable to set role {} on device {}", role, roleContext.getNodeId());
- notifyListenersRoleChangeOnDevice(roleContext.getNodeId(), false, role, init);
+ LOG.warn("Unable to set role {} on device {}", role, roleContext.getDeviceInfo().getNodeId());
+ notifyListenersRoleChangeOnDevice(roleContext.getDeviceInfo(), false, role, init);
}
});
}
@VisibleForTesting
ListenableFuture<RpcResult<SetRoleOutput>> sendRoleChangeToDevice(final OfpRole newRole, final RoleContext roleContext) {
- LOG.debug("Sending new role {} to device {}", newRole, roleContext.getNodeId());
+ LOG.debug("Sending new role {} to device {}", newRole, roleContext.getDeviceInfo().getNodeId());
final Future<RpcResult<SetRoleOutput>> setRoleOutputFuture;
- final Short version = conductor.gainVersionSafely(roleContext.getNodeId());
+ final Short version = roleContext.getDeviceInfo().getVersion();
if (null == version) {
LOG.debug("Device version is null");
return Futures.immediateFuture(null);
return Futures.immediateFuture(null);
} else {
final SetRoleInput setRoleInput = (new SetRoleInputBuilder()).setControllerRole(newRole)
- .setNode(new NodeRef(DeviceStateUtil.createNodeInstanceIdentifier(roleContext.getNodeId()))).build();
+ .setNode(new NodeRef(DeviceStateUtil.createNodeInstanceIdentifier(roleContext.getDeviceInfo().getNodeId()))).build();
setRoleOutputFuture = roleContext.getSalRoleService().setRole(setRoleInput);
- final TimerTask timerTask = new TimerTask() {
-
- @Override
- public void run(final Timeout timeout) throws Exception {
- if (!setRoleOutputFuture.isDone()) {
- LOG.warn("New role {} was not propagated to device {} during 10 sec", newRole, roleContext.getNodeId());
- setRoleOutputFuture.cancel(true);
- }
+ final TimerTask timerTask = timeout -> {
+ if (!setRoleOutputFuture.isDone()) {
+ LOG.warn("New role {} was not propagated to device {} during 10 sec", newRole, roleContext.getDeviceInfo().getNodeId());
+ setRoleOutputFuture.cancel(true);
}
};
conductor.newTimeout(timerTask, 10, TimeUnit.SECONDS);
}
@VisibleForTesting
- CheckedFuture<Void, TransactionCommitFailedException> removeDeviceFromOperationalDS(final NodeId nodeId) {
+ CheckedFuture<Void, TransactionCommitFailedException> removeDeviceFromOperationalDS(final DeviceInfo deviceInfo) {
final WriteTransaction delWtx = dataBroker.newWriteOnlyTransaction();
- delWtx.delete(LogicalDatastoreType.OPERATIONAL, DeviceStateUtil.createNodeInstanceIdentifier(nodeId));
+ delWtx.delete(LogicalDatastoreType.OPERATIONAL, DeviceStateUtil.createNodeInstanceIdentifier(deviceInfo.getNodeId()));
final CheckedFuture<Void, TransactionCommitFailedException> delFuture = delWtx.submit();
Futures.addCallback(delFuture, new FutureCallback<Void>() {
@Override
public void onSuccess(final Void result) {
- LOG.debug("Delete Node {} was successful", nodeId);
- final RoleContext roleContext = contexts.remove(nodeId);
+ LOG.debug("Delete Node {} was successful", deviceInfo);
+ final RoleContext roleContext = contexts.remove(deviceInfo);
if (roleContext != null) {
roleContext.close();
}
@Override
public void onFailure(@Nonnull final Throwable t) {
- LOG.warn("Delete Node {} failed. {}", nodeId, t);
- contexts.remove(nodeId);
- final RoleContext roleContext = contexts.remove(nodeId);
+ LOG.warn("Delete Node {} failed. {}", deviceInfo, t);
+ final RoleContext roleContext = contexts.remove(deviceInfo);
if (roleContext != null) {
roleContext.close();
}
}
@Override
- public void servicesChangeDone(final NodeId nodeId, final boolean success) {
- LOG.debug("Services stopping done for node {} as " + (success ? "successful" : "unsuccessful"), nodeId);
- final RoleContext roleContext = contexts.get(nodeId);
+ public void servicesChangeDone(final DeviceInfo deviceInfo, final boolean success) {
+ LOG.debug("Services stopping done for node {} as " + (success ? "successful" : "unsuccessful"), deviceInfo);
+ final RoleContext roleContext = contexts.get(deviceInfo);
if (null != roleContext) {
/* Services stopped or failure */
roleContext.unregisterCandidate(roleContext.getTxEntity());
}
@VisibleForTesting
- RoleContext getRoleContext(final NodeId nodeId){
- return contexts.get(nodeId);
+ RoleContext getRoleContext(final DeviceInfo deviceInfo){
+ return contexts.get(deviceInfo);
}
/**
* This method is only for testing
*/
@VisibleForTesting
- void setRoleContext(NodeId nodeId, RoleContext roleContext){
- if(!contexts.containsKey(nodeId)) {
- contexts.put(nodeId, roleContext);
+ void setRoleContext(DeviceInfo deviceInfo, RoleContext roleContext){
+ if(!contexts.containsKey(deviceInfo)) {
+ contexts.put(deviceInfo, roleContext);
}
}
/**
* Invoked when initialization phase is done
- * @param nodeId node identification
+ * @param deviceInfo node identification
* @param success true if initialization done ok, false otherwise
*/
@VisibleForTesting
- void notifyListenersRoleInitializationDone(final NodeId nodeId, final boolean success){
+ void notifyListenersRoleInitializationDone(final DeviceInfo deviceInfo, final boolean success){
LOG.debug("Notifying registered listeners for role initialization done, no. of listeners {}", listeners.size());
for (final RoleChangeListener listener : listeners) {
- listener.roleInitializationDone(nodeId, success);
+ listener.roleInitializationDone(deviceInfo, success);
}
}
/**
* Notifies registered listener on role change. Role is the new role on device
* If initialization phase is true, we may skip service starting
+ * @param deviceInfo
* @param success true if role change on device done ok, false otherwise
* @param role new role meant to be set on device
* @param initializationPhase if true, then skipp services start
*/
@VisibleForTesting
- void notifyListenersRoleChangeOnDevice(final NodeId nodeId, final boolean success, final OfpRole role, final boolean initializationPhase){
+ void notifyListenersRoleChangeOnDevice(final DeviceInfo deviceInfo, final boolean success, final OfpRole role, final boolean initializationPhase){
LOG.debug("Notifying registered listeners for role change, no. of listeners {}", listeners.size());
for (final RoleChangeListener listener : listeners) {
- listener.roleChangeOnDevice(nodeId, success, role, initializationPhase);
+ listener.roleChangeOnDevice(deviceInfo, success, role, initializationPhase);
}
}
+ @Override
+ public <T extends OFPContext> T gainContext(DeviceInfo deviceInfo) {
+ return (T) contexts.get(deviceInfo);
+ }
}
import java.util.concurrent.Semaphore;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
+import org.opendaylight.openflowplugin.api.openflow.OFPContext;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.device.XidSequencer;
import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class RpcContextImpl implements RpcContext {
+class RpcContextImpl implements RpcContext {
private static final Logger LOG = LoggerFactory.getLogger(RpcContextImpl.class);
private final RpcProviderRegistry rpcProviderRegistry;
private final MessageSpy messageSpy;
private final Semaphore tracker;
private final XidSequencer xidSequencer;
+ private boolean isStatisticsRpcEnabled;
+
+ private volatile CONTEXT_STATE contextState;
// TODO: add private Sal salBroker
private final ConcurrentMap<Class<?>, RoutedRpcRegistration<?>> rpcRegistrations = new ConcurrentHashMap<>();
private final KeyedInstanceIdentifier<Node, NodeKey> nodeInstanceIdentifier;
- public RpcContextImpl(final RpcProviderRegistry rpcProviderRegistry,
+ RpcContextImpl(final RpcProviderRegistry rpcProviderRegistry,
final XidSequencer xidSequencer,
final MessageSpy messageSpy,
final int maxRequests,
this.nodeInstanceIdentifier = nodeInstanceIdentifier;
tracker = new Semaphore(maxRequests, true);
+ contextState = CONTEXT_STATE.WORKING;
}
/**
*/
@Override
public void close() {
- for (final Iterator<Entry<Class<?>, RoutedRpcRegistration<?>>> iterator = Iterators
- .consumingIterator(rpcRegistrations.entrySet().iterator()); iterator.hasNext();) {
- final RoutedRpcRegistration<?> rpcRegistration = iterator.next().getValue();
- rpcRegistration.unregisterPath(NodeContext.class, nodeInstanceIdentifier);
- rpcRegistration.close();
- LOG.debug("Closing RPC Registration of service {} for device {}.", rpcRegistration.getServiceType(),
- nodeInstanceIdentifier);
+ if (CONTEXT_STATE.TERMINATION.equals(contextState)){
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("RpcContext is already in TERMINATION state.");
+ }
+ } else {
+ contextState = CONTEXT_STATE.TERMINATION;
+ for (final Iterator<Entry<Class<?>, RoutedRpcRegistration<?>>> iterator = Iterators
+ .consumingIterator(rpcRegistrations.entrySet().iterator()); iterator.hasNext(); ) {
+ final RoutedRpcRegistration<?> rpcRegistration = iterator.next().getValue();
+ rpcRegistration.unregisterPath(NodeContext.class, nodeInstanceIdentifier);
+ rpcRegistration.close();
+ LOG.debug("Closing RPC Registration of service {} for device {}.", rpcRegistration.getServiceType(),
+ nodeInstanceIdentifier);
+ }
}
}
}
@VisibleForTesting
- public boolean isEmptyRpcRegistrations() {
+ boolean isEmptyRpcRegistrations() {
return this.rpcRegistrations.isEmpty();
}
+ @Override
+ public void setStatisticsRpcEnabled(boolean isStatisticsRpcEnabled) {
+ this.isStatisticsRpcEnabled = isStatisticsRpcEnabled;
+ }
+
+ @Override
+ public boolean isStatisticsRpcEnabled() {
+ return isStatisticsRpcEnabled;
+ }
+ @Override
+ public CONTEXT_STATE getState() {
+ return contextState;
+ }
}
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
+import org.opendaylight.openflowplugin.api.openflow.OFPContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
import org.opendaylight.openflowplugin.api.openflow.rpc.RpcManager;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
private final int maxRequestsQuota;
- private final ConcurrentMap<NodeId, RpcContext> contexts = new ConcurrentHashMap<>();
+ private final ConcurrentMap<DeviceInfo, RpcContext> contexts = new ConcurrentHashMap<>();
+ private boolean isStatisticsRpcEnabled;
private final LifecycleConductor conductor;
}
@Override
- public void onDeviceContextLevelUp(final NodeId nodeId) throws Exception {
+ public void onDeviceContextLevelUp(final DeviceInfo deviceInfo) throws Exception {
- final DeviceContext deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(nodeId));
+ final DeviceContext deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(deviceInfo));
final RpcContext rpcContext = new RpcContextImpl(
rpcProviderRegistry,
deviceContext,
deviceContext.getMessageSpy(),
maxRequestsQuota,
- deviceContext.getDeviceState().getNodeInstanceIdentifier());
+ deviceInfo.getNodeInstanceIdentifier());
- deviceContext.setRpcContext(rpcContext);
+ Verify.verify(contexts.putIfAbsent(deviceInfo, rpcContext) == null, "RpcCtx still not closed for node {}", deviceInfo.getNodeId());
- Verify.verify(contexts.putIfAbsent(nodeId, rpcContext) == null, "RpcCtx still not closed for node {}", nodeId);
+ rpcContext.setStatisticsRpcEnabled(isStatisticsRpcEnabled);
// finish device initialization cycle back to DeviceManager
- deviceInitPhaseHandler.onDeviceContextLevelUp(nodeId);
+ deviceInitPhaseHandler.onDeviceContextLevelUp(deviceInfo);
}
@Override
}
@Override
- public void onDeviceContextLevelDown(final DeviceContext deviceContext) {
- final RpcContext removedContext = contexts.remove(deviceContext.getDeviceState().getNodeId());
+ public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
+ final RpcContext removedContext = contexts.remove(deviceInfo);
if (removedContext != null) {
LOG.info("Unregister RPCs services for device context closure");
removedContext.close();
}
- deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceContext);
+ deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
}
@Override
* This method is only for testing
*/
@VisibleForTesting
- void addRecordToContexts(NodeId nodeId, RpcContext rpcContexts) {
- if(!contexts.containsKey(nodeId)) {
- this.contexts.put(nodeId,rpcContexts);
+ void addRecordToContexts(DeviceInfo deviceInfo, RpcContext rpcContexts) {
+ if(!contexts.containsKey(deviceInfo)) {
+ this.contexts.put(deviceInfo,rpcContexts);
}
}
+
+ @Override
+ public <T extends OFPContext> T gainContext(DeviceInfo deviceInfo) {
+ return (T) contexts.get(deviceInfo);
+ }
+
+
+ @Override
+ public void setStatisticsRpcEnabled(boolean statisticsRpcEnabled) {
+ isStatisticsRpcEnabled = statisticsRpcEnabled;
+ }
}
@Override
protected final FutureCallback<OfHeader> createCallback(final RequestContext<List<MultipartReply>> context, final Class<?> requestType) {
return new MultipartRequestOnTheFlyCallback(context, requestType,
- getDeviceContext().getMessageSpy(), getEventIdentifier(), getDeviceContext().getDeviceState(),
- getDeviceContext().getDeviceFlowRegistry(), getDeviceContext());
+ getMessageSpy(), getEventIdentifier(), getDeviceInfo(),
+ getDeviceContext().getDeviceFlowRegistry(), getTxFacade());
}
import javax.annotation.Nonnull;
import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceRegistry;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
+import org.opendaylight.openflowplugin.api.openflow.device.TxFacade;
import org.opendaylight.openflowplugin.api.openflow.device.Xid;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.EventIdentifier;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
import org.opendaylight.yangtools.yang.binding.DataContainer;
import org.opendaylight.yangtools.yang.common.RpcError;
private final RequestContextStack requestContextStack;
private final DeviceContext deviceContext;
private final MessageSpy messageSpy;
- private final NodeId nodeId;
private EventIdentifier eventIdentifier;
- public AbstractService(final RequestContextStack requestContextStack, final DeviceContext deviceContext) {
- final DeviceState deviceState = deviceContext.getDeviceState();
- final GetFeaturesOutput features = deviceState.getFeatures();
+ AbstractService(final RequestContextStack requestContextStack, final DeviceContext deviceContext) {
+ final DeviceInfo deviceInfo = deviceContext.getDeviceInfo();
this.requestContextStack = requestContextStack;
this.deviceContext = deviceContext;
- this.datapathId = features.getDatapathId();
- this.version = features.getVersion();
+ this.datapathId = deviceInfo.getDatapathId();
+ this.version = deviceInfo.getVersion();
this.messageSpy = deviceContext.getMessageSpy();
- this.nodeId = deviceState.getNodeId();
}
public EventIdentifier getEventIdentifier() {
return datapathId;
}
- public NodeId getNodeId() {
- return nodeId;
- }
-
public RequestContextStack getRequestContextStack() {
return requestContextStack;
}
+ @Deprecated
public DeviceContext getDeviceContext() {
return deviceContext;
}
+ protected DeviceRegistry getDeviceRegistry() {return deviceContext;}
+
+ public DeviceInfo getDeviceInfo() {return deviceContext.getDeviceInfo();}
+
+ public TxFacade getTxFacade() {return deviceContext;}
+
public MessageSpy getMessageSpy() {
return messageSpy;
}
import com.google.common.util.concurrent.ListenableFuture;
import java.util.Collections;
import java.util.List;
-
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.device.TxFacade;
import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
final class MultipartRequestOnTheFlyCallback extends AbstractRequestCallback<List<MultipartReply>> {
private static final Logger LOG = LoggerFactory.getLogger(MultipartRequestOnTheFlyCallback.class);
private static final SinglePurposeMultipartReplyTranslator MULTIPART_REPLY_TRANSLATOR = new SinglePurposeMultipartReplyTranslator();
- private final DeviceState deviceState;
+ private final DeviceInfo deviceInfo;
private final DeviceFlowRegistry registry;
private boolean virgin = true;
private boolean finished = false;
final Class<?> requestType,
final MessageSpy messageSpy,
final EventIdentifier eventIdentifier,
- final DeviceState deviceState,
+ final DeviceInfo deviceInfo,
final DeviceFlowRegistry registry,
final TxFacade txFacade) {
super(context, requestType, messageSpy, eventIdentifier);
- this.deviceState = deviceState;
+ this.deviceInfo = deviceInfo;
this.registry = registry;
this.txFacade = txFacade;
//TODO: this is focused on flow stats only - need more general approach if used for more than flow stats
- doneEventIdentifier = new EventIdentifier(MultipartType.OFPMPFLOW.name(), deviceState.getNodeId().toString());
+ doneEventIdentifier = new EventIdentifier(MultipartType.OFPMPFLOW.name(), deviceInfo.getNodeId().toString());
}
public EventIdentifier getDoneEventIdentifier() {
final MultipartReply singleReply = multipartReply;
final List<? extends DataObject> multipartDataList = MULTIPART_REPLY_TRANSLATOR.translate(
- deviceState.getFeatures().getDatapathId(), deviceState.getFeatures().getVersion(), singleReply);
+ deviceInfo.getDatapathId(), deviceInfo.getVersion(), singleReply);
final Iterable<? extends DataObject> allMultipartData = multipartDataList;
//TODO: following part is focused on flow stats only - need more general approach if used for more than flow stats
ListenableFuture<Void> future;
if (virgin) {
- future = StatisticsGatheringUtils.deleteAllKnownFlows(deviceState, registry, txFacade);
+ future = StatisticsGatheringUtils.deleteAllKnownFlows(deviceInfo, registry, txFacade);
virgin = false;
} else {
future = Futures.immediateFuture(null);
@Override
public Void apply(final Void input) {
StatisticsGatheringUtils.writeFlowStatistics((Iterable<FlowsStatisticsUpdate>) allMultipartData,
- deviceState, registry, txFacade);
+ deviceInfo, registry, txFacade);
if (!multipartReply.getFlags().isOFPMPFREQMORE()) {
endCollecting();
}
public Future<BigInteger> getGenerationIdFromDevice(final Short version) {
- LOG.info("getGenerationIdFromDevice called for device:{}", getNodeId().getValue());
+ LOG.info("getGenerationIdFromDevice called for device:{}", getDeviceInfo().getNodeId().getValue());
// send a dummy no-change role request to get the generation-id of the switch
final RoleRequestInputBuilder roleRequestInputBuilder = new RoleRequestInputBuilder();
finalFuture.set(roleRequestOutput.getGenerationId());
} else {
LOG.info("roleRequestOutput is null in getGenerationIdFromDevice");
- finalFuture.setException(new RoleChangeException("Exception in getting generationId for device:" + getNodeId().getValue()));
+ finalFuture.setException(new RoleChangeException("Exception in getting generationId for device:" + getDeviceInfo().getNodeId().getValue()));
}
} else {
public Future<RpcResult<SetRoleOutput>> submitRoleChange(final OfpRole ofpRole, final Short version, final BigInteger generationId) {
LOG.info("submitRoleChange called for device:{}, role:{}",
- getNodeId(), ofpRole);
+ getDeviceInfo().getNodeId(), ofpRole);
final RoleRequestInputBuilder roleRequestInputBuilder = new RoleRequestInputBuilder();
roleRequestInputBuilder.setRole(toOFJavaRole(ofpRole));
roleRequestInputBuilder.setVersion(version);
@Override
public void onSuccess(final RpcResult<RoleRequestOutput> roleRequestOutputRpcResult) {
LOG.info("submitRoleChange onSuccess for device:{}, role:{}",
- getNodeId(), ofpRole);
+ getDeviceInfo().getNodeId(), ofpRole);
final RoleRequestOutput roleRequestOutput = roleRequestOutputRpcResult.getResult();
final Collection<RpcError> rpcErrors = roleRequestOutputRpcResult.getErrors();
if (roleRequestOutput != null) {
@Override
public void onFailure(final Throwable throwable) {
LOG.error("submitRoleChange onFailure for device:{}, role:{}",
- getNodeId(), ofpRole, throwable);
+ getDeviceInfo().getNodeId(), ofpRole, throwable);
finalFuture.setException(throwable);
}
});
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
import org.opendaylight.openflowplugin.api.openflow.device.Xid;
import org.opendaylight.openflowplugin.extension.api.ConvertorMessageToOFJava;
-import org.opendaylight.openflowplugin.extension.api.ExtensionConverterProviderKeeper;
import org.opendaylight.openflowplugin.extension.api.TypeVersionKey;
+import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
import org.opendaylight.openflowplugin.extension.api.exception.ConversionException;
import org.opendaylight.openflowplugin.extension.api.exception.ConverterNotFoundException;
import org.opendaylight.yang.gen.v1.urn.opendaylight.experimenter.message.service.rev151020.SalExperimenterMessageService;
public class SalExperimenterMessageServiceImpl extends AbstractVoidService<SendExperimenterInput> implements SalExperimenterMessageService {
- public SalExperimenterMessageServiceImpl(final RequestContextStack requestContextStack, final DeviceContext deviceContext) {
+ private final ExtensionConverterProvider extensionConverterProvider;
+
+ public SalExperimenterMessageServiceImpl(final RequestContextStack requestContextStack,
+ final DeviceContext deviceContext,
+ final ExtensionConverterProvider extensionConverterProvider) {
super(requestContextStack, deviceContext);
+ this.extensionConverterProvider = extensionConverterProvider;
}
@Override
protected OfHeader buildRequest(Xid xid, SendExperimenterInput input) throws ConversionException {
final TypeVersionKey key = new TypeVersionKey(input.getExperimenterMessageOfChoice().getImplementedInterface(), getVersion());
final ConvertorMessageToOFJava<ExperimenterMessageOfChoice, ExperimenterDataOfChoice> messageConverter =
- ((ExtensionConverterProviderKeeper) getDeviceContext())
- .getExtensionConverterProvider().getMessageConverter(key);
+ extensionConverterProvider.getMessageConverter(key);
if (messageConverter == null) {
throw new ConverterNotFoundException(key.toString());
}
if (itemLifecycleListener != null) {
KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
- deviceContext.getDeviceState().getNodeInstanceIdentifier());
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
final FlowBuilder flowBuilder = new FlowBuilder(input).setId(flowDescriptor.getFlowId());
itemLifecycleListener.onAdded(flowPath, flowBuilder.build());
}
deviceContext.getDeviceFlowRegistry().retrieveIdForFlow(flowRegistryKey);
if (flowDescriptor != null) {
KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
- deviceContext.getDeviceState().getNodeInstanceIdentifier());
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
itemLifecycleListener.onRemoved(flowPath);
}
}
final FlowDescriptor flowDescriptor = deviceContext.getDeviceFlowRegistry().retrieveIdForFlow(flowRegistryKey);
if (flowDescriptor != null) {
KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
- deviceContext.getDeviceState().getNodeInstanceIdentifier());
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
itemLifecycleListener.onRemoved(flowPath);
}
}
if (itemLifecycleListener != null) {
KeyedInstanceIdentifier<Flow, FlowKey> flowPath = createFlowPath(flowDescriptor,
- deviceContext.getDeviceState().getNodeInstanceIdentifier());
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
final FlowBuilder flowBuilder = new FlowBuilder(input.getUpdatedFlow()).setId(flowDescriptor.getFlowId());
itemLifecycleListener.onAdded(flowPath, flowBuilder.build());
}
@Override
public Future<RpcResult<AddGroupOutput>> addGroup(final AddGroupInput input) {
- addGroup.getDeviceContext().getDeviceGroupRegistry().store(input.getGroupId());
+ addGroup.getDeviceRegistry().getDeviceGroupRegistry().store(input.getGroupId());
final ListenableFuture<RpcResult<AddGroupOutput>> resultFuture = addGroup.handleServiceCall(input);
Futures.addCallback(resultFuture, new FutureCallback<RpcResult<AddGroupOutput>>() {
@Override
@Override
public Future<RpcResult<RemoveGroupOutput>> removeGroup(final RemoveGroupInput input) {
- removeGroup.getDeviceContext().getDeviceGroupRegistry().markToBeremoved(input.getGroupId());
+ removeGroup.getDeviceRegistry().getDeviceGroupRegistry().markToBeremoved(input.getGroupId());
final ListenableFuture<RpcResult<RemoveGroupOutput>> resultFuture = removeGroup.handleServiceCall(input);
Futures.addCallback(resultFuture, new FutureCallback<RpcResult<RemoveGroupOutput>>() {
@Override
if (itemLifecycleListener != null) {
KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group, GroupKey> groupPath
= createGroupPath(groupId,
- deviceContext.getDeviceState().getNodeInstanceIdentifier());
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
itemLifecycleListener.onRemoved(groupPath);
}
}
if (itemLifecycleListener != null) {
KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group, GroupKey> groupPath
= createGroupPath(groupId,
- deviceContext.getDeviceState().getNodeInstanceIdentifier());
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
itemLifecycleListener.onAdded(groupPath, new GroupBuilder(data).build());
}
}
@Override
public Future<RpcResult<AddMeterOutput>> addMeter(final AddMeterInput input) {
- addMeter.getDeviceContext().getDeviceMeterRegistry().store(input.getMeterId());
+ addMeter.getDeviceRegistry().getDeviceMeterRegistry().store(input.getMeterId());
final ListenableFuture<RpcResult<AddMeterOutput>> resultFuture = addMeter.handleServiceCall(input);
Futures.addCallback(resultFuture, new FutureCallback<RpcResult<AddMeterOutput>>() {
@Override
public Future<RpcResult<RemoveMeterOutput>> removeMeter(final RemoveMeterInput input) {
- removeMeter.getDeviceContext().getDeviceMeterRegistry().markToBeremoved(input.getMeterId());
+ removeMeter.getDeviceRegistry().getDeviceMeterRegistry().markToBeremoved(input.getMeterId());
final ListenableFuture<RpcResult<RemoveMeterOutput>> resultFuture = removeMeter.handleServiceCall(input);
Futures.addCallback(resultFuture, new FutureCallback<RpcResult<RemoveMeterOutput>>() {
if (itemLifecycleListener != null) {
KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter, MeterKey> meterPath
= createMeterPath(meterId,
- deviceContext.getDeviceState().getNodeInstanceIdentifier());
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
itemLifecycleListener.onRemoved(meterPath);
}
}
if (itemLifecycleListener != null) {
KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter, MeterKey> groupPath
= createMeterPath(meterId,
- deviceContext.getDeviceState().getNodeInstanceIdentifier());
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier());
itemLifecycleListener.onAdded(groupPath, new MeterBuilder(data).build());
}
}
}
private ListenableFuture<RpcResult<SetRoleOutput>> tryToChangeRole(final OfpRole role) {
- LOG.info("RoleChangeTask called on device:{} OFPRole:{}", getNodeId().getValue(), role);
+ LOG.info("RoleChangeTask called on device:{} OFPRole:{}", getDeviceInfo().getNodeId().getValue(), role);
final Future<BigInteger> generationFuture = roleService.getGenerationIdFromDevice(getVersion());
return Futures.transform(JdkFutureAdapters.listenInPoolThread(generationFuture), (AsyncFunction<BigInteger, RpcResult<SetRoleOutput>>) generationId -> {
- LOG.debug("RoleChangeTask, GenerationIdFromDevice from device {} is {}", getNodeId().getValue(), generationId);
+ LOG.debug("RoleChangeTask, GenerationIdFromDevice from device {} is {}", getDeviceInfo().getNodeId().getValue(), generationId);
final BigInteger nextGenerationId = getNextGenerationId(generationId);
- LOG.debug("nextGenerationId received from device:{} is {}", getNodeId().getValue(), nextGenerationId);
+ LOG.debug("nextGenerationId received from device:{} is {}", getDeviceInfo().getNodeId().getValue(), nextGenerationId);
final Future<RpcResult<SetRoleOutput>> submitRoleFuture = roleService.submitRoleChange(role, getVersion(), nextGenerationId);
return JdkFutureAdapters.listenInPoolThread(submitRoleFuture);
});
final List<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures> salTableFeatures = convertToSalTableFeatures(multipartReplies);
final InstanceIdentifier<FlowCapableNode> flowCapableNodeII = InstanceIdentifier.create(Nodes.class)
- .child(Node.class, new NodeKey(getNodeId())).augmentation(FlowCapableNode.class);
+ .child(Node.class, new NodeKey(getDeviceInfo().getNodeId())).augmentation(FlowCapableNode.class);
for (final org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures tableFeatureData : salTableFeatures) {
final Short tableId = tableFeatureData.getTableId();
final KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures, TableFeaturesKey> tableFeaturesII = flowCapableNodeII
package org.opendaylight.openflowplugin.impl.statistics;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
+import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
+import org.opendaylight.openflowplugin.api.openflow.OFPContext;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
import org.opendaylight.openflowplugin.impl.services.RequestContextUtil;
import org.opendaylight.openflowplugin.impl.statistics.services.dedicated.StatisticsGatheringOnTheFlyService;
import org.opendaylight.openflowplugin.impl.statistics.services.dedicated.StatisticsGatheringService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class StatisticsContextImpl implements StatisticsContext {
+class StatisticsContextImpl implements StatisticsContext {
private static final Logger LOG = LoggerFactory.getLogger(StatisticsContextImpl.class);
private static final String CONNECTION_CLOSED = "Connection closed.";
private StatisticsGatheringOnTheFlyService statisticsGatheringOnTheFlyService;
private Timeout pollTimeout;
- private final LifecycleConductor conductor;
private volatile boolean schedulingEnabled;
+ private volatile CONTEXT_STATE contextState;
- public StatisticsContextImpl(@CheckForNull final NodeId nodeId, final boolean shuttingDownStatisticsPolling, final LifecycleConductor lifecycleConductor) {
- this.conductor = lifecycleConductor;
- this.deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(nodeId));
+ StatisticsContextImpl(@CheckForNull final DeviceInfo deviceInfo, final boolean shuttingDownStatisticsPolling, final LifecycleConductor lifecycleConductor) {
+ this.deviceContext = Preconditions.checkNotNull(lifecycleConductor.getDeviceContext(deviceInfo));
this.devState = Preconditions.checkNotNull(deviceContext.getDeviceState());
this.shuttingDownStatisticsPolling = shuttingDownStatisticsPolling;
emptyFuture = Futures.immediateFuture(false);
statisticsGatheringOnTheFlyService = new StatisticsGatheringOnTheFlyService(this, deviceContext);
itemLifeCycleListener = new ItemLifecycleListenerImpl(deviceContext);
statListForCollectingInitialization();
- this.deviceContext.setStatisticsContext(StatisticsContextImpl.this);
+ contextState = CONTEXT_STATE.WORKING;
}
@Override
}
}
+
+ @Override
+ public ListenableFuture<Boolean> initialGatherDynamicData() {
+ return gatherDynamicData(true);
+ }
+
@Override
- public ListenableFuture<Boolean> gatherDynamicData() {
+ public ListenableFuture<Boolean> gatherDynamicData(){
+ return gatherDynamicData(false);
+ }
+
+ private ListenableFuture<Boolean> gatherDynamicData(final boolean initial) {
if (shuttingDownStatisticsPolling) {
- LOG.debug("Statistics for device {} is not enabled.", deviceContext.getDeviceState().getNodeId());
+ LOG.debug("Statistics for device {} is not enabled.", deviceContext.getDeviceInfo().getNodeId());
return Futures.immediateFuture(Boolean.TRUE);
}
final ListenableFuture<Boolean> errorResultFuture = deviceConnectionCheck();
// write start timestamp to state snapshot container
StatisticsGatheringUtils.markDeviceStateSnapshotStart(deviceContext);
- statChainFuture(statIterator, settableStatResultFuture);
+ statChainFuture(statIterator, settableStatResultFuture, initial);
// write end timestamp to state snapshot container
Futures.addCallback(settableStatResultFuture, new FutureCallback<Boolean>() {
}
}
- private ListenableFuture<Boolean> chooseStat(final MultipartType multipartType){
+ private ListenableFuture<Boolean> chooseStat(final MultipartType multipartType, final boolean initial){
switch (multipartType) {
case OFPMPFLOW:
- return collectFlowStatistics(multipartType);
+ return collectFlowStatistics(multipartType, initial);
case OFPMPTABLE:
return collectTableStatistics(multipartType);
case OFPMPPORTSTATS:
@Override
public void close() {
- schedulingEnabled = false;
- for (final Iterator<RequestContext<?>> iterator = Iterators.consumingIterator(requestContexts.iterator());
- iterator.hasNext();) {
- RequestContextUtil.closeRequestContextWithRpcError(iterator.next(), CONNECTION_CLOSED);
- }
- if (null != pollTimeout && !pollTimeout.isExpired()) {
- pollTimeout.cancel();
+ if (CONTEXT_STATE.TERMINATION.equals(contextState)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Statistics context is already in state TERMINATION.");
+ }
+ } else {
+ contextState = CONTEXT_STATE.TERMINATION;
+ schedulingEnabled = false;
+ for (final Iterator<RequestContext<?>> iterator = Iterators.consumingIterator(requestContexts.iterator());
+ iterator.hasNext(); ) {
+ RequestContextUtil.closeRequestContextWithRpcError(iterator.next(), CONNECTION_CLOSED);
+ }
+ if (null != pollTimeout && !pollTimeout.isExpired()) {
+ pollTimeout.cancel();
+ }
}
}
@Override
public Optional<Timeout> getPollTimeout() {
- return Optional.fromNullable(pollTimeout);
+ return Optional.ofNullable(pollTimeout);
}
- private void statChainFuture(final Iterator<MultipartType> iterator, final SettableFuture<Boolean> resultFuture) {
+ private void statChainFuture(final Iterator<MultipartType> iterator, final SettableFuture<Boolean> resultFuture, final boolean initial) {
if (ConnectionContext.CONNECTION_STATE.RIP.equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) {
final String errMsg = String.format("Device connection is closed for Node : %s.",
- deviceContext.getDeviceState().getNodeId());
+ deviceContext.getDeviceInfo().getNodeId());
LOG.debug(errMsg);
resultFuture.setException(new IllegalStateException(errMsg));
return;
}
if ( ! iterator.hasNext()) {
resultFuture.set(Boolean.TRUE);
- LOG.debug("Stats collection successfully finished for node {}", deviceContext.getDeviceState().getNodeId());
+ LOG.debug("Stats collection successfully finished for node {}", deviceContext.getDeviceInfo().getNodeId());
return;
}
final MultipartType nextType = iterator.next();
- LOG.debug("Stats iterating to next type for node {} of type {}", deviceContext.getDeviceState().getNodeId(), nextType);
+ LOG.debug("Stats iterating to next type for node {} of type {}", deviceContext.getDeviceInfo().getNodeId(), nextType);
- final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = chooseStat(nextType);
+ final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = chooseStat(nextType, initial);
Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
@Override
public void onSuccess(final Boolean result) {
- statChainFuture(iterator, resultFuture);
+ statChainFuture(iterator, resultFuture, initial);
}
@Override
public void onFailure(@Nonnull final Throwable t) {
@VisibleForTesting
ListenableFuture<Boolean> deviceConnectionCheck() {
if (!ConnectionContext.CONNECTION_STATE.WORKING.equals(deviceContext.getPrimaryConnectionContext().getConnectionState())) {
- ListenableFuture<Boolean> resultingFuture = SettableFuture.create();
+ ListenableFuture<Boolean> resultingFuture;
switch (deviceContext.getPrimaryConnectionContext().getConnectionState()) {
case RIP:
final String errMsg = String.format("Device connection doesn't exist anymore. Primary connection status : %s",
return null;
}
- private ListenableFuture<Boolean> collectFlowStatistics(final MultipartType multipartType) {
+ //TODO: Refactor twice sending deviceContext into gatheringStatistics
+ private ListenableFuture<Boolean> collectFlowStatistics(final MultipartType multipartType, final boolean initial) {
return devState.isFlowStatisticsAvailable() ? StatisticsGatheringUtils.gatherStatistics(
- statisticsGatheringOnTheFlyService, deviceContext, /*MultipartType.OFPMPFLOW*/ multipartType) : emptyFuture;
+ statisticsGatheringOnTheFlyService,
+ deviceContext.getDeviceInfo(),
+ /*MultipartType.OFPMPFLOW*/ multipartType,
+ deviceContext,
+ deviceContext,
+ initial) : emptyFuture;
}
private ListenableFuture<Boolean> collectTableStatistics(final MultipartType multipartType) {
return devState.isTableStatisticsAvailable() ? StatisticsGatheringUtils.gatherStatistics(
- statisticsGatheringService, deviceContext, /*MultipartType.OFPMPTABLE*/ multipartType) : emptyFuture;
+ statisticsGatheringService,
+ deviceContext.getDeviceInfo(),
+ /*MultipartType.OFPMPTABLE*/ multipartType,
+ deviceContext,
+ deviceContext,
+ false) : emptyFuture;
}
private ListenableFuture<Boolean> collectPortStatistics(final MultipartType multipartType) {
return devState.isPortStatisticsAvailable() ? StatisticsGatheringUtils.gatherStatistics(
- statisticsGatheringService, deviceContext, /*MultipartType.OFPMPPORTSTATS*/ multipartType) : emptyFuture;
+ statisticsGatheringService,
+ deviceContext.getDeviceInfo(),
+ /*MultipartType.OFPMPPORTSTATS*/ multipartType,
+ deviceContext,
+ deviceContext,
+ false) : emptyFuture;
}
private ListenableFuture<Boolean> collectQueueStatistics(final MultipartType multipartType) {
- return devState.isQueueStatisticsAvailable() ? StatisticsGatheringUtils.gatherStatistics(
- statisticsGatheringService, deviceContext, /*MultipartType.OFPMPQUEUE*/ multipartType) : emptyFuture;
+ return !devState.isQueueStatisticsAvailable() ? emptyFuture : StatisticsGatheringUtils.gatherStatistics(
+ statisticsGatheringService,
+ deviceContext.getDeviceInfo(),
+ /*MultipartType.OFPMPQUEUE*/ multipartType,
+ deviceContext,
+ deviceContext,
+ false);
}
private ListenableFuture<Boolean> collectGroupDescStatistics(final MultipartType multipartType) {
return devState.isGroupAvailable() ? StatisticsGatheringUtils.gatherStatistics(
- statisticsGatheringService, deviceContext, /*MultipartType.OFPMPGROUPDESC*/ multipartType) : emptyFuture;
+ statisticsGatheringService,
+ deviceContext.getDeviceInfo(),
+ /*MultipartType.OFPMPGROUPDESC*/ multipartType,
+ deviceContext,
+ deviceContext,
+ false) : emptyFuture;
}
private ListenableFuture<Boolean> collectGroupStatistics(final MultipartType multipartType) {
return devState.isGroupAvailable() ? StatisticsGatheringUtils.gatherStatistics(
- statisticsGatheringService, deviceContext, /*MultipartType.OFPMPGROUP*/ multipartType) : emptyFuture;
+ statisticsGatheringService,
+ deviceContext.getDeviceInfo(),
+ /*MultipartType.OFPMPGROUP*/ multipartType,
+ deviceContext,
+ deviceContext,
+ false) : emptyFuture;
}
private ListenableFuture<Boolean> collectMeterConfigStatistics(final MultipartType multipartType) {
return devState.isMetersAvailable() ? StatisticsGatheringUtils.gatherStatistics(
- statisticsGatheringService, deviceContext, /*MultipartType.OFPMPMETERCONFIG*/ multipartType) : emptyFuture;
+ statisticsGatheringService,
+ deviceContext.getDeviceInfo(),
+ /*MultipartType.OFPMPMETERCONFIG*/ multipartType,
+ deviceContext,
+ deviceContext,
+ false) : emptyFuture;
}
private ListenableFuture<Boolean> collectMeterStatistics(final MultipartType multipartType) {
return devState.isMetersAvailable() ? StatisticsGatheringUtils.gatherStatistics(
- statisticsGatheringService, deviceContext, /*MultipartType.OFPMPMETER*/ multipartType) : emptyFuture;
+ statisticsGatheringService,
+ deviceContext.getDeviceInfo(),
+ /*MultipartType.OFPMPMETER*/ multipartType,
+ deviceContext,
+ deviceContext,
+ false) : emptyFuture;
}
@VisibleForTesting
return itemLifeCycleListener;
}
-
@Override
- public DeviceContext getDeviceContext() {
- return deviceContext;
+ public CONTEXT_STATE getState() {
+ return contextState;
}
}
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceRegistry;
import org.opendaylight.openflowplugin.api.openflow.device.TxFacade;
import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
+import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
+import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.EventIdentifier;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.StatisticsGatherer;
import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
import org.slf4j.LoggerFactory;
/**
- * Created by Martin Bobak <mbobak@cisco.com> on 2.4.2015.
+ * Utils for gatherig statistics
*/
public final class StatisticsGatheringUtils {
- public static String DATE_AND_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
+ private static String DATE_AND_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
private static final Logger LOG = LoggerFactory.getLogger(StatisticsGatheringUtils.class);
private static final SinglePurposeMultipartReplyTranslator MULTIPART_REPLY_TRANSLATOR = new SinglePurposeMultipartReplyTranslator();
- public static final String QUEUE2_REQCTX = "QUEUE2REQCTX-";
+ private static final String QUEUE2_REQCTX = "QUEUE2REQCTX-";
private StatisticsGatheringUtils() {
throw new IllegalStateException("This class should not be instantiated.");
}
-
- public static ListenableFuture<Boolean> gatherStatistics(final StatisticsGatherer statisticsGatheringService,
- final DeviceContext deviceContext,
- final MultipartType type) {
- final String deviceId = deviceContext.getPrimaryConnectionContext().getNodeId().toString();
+ //TODO: Flow-,Group- and Meter- registry should be not in device context, consider move it in separate class
+ static ListenableFuture<Boolean> gatherStatistics(final StatisticsGatherer statisticsGatheringService,
+ final DeviceInfo deviceInfo,
+ final MultipartType type,
+ final TxFacade txFacade,
+ final DeviceRegistry registry,
+ final Boolean initial) {
EventIdentifier wholeProcessEventIdentifier = null;
if (MultipartType.OFPMPFLOW.equals(type)) {
- wholeProcessEventIdentifier = new EventIdentifier(type.toString(), deviceId);
+ wholeProcessEventIdentifier = new EventIdentifier(type.toString(), deviceInfo.getNodeId().getValue());
EventsTimeCounter.markStart(wholeProcessEventIdentifier);
}
- final EventIdentifier ofpQueuToRequestContextEventIdentifier = new EventIdentifier(QUEUE2_REQCTX + type.toString(), deviceId);
+ final EventIdentifier ofpQueuToRequestContextEventIdentifier = new EventIdentifier(QUEUE2_REQCTX + type.toString(), deviceInfo.getNodeId().toString());
final ListenableFuture<RpcResult<List<MultipartReply>>> statisticsDataInFuture =
JdkFutureAdapters.listenInPoolThread(statisticsGatheringService.getStatisticsOfType(
ofpQueuToRequestContextEventIdentifier, type));
- return transformAndStoreStatisticsData(statisticsDataInFuture, deviceContext, wholeProcessEventIdentifier, type);
+ return transformAndStoreStatisticsData(statisticsDataInFuture, deviceInfo, wholeProcessEventIdentifier, type, txFacade, registry, initial);
}
private static ListenableFuture<Boolean> transformAndStoreStatisticsData(final ListenableFuture<RpcResult<List<MultipartReply>>> statisticsDataInFuture,
- final DeviceContext deviceContext,
- final EventIdentifier eventIdentifier, final MultipartType type) {
+ final DeviceInfo deviceInfo,
+ final EventIdentifier eventIdentifier,
+ final MultipartType type,
+ final TxFacade txFacade,
+ final DeviceRegistry registry,
+ final boolean initial) {
return Futures.transform(statisticsDataInFuture, new AsyncFunction<RpcResult<List<MultipartReply>>, Boolean>() {
@Nullable
@Override
public ListenableFuture<Boolean> apply(final RpcResult<List<MultipartReply>> rpcResult) {
boolean isMultipartProcessed = Boolean.TRUE;
if (rpcResult.isSuccessful()) {
- LOG.debug("Stats reply successfully received for node {} of type {}", deviceContext.getDeviceState().getNodeId(), type);
+ LOG.debug("Stats reply successfully received for node {} of type {}", deviceInfo.getNodeId(), type);
// TODO: in case the result value is null then multipart data probably got processed on the fly -
// TODO: this contract should by clearly stated and enforced - now simple true value is returned
try {
for (final MultipartReply singleReply : rpcResult.getResult()) {
final List<? extends DataObject> multipartDataList = MULTIPART_REPLY_TRANSLATOR.translate(
- deviceContext.getPrimaryConnectionContext().getFeatures().getDatapathId(),
- deviceContext.getPrimaryConnectionContext().getFeatures().getVersion(), singleReply);
+ deviceInfo.getDatapathId(),
+ deviceInfo.getVersion(), singleReply);
multipartData = multipartDataList.get(0);
allMultipartData = Iterables.concat(allMultipartData, multipartDataList);
}
} catch (final Exception e) {
LOG.warn("stats processing of type {} for node {} failed during transfomation step",
- type, deviceContext.getDeviceState().getNodeId(), e);
+ type, deviceInfo.getNodeId(), e);
return Futures.immediateFailedFuture(e);
}
try {
if (multipartData instanceof GroupStatisticsUpdated) {
- processGroupStatistics((Iterable<GroupStatisticsUpdated>) allMultipartData, deviceContext);
+ processGroupStatistics((Iterable<GroupStatisticsUpdated>) allMultipartData, deviceInfo, txFacade);
} else if (multipartData instanceof MeterStatisticsUpdated) {
- processMetersStatistics((Iterable<MeterStatisticsUpdated>) allMultipartData, deviceContext);
+ processMetersStatistics((Iterable<MeterStatisticsUpdated>) allMultipartData, deviceInfo, txFacade);
} else if (multipartData instanceof NodeConnectorStatisticsUpdate) {
- processNodeConnectorStatistics((Iterable<NodeConnectorStatisticsUpdate>) allMultipartData, deviceContext);
+ processNodeConnectorStatistics((Iterable<NodeConnectorStatisticsUpdate>) allMultipartData, deviceInfo, txFacade);
} else if (multipartData instanceof FlowTableStatisticsUpdate) {
- processFlowTableStatistics((Iterable<FlowTableStatisticsUpdate>) allMultipartData, deviceContext);
+ processFlowTableStatistics((Iterable<FlowTableStatisticsUpdate>) allMultipartData, deviceInfo, txFacade);
} else if (multipartData instanceof QueueStatisticsUpdate) {
- processQueueStatistics((Iterable<QueueStatisticsUpdate>) allMultipartData, deviceContext);
+ processQueueStatistics((Iterable<QueueStatisticsUpdate>) allMultipartData, deviceInfo, txFacade);
} else if (multipartData instanceof FlowsStatisticsUpdate) {
/* FlowStat Processing is realized by NettyThread only by initPhase, otherwise it is realized
* by MD-SAL thread */
- return processFlowStatistics((Iterable<FlowsStatisticsUpdate>) allMultipartData, deviceContext, eventIdentifier);
+ return processFlowStatistics((Iterable<FlowsStatisticsUpdate>) allMultipartData, deviceInfo, txFacade, registry.getDeviceFlowRegistry(), initial, eventIdentifier);
} else if (multipartData instanceof GroupDescStatsUpdated) {
- processGroupDescStats((Iterable<GroupDescStatsUpdated>) allMultipartData, deviceContext);
+ processGroupDescStats((Iterable<GroupDescStatsUpdated>) allMultipartData, deviceInfo, txFacade, registry.getDeviceGroupRegistry());
} else if (multipartData instanceof MeterConfigStatsUpdated) {
- processMeterConfigStatsUpdated((Iterable<MeterConfigStatsUpdated>) allMultipartData, deviceContext);
+ processMeterConfigStatsUpdated((Iterable<MeterConfigStatsUpdated>) allMultipartData, deviceInfo, txFacade, registry.getDeviceMeterRegistry());
} else {
isMultipartProcessed = Boolean.FALSE;
}
} catch (final Exception e) {
LOG.warn("stats processing of type {} for node {} failed during write-to-tx step",
- type, deviceContext.getDeviceState().getNodeId(), e);
+ type, deviceInfo.getNodeId(), e);
return Futures.immediateFailedFuture(e);
}
- LOG.debug("Stats reply added to transaction for node {} of type {}", deviceContext.getDeviceState().getNodeId(), type);
+ LOG.debug("Stats reply added to transaction for node {} of type {}", deviceInfo.getNodeId(), type);
//TODO : implement experimenter
} else {
- LOG.debug("Stats reply was empty for node {} of type {}", deviceContext.getDeviceState().getNodeId(), type);
+ LOG.debug("Stats reply was empty for node {} of type {}", deviceInfo.getNodeId(), type);
}
} else {
- LOG.debug("Stats reply FAILED for node {} of type {}: {}", deviceContext.getDeviceState().getNodeId(), type, rpcResult.getErrors());
+ LOG.debug("Stats reply FAILED for node {} of type {}: {}", deviceInfo.getNodeId(), type, rpcResult.getErrors());
isMultipartProcessed = Boolean.FALSE;
}
return Futures.immediateFuture(isMultipartProcessed);
});
}
- private static void processMeterConfigStatsUpdated(final Iterable<MeterConfigStatsUpdated> data, final DeviceContext deviceContext) throws Exception {
- final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceContext.getDeviceState());
- deleteAllKnownMeters(deviceContext, fNodeIdent);
+ private static void processMeterConfigStatsUpdated(final Iterable<MeterConfigStatsUpdated> data,
+ final DeviceInfo deviceInfo,
+ final TxFacade txFacade,
+ final DeviceMeterRegistry meterRegistry) throws Exception {
+ final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
+ deleteAllKnownMeters(meterRegistry, fNodeIdent, txFacade);
for (final MeterConfigStatsUpdated meterConfigStatsUpdated : data) {
for (final MeterConfigStats meterConfigStats : meterConfigStatsUpdated.getMeterConfigStats()) {
final MeterId meterId = meterConfigStats.getMeterId();
final MeterBuilder meterBuilder = new MeterBuilder(meterConfigStats);
meterBuilder.setKey(new MeterKey(meterId));
meterBuilder.addAugmentation(NodeMeterStatistics.class, new NodeMeterStatisticsBuilder().build());
- deviceContext.getDeviceMeterRegistry().store(meterId);
- deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, meterInstanceIdentifier, meterBuilder.build());
+ meterRegistry.store(meterId);
+ txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, meterInstanceIdentifier, meterBuilder.build());
}
}
- deviceContext.submitTransaction();
+ txFacade.submitTransaction();
}
private static ListenableFuture<Boolean> processFlowStatistics(final Iterable<FlowsStatisticsUpdate> data,
- final DeviceContext deviceContext, final EventIdentifier eventIdentifier) {
- final ListenableFuture<Void> deleFuture = deleteAllKnownFlows(deviceContext.getDeviceState(),
- deviceContext.getDeviceFlowRegistry(), deviceContext);
- return Futures.transform(deleFuture, new Function<Void, Boolean>() {
+ final DeviceInfo deviceInfo,
+ final TxFacade txFacade,
+ final DeviceFlowRegistry flowRegistry,
+ final boolean initial,
+ final EventIdentifier eventIdentifier) {
+ final ListenableFuture<Void> deleteFuture = initial ? Futures.immediateFuture(null) : deleteAllKnownFlows(deviceInfo,
+ flowRegistry, txFacade);
+ return Futures.transform(deleteFuture, new Function<Void, Boolean>() {
@Override
public Boolean apply(final Void input) {
- writeFlowStatistics(data, deviceContext.getDeviceState(), deviceContext.getDeviceFlowRegistry(),
- deviceContext);
- deviceContext.submitTransaction();
+ writeFlowStatistics(data, deviceInfo, flowRegistry, txFacade);
+ txFacade.submitTransaction();
EventsTimeCounter.markEnd(eventIdentifier);
return Boolean.TRUE;
}
}
public static void writeFlowStatistics(final Iterable<FlowsStatisticsUpdate> data,
- final DeviceState deviceState,
+ final DeviceInfo deviceInfo,
final DeviceFlowRegistry registry,
final TxFacade txFacade) {
- final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceState);
+ final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
try {
for (final FlowsStatisticsUpdate flowsStatistics : data) {
for (final FlowAndStatisticsMapList flowStat : flowsStatistics.getFlowAndStatisticsMapList()) {
return flowStatisticsDataBld;
}
- public static ListenableFuture<Void> deleteAllKnownFlows(final DeviceState deviceState,
+ public static ListenableFuture<Void> deleteAllKnownFlows(final DeviceInfo deviceInfo,
final DeviceFlowRegistry registry,
final TxFacade txFacade) {
- /* DeviceState.deviceSynchronized is a marker for actual phase - false means initPhase, true means noInitPhase */
- if (deviceState.deviceSynchronized()) {
- final InstanceIdentifier<FlowCapableNode> flowCapableNodePath = assembleFlowCapableNodeInstanceIdentifier(deviceState);
- final ReadOnlyTransaction readTx = txFacade.getReadTransaction();
- final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowCapableNodeFuture = readTx.read(
- LogicalDatastoreType.OPERATIONAL, flowCapableNodePath);
-
- /* we wish to close readTx for fallBack */
- Futures.withFallback(flowCapableNodeFuture, new FutureFallback<Optional<FlowCapableNode>>() {
-
- @Override
- public ListenableFuture<Optional<FlowCapableNode>> create(final Throwable t) throws Exception {
- readTx.close();
- return Futures.immediateFailedFuture(t);
- }
- });
- /*
- * we have to read actual tables with all information before we set empty Flow list, merge is expensive and
- * not applicable for lists
- */
- return Futures.transform(flowCapableNodeFuture, new AsyncFunction<Optional<FlowCapableNode>, Void>() {
-
- @Override
- public ListenableFuture<Void> apply(final Optional<FlowCapableNode> flowCapNodeOpt) throws Exception {
- if (flowCapNodeOpt.isPresent()) {
- for (final Table tableData : flowCapNodeOpt.get().getTable()) {
- final Table table = new TableBuilder(tableData).setFlow(Collections.<Flow>emptyList()).build();
- final InstanceIdentifier<Table> iiToTable = flowCapableNodePath.child(Table.class, tableData.getKey());
- txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToTable, table);
- }
+ final InstanceIdentifier<FlowCapableNode> flowCapableNodePath = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
+ final ReadOnlyTransaction readTx = txFacade.getReadTransaction();
+ final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowCapableNodeFuture = readTx.read(
+ LogicalDatastoreType.OPERATIONAL, flowCapableNodePath);
+
+ /* we wish to close readTx for fallBack */
+ Futures.withFallback(flowCapableNodeFuture, new FutureFallback<Optional<FlowCapableNode>>() {
+
+ @Override
+ public ListenableFuture<Optional<FlowCapableNode>> create(final Throwable t) throws Exception {
+ readTx.close();
+ return Futures.immediateFailedFuture(t);
+ }
+ });
+ /*
+ * we have to read actual tables with all information before we set empty Flow list, merge is expensive and
+ * not applicable for lists
+ */
+ return Futures.transform(flowCapableNodeFuture, new AsyncFunction<Optional<FlowCapableNode>, Void>() {
+
+ @Override
+ public ListenableFuture<Void> apply(final Optional<FlowCapableNode> flowCapNodeOpt) throws Exception {
+ if (flowCapNodeOpt.isPresent()) {
+ for (final Table tableData : flowCapNodeOpt.get().getTable()) {
+ final Table table = new TableBuilder(tableData).setFlow(Collections.<Flow>emptyList()).build();
+ final InstanceIdentifier<Table> iiToTable = flowCapableNodePath.child(Table.class, tableData.getKey());
+ txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, iiToTable, table);
}
- registry.removeMarked();
- readTx.close();
- return Futures.immediateFuture(null);
}
+ registry.removeMarked();
+ readTx.close();
+ return Futures.immediateFuture(null);
+ }
- });
- }
- return Futures.immediateFuture(null);
+ });
}
- private static void processQueueStatistics(final Iterable<QueueStatisticsUpdate> data, final DeviceContext deviceContext) throws Exception {
+ private static void processQueueStatistics(final Iterable<QueueStatisticsUpdate> data, final DeviceInfo deviceInfo, final TxFacade txFacade) throws Exception {
// TODO: clean all queues of all node-connectors before writing up-to-date stats
- final InstanceIdentifier<Node> nodeIdent = deviceContext.getDeviceState().getNodeInstanceIdentifier();
+ final InstanceIdentifier<Node> nodeIdent = deviceInfo.getNodeInstanceIdentifier();
for (final QueueStatisticsUpdate queueStatisticsUpdate : data) {
for (final QueueIdAndStatisticsMap queueStat : queueStatisticsUpdate.getQueueIdAndStatisticsMap()) {
if (queueStat.getQueueId() != null) {
.setQueueId(queueStat.getQueueId())
// node-connector-id is already contained in parent node and the port-id here is of incompatible format
.addAugmentation(FlowCapableNodeConnectorQueueStatisticsData.class, statBuild.build());
- deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, queueIdent, queueBuilder.build());
+ txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, queueIdent, queueBuilder.build());
}
}
}
- deviceContext.submitTransaction();
+ txFacade.submitTransaction();
}
- private static void processFlowTableStatistics(final Iterable<FlowTableStatisticsUpdate> data, final DeviceContext deviceContext) throws Exception {
- final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceContext.getDeviceState());
+ private static void processFlowTableStatistics(final Iterable<FlowTableStatisticsUpdate> data, final DeviceInfo deviceInfo, final TxFacade txFacade) throws Exception {
+ final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
for (final FlowTableStatisticsUpdate flowTableStatisticsUpdate : data) {
for (final FlowTableAndStatisticsMap tableStat : flowTableStatisticsUpdate.getFlowTableAndStatisticsMap()) {
final InstanceIdentifier<FlowTableStatistics> tStatIdent = fNodeIdent.child(Table.class, new TableKey(tableStat.getTableId().getValue()))
.augmentation(FlowTableStatisticsData.class).child(FlowTableStatistics.class);
final FlowTableStatistics stats = new FlowTableStatisticsBuilder(tableStat).build();
- deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tStatIdent, stats);
+ txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tStatIdent, stats);
}
}
- deviceContext.submitTransaction();
+ txFacade.submitTransaction();
}
- private static void processNodeConnectorStatistics(final Iterable<NodeConnectorStatisticsUpdate> data, final DeviceContext deviceContext) throws Exception {
- final InstanceIdentifier<Node> nodeIdent = deviceContext.getDeviceState().getNodeInstanceIdentifier();
+ private static void processNodeConnectorStatistics(final Iterable<NodeConnectorStatisticsUpdate> data, final DeviceInfo deviceInfo, final TxFacade txFacade) throws Exception {
+ final InstanceIdentifier<Node> nodeIdent = deviceInfo.getNodeInstanceIdentifier();
for (final NodeConnectorStatisticsUpdate nodeConnectorStatisticsUpdate : data) {
for (final NodeConnectorStatisticsAndPortNumberMap nConnectPort : nodeConnectorStatisticsUpdate.getNodeConnectorStatisticsAndPortNumberMap()) {
final FlowCapableNodeConnectorStatistics stats = new FlowCapableNodeConnectorStatisticsBuilder(nConnectPort).build();
.augmentation(FlowCapableNodeConnectorStatisticsData.class);
final InstanceIdentifier<FlowCapableNodeConnectorStatistics> flowCapNodeConnStatIdent =
nodeConnStatIdent.child(FlowCapableNodeConnectorStatistics.class);
- deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, flowCapNodeConnStatIdent, stats);
+ txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, flowCapNodeConnStatIdent, stats);
}
}
- deviceContext.submitTransaction();
+ txFacade.submitTransaction();
}
private static void processMetersStatistics(final Iterable<MeterStatisticsUpdated> data,
- final DeviceContext deviceContext) throws Exception {
- final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceContext.getDeviceState());
+ final DeviceInfo deviceInfo,
+ final TxFacade txFacade) throws Exception {
+ final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
for (final MeterStatisticsUpdated meterStatisticsUpdated : data) {
for (final MeterStats mStat : meterStatisticsUpdated.getMeterStats()) {
final MeterStatistics stats = new MeterStatisticsBuilder(mStat).build();
final InstanceIdentifier<NodeMeterStatistics> nodeMeterStatIdent = meterIdent
.augmentation(NodeMeterStatistics.class);
final InstanceIdentifier<MeterStatistics> msIdent = nodeMeterStatIdent.child(MeterStatistics.class);
- deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, msIdent, stats);
+ txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, msIdent, stats);
}
}
- deviceContext.submitTransaction();
+ txFacade.submitTransaction();
}
- private static void deleteAllKnownMeters(final DeviceContext deviceContext, final InstanceIdentifier<FlowCapableNode> fNodeIdent) throws Exception {
- for (final MeterId meterId : deviceContext.getDeviceMeterRegistry().getAllMeterIds()) {
+ private static void deleteAllKnownMeters(final DeviceMeterRegistry meterRegistry, final InstanceIdentifier<FlowCapableNode> fNodeIdent, final TxFacade txFacade) throws Exception {
+ for (final MeterId meterId : meterRegistry.getAllMeterIds()) {
final InstanceIdentifier<Meter> meterIdent = fNodeIdent.child(Meter.class, new MeterKey(meterId));
- deviceContext.addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, meterIdent);
+ txFacade.addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, meterIdent);
}
- deviceContext.getDeviceMeterRegistry().removeMarked();
+ meterRegistry.removeMarked();
}
- private static void processGroupDescStats(final Iterable<GroupDescStatsUpdated> data, final DeviceContext deviceContext) throws Exception {
- final InstanceIdentifier<FlowCapableNode> fNodeIdent =
- deviceContext.getDeviceState().getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
- deleteAllKnownGroups(deviceContext, fNodeIdent);
+ private static void processGroupDescStats(final Iterable<GroupDescStatsUpdated> data, final DeviceInfo deviceInfo, final TxFacade txFacade, final DeviceGroupRegistry groupRegistry) throws Exception {
+ final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
+ deleteAllKnownGroups(txFacade, fNodeIdent, groupRegistry);
for (final GroupDescStatsUpdated groupDescStatsUpdated : data) {
for (final GroupDescStats groupDescStats : groupDescStatsUpdated.getGroupDescStats()) {
final InstanceIdentifier<Group> groupIdent = fNodeIdent.child(Group.class, new GroupKey(groupId));
- deviceContext.getDeviceGroupRegistry().store(groupId);
- deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, groupIdent, groupBuilder.build());
+ groupRegistry.store(groupId);
+ txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, groupIdent, groupBuilder.build());
}
}
- deviceContext.submitTransaction();
+ txFacade.submitTransaction();
}
- private static void deleteAllKnownGroups(final DeviceContext deviceContext, final InstanceIdentifier<FlowCapableNode> fNodeIdent) throws Exception {
- for (final GroupId groupId : deviceContext.getDeviceGroupRegistry().getAllGroupIds()) {
+ private static void deleteAllKnownGroups(final TxFacade txFacade, final InstanceIdentifier<FlowCapableNode> fNodeIdent, final DeviceGroupRegistry groupRegistry) throws Exception {
+ for (final GroupId groupId : groupRegistry.getAllGroupIds()) {
final InstanceIdentifier<Group> groupIdent = fNodeIdent.child(Group.class, new GroupKey(groupId));
- deviceContext.addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, groupIdent);
+ txFacade.addDeleteToTxChain(LogicalDatastoreType.OPERATIONAL, groupIdent);
}
- deviceContext.getDeviceGroupRegistry().removeMarked();
+ groupRegistry.removeMarked();
}
- private static void processGroupStatistics(final Iterable<GroupStatisticsUpdated> data, final DeviceContext deviceContext) throws Exception {
- final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceContext.getDeviceState());
+ private static void processGroupStatistics(final Iterable<GroupStatisticsUpdated> data, final DeviceInfo deviceInfo, final TxFacade txFacade) throws Exception {
+ final InstanceIdentifier<FlowCapableNode> fNodeIdent = assembleFlowCapableNodeInstanceIdentifier(deviceInfo);
for (final GroupStatisticsUpdated groupStatistics : data) {
for (final GroupStats groupStats : groupStatistics.getGroupStats()) {
final InstanceIdentifier<GroupStatistics> gsIdent = nGroupStatIdent.child(GroupStatistics.class);
final GroupStatistics stats = new GroupStatisticsBuilder(groupStats).build();
- deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, gsIdent, stats);
+ txFacade.writeToTransaction(LogicalDatastoreType.OPERATIONAL, gsIdent, stats);
}
}
- deviceContext.submitTransaction();
+ txFacade.submitTransaction();
}
- private static InstanceIdentifier<FlowCapableNode> assembleFlowCapableNodeInstanceIdentifier(final DeviceState deviceState) {
- return deviceState.getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
+ private static InstanceIdentifier<FlowCapableNode> assembleFlowCapableNodeInstanceIdentifier(final DeviceInfo deviceInfo) {
+ return deviceInfo.getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
}
/**
* @param deviceContext txManager + node path keeper
*/
static void markDeviceStateSnapshotStart(final DeviceContext deviceContext) {
- final InstanceIdentifier<FlowCapableStatisticsGatheringStatus> statusPath = deviceContext.getDeviceState()
+ final InstanceIdentifier<FlowCapableStatisticsGatheringStatus> statusPath = deviceContext.getDeviceInfo()
.getNodeInstanceIdentifier().augmentation(FlowCapableStatisticsGatheringStatus.class);
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_AND_TIME_FORMAT);
* @param succeeded outcome of currently finished gathering
*/
static void markDeviceStateSnapshotEnd(final DeviceContext deviceContext, final boolean succeeded) {
- final InstanceIdentifier<SnapshotGatheringStatusEnd> statusEndPath = deviceContext.getDeviceState()
+ final InstanceIdentifier<SnapshotGatheringStatusEnd> statusEndPath = deviceContext.getDeviceInfo()
.getNodeInstanceIdentifier().augmentation(FlowCapableStatisticsGatheringStatus.class)
.child(SnapshotGatheringStatusEnd.class);
package org.opendaylight.openflowplugin.impl.statistics;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Verify;
import com.google.common.collect.Iterators;
import com.google.common.util.concurrent.ListenableFuture;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.Future;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.CheckForNull;
+import javax.annotation.Nonnull;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
+import org.opendaylight.openflowplugin.api.openflow.OFPContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutputBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.annotation.CheckForNull;
-import javax.annotation.Nonnull;
-import java.util.Iterator;
-import java.util.concurrent.CancellationException;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.Future;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-
public class StatisticsManagerImpl implements StatisticsManager, StatisticsManagerControlService {
private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class);
private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
private DeviceTerminationPhaseHandler deviceTerminPhaseHandler;
- private final ConcurrentMap<NodeId, StatisticsContext> contexts = new ConcurrentHashMap<>();
+ private final ConcurrentMap<DeviceInfo, StatisticsContext> contexts = new ConcurrentHashMap<>();
private static final long basicTimerDelay = 3000;
private static long currentTimerDelay = basicTimerDelay;
}
@Override
- public void onDeviceContextLevelUp(final NodeId nodeId) throws Exception {
+ public void onDeviceContextLevelUp(final DeviceInfo deviceInfo) throws Exception {
- final DeviceContext deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(nodeId));
+ final DeviceContext deviceContext = Preconditions.checkNotNull(conductor.getDeviceContext(deviceInfo));
- final StatisticsContext statisticsContext = new StatisticsContextImpl(nodeId, shuttingDownStatisticsPolling, conductor);
- Verify.verify(contexts.putIfAbsent(nodeId, statisticsContext) == null, "StatisticsCtx still not closed for Node {}", nodeId);
+ final StatisticsContext statisticsContext = new StatisticsContextImpl(deviceInfo, shuttingDownStatisticsPolling, conductor);
+ Verify.verify(contexts.putIfAbsent(deviceInfo, statisticsContext) == null, "StatisticsCtx still not closed for Node {}", deviceInfo.getNodeId());
- deviceContext.getDeviceState().setDeviceSynchronized(true);
- deviceInitPhaseHandler.onDeviceContextLevelUp(nodeId);
+ deviceInitPhaseHandler.onDeviceContextLevelUp(deviceInfo);
}
@VisibleForTesting
- void pollStatistics(final DeviceContext deviceContext,
- final StatisticsContext statisticsContext,
- final TimeCounter timeCounter) {
-
- final NodeId nodeId = deviceContext.getDeviceState().getNodeId();
+ void pollStatistics(final DeviceState deviceState,
+ final StatisticsContext statisticsContext,
+ final TimeCounter timeCounter,
+ final DeviceInfo deviceInfo) {
if (!statisticsContext.isSchedulingEnabled()) {
- LOG.debug("Disabling statistics scheduling for device: {}", nodeId);
+ LOG.debug("Disabling statistics scheduling for device: {}", deviceInfo.getNodeId());
return;
}
- if (!deviceContext.getDeviceState().isValid()) {
- LOG.debug("Session is not valid for device: {}", nodeId);
+ if (!deviceState.isValid()) {
+ LOG.debug("Session is not valid for device: {}", deviceInfo.getNodeId());
return;
}
- if (!deviceContext.getDeviceState().isStatisticsPollingEnabled()) {
- LOG.debug("Statistics polling is currently disabled for device: {}", nodeId);
- scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
+ if (!deviceState.isStatisticsPollingEnabled()) {
+ LOG.debug("Statistics polling is currently disabled for device: {}", deviceInfo.getNodeId());
+ scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
return;
}
- LOG.debug("POLLING ALL STATISTICS for device: {}", nodeId);
+ LOG.debug("POLLING ALL STATISTICS for device: {}", deviceInfo.getNodeId());
timeCounter.markStart();
final ListenableFuture<Boolean> deviceStatisticsCollectionFuture = statisticsContext.gatherDynamicData();
Futures.addCallback(deviceStatisticsCollectionFuture, new FutureCallback<Boolean>() {
public void onSuccess(final Boolean o) {
timeCounter.addTimeMark();
calculateTimerDelay(timeCounter);
- scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
+ scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
}
@Override
calculateTimerDelay(timeCounter);
if (throwable instanceof CancellationException) {
/** This often happens when something wrong with akka or DS, so closing connection will help to restart device **/
- conductor.closeConnection(deviceContext.getDeviceState().getNodeId());
+ conductor.closeConnection(deviceInfo);
} else {
- scheduleNextPolling(deviceContext, statisticsContext, timeCounter);
+ scheduleNextPolling(deviceState, deviceInfo, statisticsContext, timeCounter);
}
}
});
final long averageTime = TimeUnit.MILLISECONDS.toSeconds(timeCounter.getAverageTimeBetweenMarks());
final long STATS_TIMEOUT_SEC = averageTime > 0 ? 3 * averageTime : DEFAULT_STATS_TIMEOUT_SEC;
- final TimerTask timerTask = new TimerTask() {
-
- @Override
- public void run(final Timeout timeout) throws Exception {
- if (!deviceStatisticsCollectionFuture.isDone()) {
- LOG.info("Statistics collection for node {} still in progress even after {} secs", nodeId, STATS_TIMEOUT_SEC);
- deviceStatisticsCollectionFuture.cancel(true);
- }
+ final TimerTask timerTask = timeout -> {
+ if (!deviceStatisticsCollectionFuture.isDone()) {
+ LOG.info("Statistics collection for node {} still in progress even after {} secs", deviceInfo.getNodeId(), STATS_TIMEOUT_SEC);
+ deviceStatisticsCollectionFuture.cancel(true);
}
};
conductor.newTimeout(timerTask, STATS_TIMEOUT_SEC, TimeUnit.SECONDS);
}
- private void scheduleNextPolling(final DeviceContext deviceContext,
+ private void scheduleNextPolling(final DeviceState deviceState,
+ final DeviceInfo deviceInfo,
final StatisticsContext statisticsContext,
final TimeCounter timeCounter) {
- LOG.debug("SCHEDULING NEXT STATISTICS POLLING for device: {}", deviceContext.getDeviceState().getNodeId());
+ LOG.debug("SCHEDULING NEXT STATISTICS POLLING for device: {}", deviceInfo.getNodeId());
if (!shuttingDownStatisticsPolling) {
- final Timeout pollTimeout = conductor.newTimeout(new TimerTask() {
- @Override
- public void run(final Timeout timeout) throws Exception {
- pollStatistics(deviceContext, statisticsContext, timeCounter);
- }
- }, currentTimerDelay, TimeUnit.MILLISECONDS);
+ final Timeout pollTimeout = conductor.newTimeout(timeout -> pollStatistics(deviceState, statisticsContext, timeCounter, deviceInfo), currentTimerDelay, TimeUnit.MILLISECONDS);
statisticsContext.setPollTimeout(pollTimeout);
}
}
}
@Override
- public void onDeviceContextLevelDown(final DeviceContext deviceContext) {
- final StatisticsContext statisticsContext = contexts.remove(deviceContext.getDeviceState().getNodeId());
+ public void onDeviceContextLevelDown(final DeviceInfo deviceInfo) {
+ final StatisticsContext statisticsContext = contexts.remove(deviceInfo);
if (null != statisticsContext) {
- LOG.trace("Removing device context from stack. No more statistics gathering for device: {}", deviceContext.getDeviceState().getNodeId());
+ LOG.trace("Removing device context from stack. No more statistics gathering for device: {}", deviceInfo.getNodeId());
statisticsContext.close();
}
- deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceContext);
+ deviceTerminPhaseHandler.onDeviceContextLevelDown(deviceInfo);
}
@Override
if (!workMode.equals(targetWorkMode)) {
shuttingDownStatisticsPolling = StatisticsWorkMode.FULLYDISABLED.equals(targetWorkMode);
// iterate through stats-ctx: propagate mode
- for (final StatisticsContext statisticsContext : contexts.values()) {
- final DeviceContext deviceContext = statisticsContext.getDeviceContext();
+ for (Map.Entry<DeviceInfo, StatisticsContext> entry : contexts.entrySet()) {
switch (targetWorkMode) {
case COLLECTALL:
- scheduleNextPolling(deviceContext, statisticsContext, new TimeCounter());
- for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
+ scheduleNextPolling(conductor.getDeviceContext(entry.getKey()).getDeviceState(), entry.getKey(), entry.getValue(), new TimeCounter());
+ for (final ItemLifeCycleSource lifeCycleSource : conductor.getDeviceContext(entry.getKey()).getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
lifeCycleSource.setItemLifecycleListener(null);
}
break;
case FULLYDISABLED:
- final Optional<Timeout> pollTimeout = statisticsContext.getPollTimeout();
+ final Optional<Timeout> pollTimeout = entry.getValue().getPollTimeout();
if (pollTimeout.isPresent()) {
pollTimeout.get().cancel();
}
- for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
- lifeCycleSource.setItemLifecycleListener(statisticsContext.getItemLifeCycleListener());
+ for (final ItemLifeCycleSource lifeCycleSource : conductor.getDeviceContext(entry.getKey()).getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
+ lifeCycleSource.setItemLifecycleListener(entry.getValue().getItemLifeCycleListener());
}
break;
default:
}
@Override
- public void startScheduling(final NodeId nodeId) {
+ public void startScheduling(final DeviceInfo deviceInfo) {
if (shuttingDownStatisticsPolling) {
- LOG.info("Statistics are shut down for device: {}", nodeId);
+ LOG.info("Statistics are shut down for device: {}", deviceInfo.getNodeId());
return;
}
- final StatisticsContext statisticsContext = contexts.get(nodeId);
+ final StatisticsContext statisticsContext = contexts.get(deviceInfo);
if (statisticsContext == null) {
- LOG.warn("Statistics context not found for device: {}", nodeId);
+ LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
return;
}
if (statisticsContext.isSchedulingEnabled()) {
- LOG.debug("Statistics scheduling is already enabled for device: {}", nodeId);
+ LOG.debug("Statistics scheduling is already enabled for device: {}", deviceInfo.getNodeId());
return;
}
- LOG.info("Scheduling statistics poll for device: {}", nodeId);
- final DeviceContext deviceContext = conductor.getDeviceContext(nodeId);
-
- if (deviceContext == null) {
- LOG.warn("Device context not found for device: {}", nodeId);
- return;
- }
+ LOG.info("Scheduling statistics poll for device: {}", deviceInfo.getNodeId());
statisticsContext.setSchedulingEnabled(true);
- scheduleNextPolling(deviceContext, statisticsContext, new TimeCounter());
+ scheduleNextPolling(conductor.getDeviceContext(deviceInfo).getDeviceState(), deviceInfo, statisticsContext, new TimeCounter());
}
@Override
- public void stopScheduling(final NodeId nodeId) {
- LOG.debug("Stopping statistics scheduling for device: {}", nodeId);
- final StatisticsContext statisticsContext = contexts.get(nodeId);
+ public void stopScheduling(final DeviceInfo deviceInfo) {
+ LOG.debug("Stopping statistics scheduling for device: {}", deviceInfo.getNodeId());
+ final StatisticsContext statisticsContext = contexts.get(deviceInfo);
if (statisticsContext == null) {
- LOG.warn("Statistics context not found for device: {}", nodeId);
+ LOG.warn("Statistics context not found for device: {}", deviceInfo.getNodeId());
return;
}
public void setDeviceTerminationPhaseHandler(final DeviceTerminationPhaseHandler handler) {
this.deviceTerminPhaseHandler = handler;
}
+
+ @Override
+ public <T extends OFPContext> T gainContext(DeviceInfo deviceInfo) {
+ return (T) contexts.get(deviceInfo);
+ }
}
final TranslatorKey translatorKey = new TranslatorKey(mpReply.getVersion(), MultipartReplyAggregateCase.class.getName());
final MessageTranslator<MultipartReply, AggregatedFlowStatistics> messageTranslator = translatorLibrary.lookupTranslator(translatorKey);
- final AggregatedFlowStatistics flowStatistics = messageTranslator.translate(mpReply, getDeviceContext().getDeviceState(), null);
+ final AggregatedFlowStatistics flowStatistics = messageTranslator.translate(mpReply, getDeviceInfo(), null);
final AggregateFlowStatisticsUpdateBuilder notification = new AggregateFlowStatisticsUpdateBuilder(flowStatistics)
- .setId(getDeviceContext().getDeviceState().getNodeId())
+ .setId(getDeviceInfo().getNodeId())
.setMoreReplies(Boolean.FALSE)
.setTransactionId(emulatedTxId);
@Override
public FlowsStatisticsUpdate transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
- return FlowStatisticsToNotificationTransformer.transformToNotification(result, getDeviceContext().getDeviceState(), getOfVersion(), emulatedTxId);
+ return FlowStatisticsToNotificationTransformer.transformToNotification(result, getDeviceInfo(), getOfVersion(), emulatedTxId);
}
}
@Override
public FlowsStatisticsUpdate transformToNotification(List<MultipartReply> mpResult, TransactionId emulatedTxId) {
- return FlowStatisticsToNotificationTransformer.transformToNotification(mpResult, getDeviceContext().getDeviceState(), getOfVersion(), emulatedTxId);
+ return FlowStatisticsToNotificationTransformer.transformToNotification(mpResult, getDeviceInfo(), getOfVersion(), emulatedTxId);
}
}
@Override
public GroupStatisticsUpdated transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
- return GroupStatisticsToNotificationTransformer.transformToNotification(result, getDeviceContext().getDeviceState(), getOfVersion(), emulatedTxId);
+ return GroupStatisticsToNotificationTransformer.transformToNotification(result, getDeviceInfo(), emulatedTxId);
}
}
@Override
public MeterConfigStatsUpdated transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
MeterConfigStatsUpdatedBuilder message = new MeterConfigStatsUpdatedBuilder();
- message.setId(getDeviceContext().getDeviceState().getNodeId());
+ message.setId(getDeviceInfo().getNodeId());
message.setMoreReplies(Boolean.FALSE);
message.setTransactionId(emulatedTxId);
@Override
public MeterStatisticsUpdated transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
- return MeterStatisticsToNotificationTransformer.transformToNotification(result, getDeviceContext().getDeviceState(), getOfVersion(), emulatedTxId);
+ return MeterStatisticsToNotificationTransformer.transformToNotification(result, getDeviceInfo(), getOfVersion(), emulatedTxId);
}
}
@Override
public NodeConnectorStatisticsUpdate transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
- return NodeConnectorStatisticsToNotificationTransformer.transformToNotification(result, getDeviceContext(), getOfVersion(), emulatedTxId);
+ return NodeConnectorStatisticsToNotificationTransformer.transformToNotification(result, getDeviceInfo(), getOfVersion(), emulatedTxId);
}
}
@Override
public QueueStatisticsUpdate transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
- return QueueStatisticsToNotificationTransformer.transformToNotification(result, getDeviceContext().getDeviceState(), getOfVersion(), emulatedTxId);
+ return QueueStatisticsToNotificationTransformer.transformToNotification(result, getDeviceInfo(), getOfVersion(), emulatedTxId);
}
}
@Override
public QueueStatisticsUpdate transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
- return QueueStatisticsToNotificationTransformer.transformToNotification(result, getDeviceContext().getDeviceState(), getOfVersion(), emulatedTxId);
+ return QueueStatisticsToNotificationTransformer.transformToNotification(result, getDeviceInfo(), getOfVersion(), emulatedTxId);
}
}
// convert and inject match
final short version = getVersion();
- final DeviceContext deviceContext = getDeviceContext();
MatchReactor.getInstance().convert(input.getMatch(), version, mprFlowRequestBuilder,
- deviceContext.getPrimaryConnectionContext().getFeatures().getDatapathId());
+ getDeviceInfo().getDatapathId());
// Set request body to main multipart request
multipartRequestFlowCaseBuilder.setMultipartRequestFlow(mprFlowRequestBuilder.build());
@Override
public FlowsStatisticsUpdate transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
- return FlowStatisticsToNotificationTransformer.transformToNotification(result, getDeviceContext().getDeviceState(), getOfVersion(), emulatedTxId);
+ return FlowStatisticsToNotificationTransformer.transformToNotification(result, getDeviceInfo(), getOfVersion(), emulatedTxId);
}
}
@Override
public GroupDescStatsUpdated transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
GroupDescStatsUpdatedBuilder notification = new GroupDescStatsUpdatedBuilder();
- notification.setId(getDeviceContext().getDeviceState().getNodeId());
+ notification.setId(getDeviceInfo().getNodeId());
notification.setMoreReplies(Boolean.FALSE);
notification.setTransactionId(emulatedTxId);
Preconditions.checkArgument(mpSize == 1, "unexpected (!=1) mp-reply size received: {}", mpSize);
GroupFeaturesUpdatedBuilder notification = new GroupFeaturesUpdatedBuilder();
- notification.setId(getDeviceContext().getDeviceState().getNodeId());
+ notification.setId(getDeviceInfo().getNodeId());
notification.setMoreReplies(Boolean.FALSE);
notification.setTransactionId(emulatedTxId);
@Override
public GroupStatisticsUpdated transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
- return GroupStatisticsToNotificationTransformer.transformToNotification(result, getDeviceContext().getDeviceState(), getOfVersion(), emulatedTxId);
+ return GroupStatisticsToNotificationTransformer.transformToNotification(result, getDeviceInfo(), emulatedTxId);
}
}
@Override
protected OfHeader buildRequest(final Xid xid, final GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput input) {
- final DeviceContext deviceContext = getDeviceContext();
final MultipartRequestAggregateCaseBuilder multipartRequestAggregateCaseBuilder = new MultipartRequestAggregateCaseBuilder();
final MultipartRequestAggregateBuilder mprAggregateRequestBuilder = new MultipartRequestAggregateBuilder();
final short tableId = MoreObjects.firstNonNull(input.getTableId(), OFConstants.OFPTT_ALL).shortValue();
Preconditions.checkArgument(mpSize == 1, "unexpected (!=1) mp-reply size received: {}", mpSize);
MeterFeaturesUpdatedBuilder notification = new MeterFeaturesUpdatedBuilder();
- notification.setId(getDeviceContext().getDeviceState().getNodeId());
+ notification.setId(getDeviceInfo().getNodeId());
notification.setMoreReplies(Boolean.FALSE);
notification.setTransactionId(emulatedTxId);
@Override
public MeterStatisticsUpdated transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
- return MeterStatisticsToNotificationTransformer.transformToNotification(result, getDeviceContext().getDeviceState(), getOfVersion(), emulatedTxId);
+ return MeterStatisticsToNotificationTransformer.transformToNotification(result, getDeviceInfo(), getOfVersion(), emulatedTxId);
}
}
@Override
public QueueStatisticsUpdate transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
- return QueueStatisticsToNotificationTransformer.transformToNotification(result, getDeviceContext().getDeviceState(), getOfVersion(), emulatedTxId);
+ return QueueStatisticsToNotificationTransformer.transformToNotification(result, getDeviceInfo(), getOfVersion(), emulatedTxId);
}
}
import java.util.List;
import java.util.concurrent.Future;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
new Function<RpcResult<List<MultipartReply>>, RpcResult<GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput>>() {
@Override
public RpcResult<GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput> apply(final RpcResult<List<MultipartReply>> input) {
- final DeviceContext deviceContext = matchingFlowsInTable.getDeviceContext();
+ final DeviceInfo deviceInfo = matchingFlowsInTable.getDeviceInfo();
final RpcResult<GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput> rpcResult;
if (input.isSuccessful()) {
MultipartReply reply = input.getResult().get(0);
List<AggregatedFlowStatistics> aggregStats = new ArrayList<AggregatedFlowStatistics>();
for (MultipartReply multipartReply : input.getResult()) {
- aggregStats.add(messageTranslator.translate(multipartReply, deviceContext.getDeviceState(), null));
+ aggregStats.add(messageTranslator.translate(multipartReply, deviceInfo, null));
}
GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder getAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder =
@Override
public FlowTableStatisticsUpdate transformToNotification(List<MultipartReply> mpReplyList, TransactionId emulatedTxId) {
FlowTableStatisticsUpdateBuilder notification = new FlowTableStatisticsUpdateBuilder();
- notification.setId(getDeviceContext().getDeviceState().getNodeId());
+ notification.setId(getDeviceInfo().getNodeId());
notification.setMoreReplies(Boolean.FALSE);
notification.setTransactionId(emulatedTxId);
@Override
public NodeConnectorStatisticsUpdate transformToNotification(List<MultipartReply> result, TransactionId emulatedTxId) {
- return NodeConnectorStatisticsToNotificationTransformer.transformToNotification(result, getDeviceContext(), getOfVersion(), emulatedTxId);
+ return NodeConnectorStatisticsToNotificationTransformer.transformToNotification(result, getDeviceInfo(), getOfVersion(), emulatedTxId);
}
}
import com.google.common.base.Preconditions;
import java.util.ArrayList;
import java.util.List;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.FlowStatsResponseConvertor;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowsStatisticsUpdate;
/**
* @param mpResult raw multipart response from device
- * @param deviceState device state
+ * @param deviceInfo device state
* @param ofVersion device version
* @param emulatedTxId
* @return notification containing flow stats
*/
public static FlowsStatisticsUpdate transformToNotification(final List<MultipartReply> mpResult,
- final DeviceState deviceState,
+ final DeviceInfo deviceInfo,
final OpenflowVersion ofVersion,
final TransactionId emulatedTxId) {
final FlowsStatisticsUpdateBuilder notification = new FlowsStatisticsUpdateBuilder();
final List<FlowAndStatisticsMapList> statsList = new ArrayList<>();
- notification.setId(deviceState.getNodeId());
+ notification.setId(deviceInfo.getNodeId());
notification.setFlowAndStatisticsMapList(statsList);
notification.setMoreReplies(Boolean.FALSE);
notification.setTransactionId(emulatedTxId);
MultipartReplyFlow replyBody = caseBody.getMultipartReplyFlow();
List<FlowAndStatisticsMapList> outStatsItem = flowStatsConvertor.toSALFlowStatsList(
replyBody.getFlowStats(),
- deviceState.getFeatures().getDatapathId(),
+ deviceInfo.getDatapathId(),
ofVersion);
statsList.addAll(outStatsItem);
}
import java.util.ArrayList;
import java.util.List;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
-import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.GroupStatsResponseConvertor;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupStatisticsUpdated;
/**
* @param mpReplyList raw multipart response from device
- * @param deviceState device state
- * @param ofVersion device version
+ * @param deviceInfo device state
* @param emulatedTxId
* @return notification containing flow stats
*/
public static GroupStatisticsUpdated transformToNotification(final List<MultipartReply> mpReplyList,
- final DeviceState deviceState,
- final OpenflowVersion ofVersion,
+ final DeviceInfo deviceInfo,
final TransactionId emulatedTxId) {
GroupStatisticsUpdatedBuilder notification = new GroupStatisticsUpdatedBuilder();
- notification.setId(deviceState.getNodeId());
+ notification.setId(deviceInfo.getNodeId());
notification.setMoreReplies(Boolean.FALSE);
notification.setTransactionId(emulatedTxId);
import java.util.ArrayList;
import java.util.List;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.MeterStatsResponseConvertor;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId;
/**
* @param mpReplyList raw multipart response from device
- * @param deviceState device state
+ * @param deviceInfo device state
* @param ofVersion device version
* @param emulatedTxId
* @return notification containing flow stats
*/
public static MeterStatisticsUpdated transformToNotification(final List<MultipartReply> mpReplyList,
- final DeviceState deviceState,
+ final DeviceInfo deviceInfo,
final OpenflowVersion ofVersion,
final TransactionId emulatedTxId) {
MeterStatisticsUpdatedBuilder notification = new MeterStatisticsUpdatedBuilder();
- notification.setId(deviceState.getNodeId());
+ notification.setId(deviceInfo.getNodeId());
notification.setMoreReplies(Boolean.FALSE);
notification.setTransactionId(emulatedTxId);
import com.google.common.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.List;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.Counter32;
/**
* @param mpReplyList raw multipart response from device
- * @param deviceContext device context
+ * @param deviceInfo device basic info
* @param ofVersion device version
* @param emulatedTxId
* @return notification containing flow stats
*/
public static NodeConnectorStatisticsUpdate transformToNotification(final List<MultipartReply> mpReplyList,
- final DeviceContext deviceContext,
+ final DeviceInfo deviceInfo,
final OpenflowVersion ofVersion,
final TransactionId emulatedTxId) {
NodeConnectorStatisticsUpdateBuilder notification = new NodeConnectorStatisticsUpdateBuilder();
- notification.setId(deviceContext.getDeviceState().getNodeId());
+ notification.setId(deviceInfo.getNodeId());
notification.setMoreReplies(Boolean.FALSE);
notification.setTransactionId(emulatedTxId);
MultipartReplyPortStats replyBody = caseBody.getMultipartReplyPortStats();
for (PortStats portStats : replyBody.getPortStats()) {
NodeConnectorStatisticsAndPortNumberMapBuilder statsBuilder =
- processSingleNodeConnectorStats(deviceContext, ofVersion, portStats);
+ processSingleNodeConnectorStats(deviceInfo, ofVersion, portStats);
notification.getNodeConnectorStatisticsAndPortNumberMap().add(statsBuilder.build());
}
}
}
@VisibleForTesting
- static NodeConnectorStatisticsAndPortNumberMapBuilder processSingleNodeConnectorStats(DeviceContext deviceContext, OpenflowVersion ofVersion, PortStats portStats) {
+ static NodeConnectorStatisticsAndPortNumberMapBuilder processSingleNodeConnectorStats(DeviceInfo deviceInfo, OpenflowVersion ofVersion, PortStats portStats) {
NodeConnectorStatisticsAndPortNumberMapBuilder statsBuilder =
new NodeConnectorStatisticsAndPortNumberMapBuilder();
statsBuilder.setNodeConnectorId(
InventoryDataServiceUtil.nodeConnectorIdfromDatapathPortNo(
- deviceContext.getDeviceState().getFeatures().getDatapathId(),
+ deviceInfo.getDatapathId(),
portStats.getPortNo(), ofVersion));
BytesBuilder bytesBuilder = new BytesBuilder();
import java.util.ArrayList;
import java.util.List;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.Counter32;
/**
* @param mpReplyList raw multipart response from device
- * @param deviceState device state
+ * @param deviceInfo device state
* @param ofVersion device version
* @param emulatedTxId
* @return notification containing flow stats
*/
public static QueueStatisticsUpdate transformToNotification(final List<MultipartReply> mpReplyList,
- final DeviceState deviceState,
+ final DeviceInfo deviceInfo,
final OpenflowVersion ofVersion,
final TransactionId emulatedTxId) {
QueueStatisticsUpdateBuilder notification = new QueueStatisticsUpdateBuilder();
- notification.setId(deviceState.getNodeId());
+ notification.setId(deviceInfo.getNodeId());
notification.setMoreReplies(Boolean.FALSE);
notification.setTransactionId(emulatedTxId);
new QueueIdAndStatisticsMapBuilder();
statsBuilder.setNodeConnectorId(
InventoryDataServiceUtil.nodeConnectorIdfromDatapathPortNo(
- deviceState.getFeatures().getDatapathId(),
+ deviceInfo.getDatapathId(),
queueStats.getPortNo(), ofVersion));
statsBuilder.setTransmissionErrors(new Counter64(queueStats.getTxErrors()));
statsBuilder.setTransmittedBytes(new Counter64(queueStats.getTxBytes()));
@Override
public Future<RpcResult<List<MultipartReply>>> getStatisticsOfType(final EventIdentifier eventIdentifier, final MultipartType type) {
- LOG.debug("Getting statistics (onTheFly) for node {} of type {}", getNodeId(), type);
+ LOG.debug("Getting statistics (onTheFly) for node {} of type {}", getDeviceInfo().getNodeId(), type);
EventsTimeCounter.markStart(eventIdentifier);
setEventIdentifier(eventIdentifier);
return handleServiceCall(type);
@Override
public Future<RpcResult<List<MultipartReply>>> getStatisticsOfType(final EventIdentifier eventIdentifier, final MultipartType type) {
- LOG.debug("Getting statistics for node {} of type {}", getNodeId(), type);
+ LOG.debug("Getting statistics for node {} of type {}", getDeviceInfo().getNodeId(), type);
EventsTimeCounter.markStart(eventIdentifier);
setEventIdentifier(eventIdentifier);
return handleServiceCall(type);
import com.google.common.util.concurrent.AsyncFunction;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
+import java.util.List;
+import java.util.concurrent.Future;
+import javax.annotation.Nullable;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
import org.opendaylight.openflowplugin.api.openflow.device.Xid;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import javax.annotation.Nullable;
-import java.util.List;
-import java.util.concurrent.Future;
-
/**
* The abstract direct statistics service.
* This abstract service provides wrappers and tools for all other derived statistics services.
if (input.isSuccessful()) {
storeStatistics(input.getResult());
- getDeviceContext().submitTransaction(); // TODO: If submitTransaction will ever return future, chain it
+ getTxFacade().submitTransaction(); // TODO: If submitTransaction will ever return future, chain it
}
return Futures.immediateFuture(input);
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import java.util.ArrayList;
+import java.util.List;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.flow._case.MultipartRequestFlowBuilder;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import java.util.ArrayList;
-import java.util.List;
-
/**
* The Flow direct statistics service.
*/
@Override
protected void storeStatistics(GetFlowStatisticsOutput output) throws Exception {
- final InstanceIdentifier<FlowCapableNode> nodePath = getDeviceContext()
- .getDeviceState().getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
+ final InstanceIdentifier<FlowCapableNode> nodePath = getDeviceInfo().getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
for (final FlowAndStatisticsMapList flowStatistics : output.getFlowAndStatisticsMapList()) {
final FlowId flowId = generateFlowId(flowStatistics);
.child(Table.class, new TableKey(flowStatistics.getTableId()))
.child(Flow.class, flowKey);
- getDeviceContext().writeToTransactionWithParentsSlow(LogicalDatastoreType.OPERATIONAL, flowStatisticsPath, flowBuilder.build());
+ getTxFacade().writeToTransactionWithParentsSlow(LogicalDatastoreType.OPERATIONAL, flowStatisticsPath, flowBuilder.build());
}
}
final short tableId = flowStatistics.getTableId();
final FlowRegistryKey flowRegistryKey = FlowRegistryKeyFactory.create(flowBuilder.build());
- return getDeviceContext().getDeviceFlowRegistry().storeIfNecessary(flowRegistryKey, tableId);
+ return getDeviceRegistry().getDeviceFlowRegistry().storeIfNecessary(flowRegistryKey, tableId);
}
}
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import java.util.ArrayList;
+import java.util.List;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.group._case.MultipartRequestGroupBuilder;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import java.util.ArrayList;
-import java.util.List;
-
/**
* The Group direct statistics service.
*/
@Override
protected void storeStatistics(GetGroupStatisticsOutput output) throws Exception {
- final InstanceIdentifier<FlowCapableNode> nodePath = getDeviceContext()
- .getDeviceState().getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
+ final InstanceIdentifier<FlowCapableNode> nodePath = getDeviceInfo().getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
for (final GroupStats groupStatistics : output.getGroupStats()) {
final InstanceIdentifier<GroupStatistics> groupStatisticsPath = nodePath
.child(GroupStatistics.class);
final GroupStatistics stats = new GroupStatisticsBuilder(groupStatistics).build();
- getDeviceContext().writeToTransactionWithParentsSlow(LogicalDatastoreType.OPERATIONAL, groupStatisticsPath, stats);
+ getTxFacade().writeToTransactionWithParentsSlow(LogicalDatastoreType.OPERATIONAL, groupStatisticsPath, stats);
}
}
}
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import java.util.ArrayList;
+import java.util.List;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.meter._case.MultipartRequestMeterBuilder;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import java.util.ArrayList;
-import java.util.List;
-
/**
* The Meter direct statistics service.
*/
@Override
protected void storeStatistics(GetMeterStatisticsOutput output) throws Exception {
- final InstanceIdentifier<FlowCapableNode> nodePath = getDeviceContext()
- .getDeviceState().getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
+ final InstanceIdentifier<FlowCapableNode> nodePath = getDeviceInfo().getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
for (final MeterStats meterStatistics : output.getMeterStats()) {
final InstanceIdentifier<MeterStatistics> meterPath = nodePath
.child(MeterStatistics.class);
final MeterStatistics stats = new MeterStatisticsBuilder(meterStatistics).build();
- getDeviceContext().writeToTransactionWithParentsSlow(LogicalDatastoreType.OPERATIONAL, meterPath, stats);
+ getTxFacade().writeToTransactionWithParentsSlow(LogicalDatastoreType.OPERATIONAL, meterPath, stats);
}
}
}
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import java.util.ArrayList;
+import java.util.List;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMapKey;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import java.util.ArrayList;
-import java.util.List;
-
/**
* The Node connector direct statistics service.
*/
@Override
protected void storeStatistics(GetNodeConnectorStatisticsOutput output) throws Exception {
- final InstanceIdentifier<Node> nodePath = getDeviceContext().getDeviceState().getNodeInstanceIdentifier();
+ final InstanceIdentifier<Node> nodePath = getDeviceInfo().getNodeInstanceIdentifier();
for (final NodeConnectorStatisticsAndPortNumberMap nodeConnectorStatistics : output.getNodeConnectorStatisticsAndPortNumberMap()) {
final InstanceIdentifier<FlowCapableNodeConnectorStatistics> nodeConnectorPath = nodePath
.child(FlowCapableNodeConnectorStatistics.class);
final FlowCapableNodeConnectorStatistics stats = new FlowCapableNodeConnectorStatisticsBuilder(nodeConnectorStatistics).build();
- getDeviceContext().writeToTransactionWithParentsSlow(LogicalDatastoreType.OPERATIONAL, nodeConnectorPath, stats);
+ getTxFacade().writeToTransactionWithParentsSlow(LogicalDatastoreType.OPERATIONAL, nodeConnectorPath, stats);
}
}
}
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import java.util.Optional;
+import java.util.concurrent.Future;
import org.opendaylight.yang.gen.v1.urn.opendaylight.direct.statistics.rev160511.GetFlowStatisticsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.direct.statistics.rev160511.GetFlowStatisticsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.direct.statistics.rev160511.GetGroupStatisticsInput;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import java.util.Optional;
-import java.util.concurrent.Future;
-
/**
* The Opendaylight direct statistics service.
* This service handles RPC requests, sends them to registered handlers and returns their replies.
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import java.util.ArrayList;
+import java.util.List;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.queue.id.and.statistics.map.QueueIdAndStatisticsMapBuilder;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import java.util.ArrayList;
-import java.util.List;
-
/**
* The Queue direct statistics service.
*/
@Override
protected void storeStatistics(GetQueueStatisticsOutput output) throws Exception {
- final InstanceIdentifier<Node> nodePath = getDeviceContext().getDeviceState().getNodeInstanceIdentifier();
+ final InstanceIdentifier<Node> nodePath = getDeviceInfo().getNodeInstanceIdentifier();
for (final QueueIdAndStatisticsMap queueStatistics : output.getQueueIdAndStatisticsMap()) {
if (queueStatistics.getQueueId() != null) {
.setQueueId(queueStatistics.getQueueId())
.addAugmentation(FlowCapableNodeConnectorQueueStatisticsData.class, statBuild.build()).build();
- getDeviceContext().writeToTransactionWithParentsSlow(LogicalDatastoreType.OPERATIONAL, queueStatisticsPath, stats);
+ getTxFacade().writeToTransactionWithParentsSlow(LogicalDatastoreType.OPERATIONAL, queueStatisticsPath, stats);
}
}
}
package org.opendaylight.openflowplugin.impl.translator;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.Counter32;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.Counter64;
*/
public class AggregatedFlowStatisticsTranslator implements MessageTranslator<MultipartReply, AggregatedFlowStatistics> {
@Override
- public AggregatedFlowStatistics translate(final MultipartReply input, final DeviceState deviceState, final Object connectionDistinguisher) {
+ public AggregatedFlowStatistics translate(final MultipartReply input, final DeviceInfo deviceInfo, final Object connectionDistinguisher) {
AggregatedFlowStatisticsBuilder aggregatedFlowStatisticsBuilder = new AggregatedFlowStatisticsBuilder();
MultipartReplyAggregateCase caseBody = (MultipartReplyAggregateCase)input.getMultipartReplyBody();
*/
package org.opendaylight.openflowplugin.impl.translator;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.match.MatchConvertorImpl;
public class FlowRemovedTranslator implements MessageTranslator<FlowRemoved, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved> {
@Override
- public org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved translate(FlowRemoved input, DeviceState deviceState, Object connectionDistinguisher) {
+ public org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved translate(FlowRemoved input, DeviceInfo deviceInfo, Object connectionDistinguisher) {
FlowRemovedBuilder flowRemovedBld = new FlowRemovedBuilder()
- .setMatch(translateMatch(input, deviceState).build())
+ .setMatch(translateMatch(input, deviceInfo).build())
.setCookie(new FlowCookie(input.getCookie()))
- .setNode(new NodeRef(deviceState.getNodeInstanceIdentifier()))
+ .setNode(new NodeRef(deviceInfo.getNodeInstanceIdentifier()))
.setPriority(input.getPriority())
.setTableId(translateTableId(input));
return flowRemovedBld.build();
}
- protected MatchBuilder translateMatch(FlowRemoved flowRemoved, DeviceState deviceState) {
+ protected MatchBuilder translateMatch(FlowRemoved flowRemoved, DeviceInfo deviceInfo) {
return MatchConvertorImpl.fromOFMatchToSALMatch(flowRemoved.getMatch(),
- deviceState.getFeatures().getDatapathId(), OpenflowVersion.OF13);
+ deviceInfo.getDatapathId(), OpenflowVersion.OF13);
}
/**
package org.opendaylight.openflowplugin.impl.translator;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.match.MatchConvertorImpl;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
public class FlowRemovedV10Translator extends FlowRemovedTranslator {
@Override
- protected MatchBuilder translateMatch(FlowRemoved flowRemoved, DeviceState deviceState) {
+ protected MatchBuilder translateMatch(FlowRemoved flowRemoved, DeviceInfo deviceInfo) {
return MatchConvertorImpl.fromOFMatchV10ToSALMatch(flowRemoved.getMatchV10(),
- deviceState.getFeatures().getDatapathId(), OpenflowVersion.OF10);
+ deviceInfo.getDatapathId(), OpenflowVersion.OF10);
}
/**
import com.google.common.annotations.VisibleForTesting;
import java.math.BigInteger;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion;
import org.opendaylight.openflowplugin.extension.api.AugmentTuple;
*/
public class PacketReceivedTranslator implements MessageTranslator<PacketInMessage, PacketReceived> {
@Override
- public PacketReceived translate(final PacketInMessage input, final DeviceState deviceState, final Object connectionDistinguisher) {
+ public PacketReceived translate(final PacketInMessage input, final DeviceInfo deviceInfo, final Object connectionDistinguisher) {
PacketReceivedBuilder packetReceivedBuilder = new PacketReceivedBuilder();
- BigInteger datapathId = deviceState.getFeatures().getDatapathId();
+ BigInteger datapathId = deviceInfo.getDatapathId();
// TODO: connection cookie from connection distinguisher
// packetReceivedBuilder.setConnectionCookie(new ConnectionCookie(input.getCookie().longValue()));
}
// Try to create the NodeConnectorRef
- BigInteger dataPathId = deviceState.getFeatures().getDatapathId();
+ BigInteger dataPathId = deviceInfo.getDatapathId();
NodeConnectorRef nodeConnectorRef = NodeConnectorRefToPortTranslator.toNodeConnectorRef(input, dataPathId);
// If we was able to create NodeConnectorRef, use it
import java.util.Collections;
import org.opendaylight.openflowplugin.api.OFConstants;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
import org.opendaylight.openflowplugin.openflow.md.util.PortTranslatorUtil;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
@Override
public FlowCapableNodeConnector translate(final PortGrouping input,
- final DeviceState deviceState, final Object connectionDistinguisher) {
+ final DeviceInfo deviceInfo, final Object connectionDistinguisher) {
final FlowCapableNodeConnectorBuilder builder = new FlowCapableNodeConnectorBuilder();
//OF1.0
- if (deviceState.getVersion() == OFConstants.OFP_VERSION_1_0) {
+ if (deviceInfo.getVersion() == OFConstants.OFP_VERSION_1_0) {
builder.setAdvertisedFeatures(PortTranslatorUtil.translatePortFeatures(input.getAdvertisedFeaturesV10()));
builder.setConfiguration(PortTranslatorUtil.translatePortConfig(input.getConfigV10()));
builder.setCurrentFeature(PortTranslatorUtil.translatePortFeatures(input.getCurrentFeaturesV10()));
builder.setPeerFeatures(PortTranslatorUtil.translatePortFeatures(input.getPeerFeaturesV10()));
builder.setState(PortTranslatorUtil.translatePortState(input.getStateV10()));
builder.setSupported(PortTranslatorUtil.translatePortFeatures(input.getSupportedFeaturesV10()));
- } else if (deviceState.getVersion() == OFConstants.OFP_VERSION_1_3) {
+ } else if (deviceInfo.getVersion() == OFConstants.OFP_VERSION_1_3) {
builder.setAdvertisedFeatures(PortTranslatorUtil.translatePortFeatures(input.getAdvertisedFeatures()));
builder.setConfiguration(PortTranslatorUtil.translatePortConfig(input.getConfig()));
builder.setCurrentFeature(PortTranslatorUtil.translatePortFeatures(input.getCurrentFeatures()));
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
public static ListenableFuture<Void> initializeNodeInformation(final DeviceContext deviceContext, final boolean switchFeaturesMandatory) {
Preconditions.checkArgument(deviceContext != null);
final DeviceState deviceState = Preconditions.checkNotNull(deviceContext.getDeviceState());
+ final DeviceInfo deviceInfo = deviceContext.getDeviceInfo();
final ConnectionContext connectionContext = Preconditions.checkNotNull(deviceContext.getPrimaryConnectionContext());
- final short version = deviceState.getVersion();
- LOG.trace("initalizeNodeInformation for node {}", deviceState.getNodeId());
+ final short version = deviceInfo.getVersion();
+ LOG.trace("initalizeNodeInformation for node {}", deviceInfo.getNodeId());
final SettableFuture<Void> returnFuture = SettableFuture.<Void>create();
addNodeToOperDS(deviceContext, returnFuture);
final ListenableFuture<List<RpcResult<List<MultipartReply>>>> deviceFeaturesFuture;
// create empty tables after device description is processed
chainTableTrunkWriteOF10(deviceContext, deviceFeaturesFuture);
- final short ofVersion = deviceContext.getDeviceState().getVersion();
+ final short ofVersion = deviceInfo.getVersion();
final TranslatorKey translatorKey = new TranslatorKey(ofVersion, PortGrouping.class.getName());
final MessageTranslator<PortGrouping, FlowCapableNodeConnector> translator = deviceContext.oook()
.lookupTranslator(translatorKey);
- final BigInteger dataPathId = deviceContext.getPrimaryConnectionContext().getFeatures().getDatapathId();
+ final BigInteger dataPathId = deviceContext.getDeviceInfo().getDatapathId();
for (final PortGrouping port : connectionContext.getFeatures().getPhyPort()) {
- final FlowCapableNodeConnector fcNodeConnector = translator.translate(port, deviceContext.getDeviceState(), null);
+ final FlowCapableNodeConnector fcNodeConnector = translator.translate(port, deviceContext.getDeviceInfo(), null);
final NodeConnectorId nodeConnectorId = NodeStaticReplyTranslatorUtil.nodeConnectorId(
dataPathId.toString(), port.getPortNo(), ofVersion);
ncBuilder.addAugmentation(FlowCapableNodeConnectorStatisticsData.class,
new FlowCapableNodeConnectorStatisticsDataBuilder().build());
final NodeConnector connector = ncBuilder.build();
- final InstanceIdentifier<NodeConnector> connectorII = deviceState.getNodeInstanceIdentifier().child(
+ final InstanceIdentifier<NodeConnector> connectorII = deviceInfo.getNodeInstanceIdentifier().child(
NodeConnector.class, connector.getKey());
try {
deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, connectorII, connector);
} catch (final Exception e) {
- LOG.debug("Failed to write node {} to DS ", deviceContext.getDeviceState().getNodeId().toString(),
+ LOG.debug("Failed to write node {} to DS ", deviceInfo.getNodeId().toString(),
e);
}
}
} else if (OFConstants.OFP_VERSION_1_3 == version) {
final Capabilities capabilities = connectionContext.getFeatures().getCapabilities();
- LOG.debug("Setting capabilities for device {}", deviceContext.getDeviceState().getNodeId());
+ LOG.debug("Setting capabilities for device {}", deviceInfo.getNodeId());
DeviceStateUtil.setDeviceStateBasedOnV13Capabilities(deviceState, capabilities);
deviceFeaturesFuture = createDeviceFeaturesForOF13(deviceContext, deviceState, switchFeaturesMandatory);
} else {
Futures.addCallback(deviceFeaturesFuture, new FutureCallback<List<RpcResult<List<MultipartReply>>>>() {
@Override
public void onSuccess(final List<RpcResult<List<MultipartReply>>> result) {
- LOG.debug("All init data for node {} is in submited.", deviceState.getNodeId());
+ LOG.debug("All init data for node {} is in submited.", deviceInfo.getNodeId());
returnFuture.set(null);
}
// FIXME : remove session
LOG.trace("Device capabilities gathering future failed.");
LOG.trace("more info in exploration failure..", t);
- LOG.debug("All init data for node {} was not submited correctly - connection has to go down.", deviceState.getNodeId());
+ LOG.debug("All init data for node {} was not submited correctly - connection has to go down.", deviceInfo.getNodeId());
returnFuture.setException(t);
}
});
private static void addNodeToOperDS(final DeviceContext deviceContext, final SettableFuture<Void> future) {
Preconditions.checkArgument(deviceContext != null);
final DeviceState deviceState = deviceContext.getDeviceState();
- final NodeBuilder nodeBuilder = new NodeBuilder().setId(deviceState.getNodeId()).setNodeConnector(
+ final NodeBuilder nodeBuilder = new NodeBuilder().setId(deviceContext.getDeviceInfo().getNodeId()).setNodeConnector(
Collections.<NodeConnector>emptyList());
try {
- deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, deviceState.getNodeInstanceIdentifier(),
+ deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, deviceContext.getDeviceInfo().getNodeInstanceIdentifier(),
nodeBuilder.build());
} catch (final Exception e) {
- LOG.warn("Failed to write node {} to DS ", deviceState.getNodeId(), e);
+ LOG.warn("Failed to write node {} to DS ", deviceContext.getDeviceInfo().getNodeId(), e);
future.cancel(true);
}
}
private static ListenableFuture<List<RpcResult<List<MultipartReply>>>> createDeviceFeaturesForOF10(
final DeviceContext deviceContext, final DeviceState deviceState) {
final ListenableFuture<RpcResult<List<MultipartReply>>> replyDesc = getNodeStaticInfo(MultipartType.OFPMPDESC,
- deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
+ deviceContext, deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), deviceContext.getDeviceInfo().getVersion());
return Futures.allAsList(Arrays.asList(replyDesc));
}
final DeviceContext deviceContext, final DeviceState deviceState, final boolean switchFeaturesMandatory) {
final ListenableFuture<RpcResult<List<MultipartReply>>> replyDesc = getNodeStaticInfo(MultipartType.OFPMPDESC,
- deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
+ deviceContext, deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), deviceContext.getDeviceInfo().getVersion());
//first process description reply, write data to DS and write consequent data if successful
return Futures.transform(replyDesc,
final RpcResult<List<MultipartReply>> rpcResult) throws Exception {
translateAndWriteReply(MultipartType.OFPMPDESC, deviceContext,
- deviceState.getNodeInstanceIdentifier(), rpcResult.getResult());
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), rpcResult.getResult());
final ListenableFuture<RpcResult<List<MultipartReply>>> replyMeterFeature = getNodeStaticInfo(
MultipartType.OFPMPMETERFEATURES, deviceContext,
- deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), deviceContext.getDeviceInfo().getVersion());
createSuccessProcessingCallback(MultipartType.OFPMPMETERFEATURES, deviceContext,
- deviceState.getNodeInstanceIdentifier(), replyMeterFeature);
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), replyMeterFeature);
final ListenableFuture<RpcResult<List<MultipartReply>>> replyGroupFeatures = getNodeStaticInfo(
MultipartType.OFPMPGROUPFEATURES, deviceContext,
- deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), deviceContext.getDeviceInfo().getVersion());
createSuccessProcessingCallback(MultipartType.OFPMPGROUPFEATURES, deviceContext,
- deviceState.getNodeInstanceIdentifier(), replyGroupFeatures);
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), replyGroupFeatures);
final ListenableFuture<RpcResult<List<MultipartReply>>> replyTableFeatures = getNodeStaticInfo(
MultipartType.OFPMPTABLEFEATURES, deviceContext,
- deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), deviceContext.getDeviceInfo().getVersion());
createSuccessProcessingCallback(MultipartType.OFPMPTABLEFEATURES, deviceContext,
- deviceState.getNodeInstanceIdentifier(), replyTableFeatures);
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), replyTableFeatures);
final ListenableFuture<RpcResult<List<MultipartReply>>> replyPortDescription = getNodeStaticInfo(
- MultipartType.OFPMPPORTDESC, deviceContext, deviceState.getNodeInstanceIdentifier(),
- deviceState.getVersion());
+ MultipartType.OFPMPPORTDESC, deviceContext, deviceContext.getDeviceInfo().getNodeInstanceIdentifier(),
+ deviceContext.getDeviceInfo().getVersion());
createSuccessProcessingCallback(MultipartType.OFPMPPORTDESC, deviceContext,
- deviceState.getNodeInstanceIdentifier(), replyPortDescription);
+ deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), replyPortDescription);
if (switchFeaturesMandatory) {
return Futures.allAsList(Arrays.asList(replyMeterFeature, replyGroupFeatures,
replyTableFeatures, replyPortDescription));
final MultipartReplyPortDesc portDesc = ((MultipartReplyPortDescCase) body)
.getMultipartReplyPortDesc();
for (final PortGrouping port : portDesc.getPorts()) {
- final short ofVersion = dContext.getDeviceState().getVersion();
+ final short ofVersion = dContext.getDeviceInfo().getVersion();
final TranslatorKey translatorKey = new TranslatorKey(ofVersion, PortGrouping.class.getName());
final MessageTranslator<PortGrouping, FlowCapableNodeConnector> translator = dContext.oook()
.lookupTranslator(translatorKey);
- final FlowCapableNodeConnector fcNodeConnector = translator.translate(port, dContext.getDeviceState(), null);
+ final FlowCapableNodeConnector fcNodeConnector = translator.translate(port, dContext.getDeviceInfo(), null);
final BigInteger dataPathId = dContext.getPrimaryConnectionContext().getFeatures()
.getDatapathId();
}
}
} catch (final Exception e) {
- LOG.debug("Failed to write node {} to DS ", dContext.getDeviceState().getNodeId().toString(), e);
+ LOG.debug("Failed to write node {} to DS ", dContext.getDeviceInfo().getNodeId().toString(), e);
}
}
private static void createEmptyFlowCapableNodeInDs(final DeviceContext deviceContext) {
final FlowCapableNodeBuilder flowCapableNodeBuilder = new FlowCapableNodeBuilder();
- final InstanceIdentifier<FlowCapableNode> fNodeII = deviceContext.getDeviceState().getNodeInstanceIdentifier()
+ final InstanceIdentifier<FlowCapableNode> fNodeII = deviceContext.getDeviceInfo().getNodeInstanceIdentifier()
.augmentation(FlowCapableNode.class);
try {
deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, fNodeII, flowCapableNodeBuilder.build());
} catch (final Exception e) {
- LOG.debug("Failed to write node {} to DS ", deviceContext.getDeviceState().getNodeId().toString(), e);
+ LOG.debug("Failed to write node {} to DS ", deviceContext.getDeviceInfo().getNodeId().toString(), e);
}
}
if (remoteAddress == null) {
LOG.warn("IP address of the node {} cannot be obtained. No connection with switch.", deviceContext
- .getDeviceState().getNodeId());
+ .getDeviceInfo().getNodeId());
return null;
}
LOG.info("IP address of switch is: {}", remoteAddress);
try {
dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, tableBuilder.build());
} catch (final Exception e) {
- LOG.debug("Failed to write node {} to DS ", dContext.getDeviceState().getNodeId().toString(), e);
+ LOG.debug("Failed to write node {} to DS ", dContext.getDeviceInfo().getNodeId().toString(), e);
}
}
public void onSuccess(final RpcResult<List<MultipartReply>> rpcResult) {
final List<MultipartReply> result = rpcResult.getResult();
if (result != null) {
- LOG.info("Static node {} info: {} collected", deviceContext.getDeviceState().getNodeId(), type);
+ LOG.info("Static node {} info: {} collected", deviceContext.getDeviceInfo().getNodeId(), type);
translateAndWriteReply(type, deviceContext, nodeII, result);
} else {
final Iterator<RpcError> rpcErrorIterator = rpcResult.getErrors().iterator();
}
if (allSucceeded) {
createEmptyFlowCapableNodeInDs(deviceContext);
- makeEmptyTables(deviceContext, deviceContext.getDeviceState().getNodeInstanceIdentifier(),
- deviceContext.getDeviceState().getFeatures().getTables());
+ makeEmptyTables(deviceContext, deviceContext.getDeviceInfo().getNodeInstanceIdentifier(),
+ deviceContext.getPrimaryConnectionContext().getFeatures().getTables());
}
}
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
import org.opendaylight.openflowplugin.api.openflow.statistics.compatibility.Delegator;
+import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
import org.opendaylight.openflowplugin.impl.services.FlowCapableTransactionServiceImpl;
import org.opendaylight.openflowplugin.impl.services.NodeConfigServiceImpl;
import org.opendaylight.openflowplugin.impl.services.PacketProcessingServiceImpl;
* @param newRole - role validation for {@link OfpRole#BECOMEMASTER}
*/
public static void registerMasterServices(@CheckForNull final RpcContext rpcContext,
- @CheckForNull final DeviceContext deviceContext, @CheckForNull final OfpRole newRole) {
+ @CheckForNull final DeviceContext deviceContext,
+ @CheckForNull final OfpRole newRole,
+ final ExtensionConverterProvider extensionConverterProvider) {
Preconditions.checkArgument(rpcContext != null);
Preconditions.checkArgument(deviceContext != null);
Preconditions.checkArgument(newRole != null);
rpcContext.registerRpcServiceImplementation(SalFlatBatchService.class, salFlatBatchService);
// TODO: experimenter symmetric and multipart message services
- rpcContext.registerRpcServiceImplementation(SalExperimenterMessageService.class, new SalExperimenterMessageServiceImpl(rpcContext, deviceContext));
+ rpcContext.registerRpcServiceImplementation(SalExperimenterMessageService.class,
+ new SalExperimenterMessageServiceImpl(rpcContext, deviceContext, extensionConverterProvider));
}
/**
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import com.google.common.util.concurrent.ListenableFuture;
import io.netty.util.HashedWheelTimer;
import io.netty.util.TimerTask;
+import java.math.BigInteger;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
+import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.ServiceChangeListener;
+import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
+import org.opendaylight.openflowplugin.api.openflow.rpc.RpcManager;
import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
@Mock
private ServiceChangeListener serviceChangeListener;
@Mock
- private ConcurrentHashMap<NodeId, ServiceChangeListener> serviceChangeListeners;
+ private ConcurrentHashMap<DeviceInfo, ServiceChangeListener> serviceChangeListeners;
@Mock
private DeviceContext deviceContext;
@Mock
private ListenableFuture<Void> listenableFuture;
@Mock
private StatisticsManager statisticsManager;
+ @Mock
+ private RpcManager rpcManager;
+ @Mock
+ private RpcContext rpcContext;
+ @Mock
+ private DeviceInfo deviceInfo;
private NodeId nodeId = new NodeId("openflow-junit:1");
private OfpRole ofpRole = OfpRole.NOCHANGE;
@Before
public void setUp() {
- when(deviceManager.getDeviceContextFromNodeId(nodeId)).thenReturn(deviceContext);
- when(deviceContext.getPrimaryConnectionContext()).thenReturn(connectionContext);
lifecycleConductor = new LifecycleConductorImpl(messageIntelligenceAgency);
- lifecycleConductor.setSafelyDeviceManager(deviceManager);
- lifecycleConductor.setSafelyStatisticsManager(statisticsManager);
+ lifecycleConductor.setSafelyManager(deviceManager);
+ lifecycleConductor.setSafelyManager(statisticsManager);
+ lifecycleConductor.setSafelyManager(rpcManager);
- when(connectionContext.getFeatures()).thenReturn(featuresReply);
+ when(deviceManager.gainContext(Mockito.<DeviceInfo>any())).thenReturn(deviceContext);
+ when(deviceContext.getPrimaryConnectionContext()).thenReturn(connectionContext);
+ when(deviceContext.getDeviceInfo()).thenReturn(deviceInfo);
+ when(rpcManager.gainContext(Mockito.<DeviceInfo>any())).thenReturn(rpcContext);
+ when(deviceInfo.getNodeId()).thenReturn(nodeId);
+ when(deviceInfo.getDatapathId()).thenReturn(BigInteger.TEN);
+ when(deviceContext.getDeviceInfo()).thenReturn(deviceInfo);
+ when(rpcManager.gainContext(Mockito.<DeviceInfo>any())).thenReturn(rpcContext);
}
@Test
public void addOneTimeListenerWhenServicesChangesDoneTest() {
- lifecycleConductor.addOneTimeListenerWhenServicesChangesDone(serviceChangeListener, nodeId);
+ lifecycleConductor.addOneTimeListenerWhenServicesChangesDone(serviceChangeListener, deviceInfo);
assertEquals(false,lifecycleConductor.isServiceChangeListenersEmpty());
}
*/
@Test
public void notifyServiceChangeListenersTest1() {
- lifecycleConductor.notifyServiceChangeListeners(nodeId,true);
+ lifecycleConductor.notifyServiceChangeListeners(deviceInfo,true);
when(serviceChangeListeners.size()).thenReturn(0);
- verify(serviceChangeListeners,times(0)).remove(nodeId);
+ verify(serviceChangeListeners,times(0)).remove(deviceInfo);
}
/**
*/
@Test
public void notifyServiceChangeListenersTest2() {
- lifecycleConductor.addOneTimeListenerWhenServicesChangesDone(serviceChangeListener, nodeId);
+ lifecycleConductor.addOneTimeListenerWhenServicesChangesDone(serviceChangeListener, deviceInfo);
assertEquals(false,lifecycleConductor.isServiceChangeListenersEmpty());
- lifecycleConductor.notifyServiceChangeListeners(nodeId,true);
+ lifecycleConductor.notifyServiceChangeListeners(deviceInfo,true);
assertEquals(true,lifecycleConductor.isServiceChangeListenersEmpty());
}
*/
@Test
public void roleInitializationDoneTest1() {
- lifecycleConductor.addOneTimeListenerWhenServicesChangesDone(serviceChangeListener, nodeId);
- lifecycleConductor.roleInitializationDone(nodeId,false);
+ lifecycleConductor.addOneTimeListenerWhenServicesChangesDone(serviceChangeListener, deviceInfo);
+ lifecycleConductor.roleInitializationDone(deviceInfo,false);
verify(deviceContext,times(1)).shutdownConnection();
}
*/
@Test
public void roleInitializationDoneTest2() {
- lifecycleConductor.addOneTimeListenerWhenServicesChangesDone(serviceChangeListener, nodeId);
- lifecycleConductor.roleInitializationDone(nodeId,true);
+ lifecycleConductor.addOneTimeListenerWhenServicesChangesDone(serviceChangeListener, deviceInfo);
+ lifecycleConductor.roleInitializationDone(deviceInfo,true);
verify(deviceContext,times(0)).shutdownConnection();
}
*/
@Test
public void roleChangeOnDeviceTest1() {
- when(deviceManager.getDeviceContextFromNodeId(nodeId)).thenReturn(null);
- lifecycleConductor.roleChangeOnDevice(nodeId,true,ofpRole,false);
+ when(deviceManager.gainContext(deviceInfo)).thenReturn(null);
+ lifecycleConductor.roleChangeOnDevice(deviceInfo,true,ofpRole,false);
verify(deviceContext,times(0)).shutdownConnection();
- lifecycleConductor.roleChangeOnDevice(nodeId,false,ofpRole,false);
+ lifecycleConductor.roleChangeOnDevice(deviceInfo,false,ofpRole,false);
verify(deviceContext,times(0)).shutdownConnection();
}
*/
@Test
public void roleChangeOnDeviceTest2() {
- when(deviceManager.getDeviceContextFromNodeId(nodeId)).thenReturn(deviceContext);
- lifecycleConductor.roleChangeOnDevice(nodeId,false,ofpRole,false);
+ when(deviceManager.gainContext(deviceInfo)).thenReturn(deviceContext);
+ lifecycleConductor.roleChangeOnDevice(deviceInfo,false,ofpRole,false);
verify(deviceContext,times(1)).shutdownConnection();
}
*/
@Test
public void roleChangeOnDeviceTest3() {
- when(deviceManager.getDeviceContextFromNodeId(nodeId)).thenReturn(deviceContext);
- lifecycleConductor.roleChangeOnDevice(nodeId,true,ofpRole,true);
+ when(deviceManager.gainContext(deviceInfo)).thenReturn(deviceContext);
+ lifecycleConductor.roleChangeOnDevice(deviceInfo,true,ofpRole,true);
verify(deviceContext,times(0)).shutdownConnection();
}
@Test
public void roleChangeOnDeviceTest4() {
when(deviceContext.getDeviceState()).thenReturn(deviceState);
- when(deviceManager.getDeviceContextFromNodeId(nodeId)).thenReturn(deviceContext);
- when(deviceContext.onClusterRoleChange(null, OfpRole.BECOMEMASTER)).thenReturn(listenableFuture);
- lifecycleConductor.roleChangeOnDevice(nodeId,true,OfpRole.BECOMEMASTER,false);
- verify(statisticsManager).startScheduling(nodeId);
+ when(deviceManager.gainContext(deviceInfo)).thenReturn(deviceContext);
+ when(deviceManager.onClusterRoleChange(deviceInfo, OfpRole.BECOMEMASTER)).thenReturn(listenableFuture);
+ lifecycleConductor.roleChangeOnDevice(deviceInfo,true,OfpRole.BECOMEMASTER,false);
+ verify(statisticsManager).startScheduling(Mockito.<DeviceInfo>any());
}
/**
@Test
public void roleChangeOnDeviceTest5() {
when(deviceContext.getDeviceState()).thenReturn(deviceState);
- when(deviceManager.getDeviceContextFromNodeId(nodeId)).thenReturn(deviceContext);
- when(deviceContext.onClusterRoleChange(null, OfpRole.BECOMESLAVE)).thenReturn(listenableFuture);
- lifecycleConductor.roleChangeOnDevice(nodeId,true,OfpRole.BECOMESLAVE,false);
- verify(statisticsManager).stopScheduling(nodeId);
- }
-
- /**
- * If getDeviceContext returns null nothing should happen
- */
- @Test
- public void gainVersionSafelyTest1() {
- when(deviceManager.getDeviceContextFromNodeId(nodeId)).thenReturn(null);
- assertNull(lifecycleConductor.gainVersionSafely(nodeId));
- }
-
- /**
- * If getDeviceContext returns deviceContext getPrimaryConnectionContext() should be called
- */
- @Test
- public void gainVersionSafelyTest2() {
- when(deviceManager.getDeviceContextFromNodeId(nodeId)).thenReturn(deviceContext);
- lifecycleConductor.gainVersionSafely(nodeId);
- verify(deviceContext,times(1)).getPrimaryConnectionContext();
+ when(deviceManager.gainContext(deviceInfo)).thenReturn(deviceContext);
+ when(deviceManager.onClusterRoleChange(deviceInfo, OfpRole.BECOMESLAVE)).thenReturn(listenableFuture);
+ lifecycleConductor.roleChangeOnDevice(deviceInfo,true,OfpRole.BECOMESLAVE,false);
+ verify(statisticsManager).stopScheduling(Mockito.<DeviceInfo>any());
}
/**
*/
@Test
public void gainConnectionStateSafelyTest1() {
- when(deviceManager.getDeviceContextFromNodeId(nodeId)).thenReturn(null);
- assertNull(lifecycleConductor.gainConnectionStateSafely(nodeId));
+ when(deviceManager.gainContext(deviceInfo)).thenReturn(null);
+ assertNull(lifecycleConductor.gainConnectionStateSafely(deviceInfo));
}
/**
*/
@Test
public void gainConnectionStateSafelyTest2() {
- when(deviceManager.getDeviceContextFromNodeId(nodeId)).thenReturn(deviceContext);
- lifecycleConductor.gainConnectionStateSafely(nodeId);
+ lifecycleConductor.gainConnectionStateSafely(deviceInfo);
verify(deviceContext,times(1)).getPrimaryConnectionContext();
}
*/
@Test
public void reserveXidForDeviceMessageTest1() {
- when(deviceManager.getDeviceContextFromNodeId(nodeId)).thenReturn(null);
- assertNull(lifecycleConductor.reserveXidForDeviceMessage(nodeId));
+ when(deviceManager.gainContext(deviceInfo)).thenReturn(null);
+ assertNull(lifecycleConductor.reserveXidForDeviceMessage(deviceInfo));
}
/**
*/
@Test
public void reserveXidForDeviceMessageTest2() {
- when(deviceManager.getDeviceContextFromNodeId(nodeId)).thenReturn(deviceContext);
- lifecycleConductor.reserveXidForDeviceMessage(nodeId);
+ lifecycleConductor.reserveXidForDeviceMessage(deviceInfo);
verify(deviceContext,times(1)).reserveXidForDeviceMessage();
}
*/
@Test
public void deviceStartInitializationDoneTest() {
- lifecycleConductor.deviceStartInitializationDone(nodeId, false);
+ lifecycleConductor.deviceStartInitializationDone(deviceInfo, false);
verify(deviceContext,times(1)).shutdownConnection();
}
*/
@Test
public void deviceInitializationDoneTest() {
- lifecycleConductor.deviceInitializationDone(nodeId, false);
+ lifecycleConductor.deviceInitializationDone(deviceInfo, false);
verify(deviceContext,times(1)).shutdownConnection();
}
}
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import org.junit.After;
private static final long RPC_REQUESTS_QUOTA = 500;
private static final long GLOBAL_NOTIFICATION_QUOTA = 131072;
+ private static final int THREAD_POOL_MIN_THREADS = 1;
+ private static final int THREAD_POOL_MAX_THREADS = 32000;
+ private static final long THREAD_POOL_TIMEOUT = 60;
private OpenFlowPluginProviderImpl provider;
when(rpcProviderRegistry.addRpcImplementation(eq(StatisticsManagerControlService.class), any())).thenReturn(controlServiceRegistration);
when(switchConnectionProvider.startup()).thenReturn(Futures.immediateCheckedFuture(null));
- provider = new OpenFlowPluginProviderImpl(RPC_REQUESTS_QUOTA, GLOBAL_NOTIFICATION_QUOTA);
+ provider = new OpenFlowPluginProviderImpl(
+ RPC_REQUESTS_QUOTA,
+ GLOBAL_NOTIFICATION_QUOTA,
+ THREAD_POOL_MIN_THREADS,
+ THREAD_POOL_MAX_THREADS,
+ THREAD_POOL_TIMEOUT);
+
provider.setDataBroker(dataBroker);
provider.setRpcProviderRegistry(rpcProviderRegistry);
provider.setNotificationProviderService(notificationService);
import com.google.common.util.concurrent.SettableFuture;
import java.math.BigInteger;
+import java.net.InetAddress;
import java.net.InetSocketAddress;
+import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.TimeUnit;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceConnectedHandler;
+import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput;
*/
@Before
public void setUp() {
- connectionManagerImpl = new ConnectionManagerImpl(ECHO_REPLY_TIMEOUT);
+ final ThreadPoolLoggingExecutor threadPool = new ThreadPoolLoggingExecutor(0, Integer.MAX_VALUE,
+ 60L, TimeUnit.SECONDS,
+ new SynchronousQueue<>(), "ofppool");
+
+ connectionManagerImpl = new ConnectionManagerImpl(ECHO_REPLY_TIMEOUT, threadPool);
connectionManagerImpl.setDeviceConnectedHandler(deviceConnectedHandler);
final InetSocketAddress deviceAddress = InetSocketAddress.createUnresolved("yahoo", 42);
Mockito.when(connection.getRemoteAddress()).thenReturn(deviceAddress);
package org.opendaylight.openflowplugin.impl.connection;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
import junit.framework.TestCase;
import org.junit.Test;
import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
public class OutboundQueueProviderImplTest extends TestCase {
private static final Long DUMMY_ENTRY_NUMBER = 44L;
connectionContextSpy = Mockito.spy(new ConnectionContextImpl(connectionAdapter));
Mockito.when(connectionContextSpy.getConnectionAdapter()).thenReturn(connectionAdapter);
Mockito.when(features.getDatapathId()).thenReturn(BigInteger.TEN);
+ Mockito.doNothing().when(connectionContextSpy).handshakeSuccessful();
handshakeListener = new HandshakeListenerImpl(connectionContextSpy, deviceConnectedHandler);
handshakeListener.setHandshakeContext(handshakeContext);
}
Mockito.verify(connectionContextSpy).changeStateToWorking();
Mockito.verify(connectionContextSpy).setFeatures(Matchers.any(FeaturesReply.class));
Mockito.verify(connectionContextSpy).setNodeId(nodeIdCaptor.capture());
+ Mockito.verify(connectionContextSpy).handshakeSuccessful();
Mockito.verify(deviceConnectedHandler).deviceConnected(connectionContextSpy);
Mockito.verify(handshakeContext).close();
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
import java.net.InetSocketAddress;
+import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.TimeUnit;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.impl.connection.ConnectionContextImpl;
+import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput;
Mockito.when(connectionContext.getConnectionAdapter()).thenReturn(connectionAdapter);
Mockito.when(connectionContext.getFeatures()).thenReturn(features);
- systemNotificationsListener = new SystemNotificationsListenerImpl(connectionContext, ECHO_REPLY_TIMEOUT);
+ final ThreadPoolLoggingExecutor threadPool = new ThreadPoolLoggingExecutor(0, Integer.MAX_VALUE,
+ 60L, TimeUnit.SECONDS,
+ new SynchronousQueue<>(), "opfpool");
+
+ systemNotificationsListener = new SystemNotificationsListenerImpl(connectionContext, ECHO_REPLY_TIMEOUT, threadPool);
}
@After
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicLong;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
-import org.mockito.stubbing.Answer;
import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
-import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
-import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
import org.opendaylight.openflowplugin.extension.api.ConvertorMessageFromOFJava;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemovedBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
-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.Nodes;
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.openflow.common.types.rev130731.Capabilities;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.*;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.Error;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessageBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessageBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncReply;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketIn;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.experimenter.core.ExperimenterDataOfChoice;
import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
private static final BigInteger DUMMY_DATAPATH_ID = new BigInteger("55");
Xid xid;
Xid xidMulti;
- DeviceContextImpl deviceContext;
+
+ DeviceContext deviceContext;
@Mock
TransactionChainManager txChainManager;
@Mock
RequestContext<GetAsyncReply> requestContext;
@Mock
RequestContext<MultipartReply> requestContextMultiReply;
-
@Mock
ConnectionContext connectionContext;
@Mock
private MessageTranslator<Object, Object> messageTranslatorFlowRemoved;
@Mock
private LifecycleConductor lifecycleConductor;
+ @Mock
+ private DeviceInfo deviceInfo;
private InOrder inOrderDevState;
private DeviceContext deviceContextSpy;
@Before
- public void setUp() {
+ public void setUp() throws Exception{
final CheckedFuture<Optional<Node>, ReadFailedException> noExistNodeFuture = Futures.immediateCheckedFuture(Optional.<Node>absent());
Mockito.when(rTx.read(LogicalDatastoreType.OPERATIONAL, nodeKeyIdent)).thenReturn(noExistNodeFuture);
Mockito.when(dataBroker.newReadOnlyTransaction()).thenReturn(rTx);
Mockito.when(dataBroker.createTransactionChain(Mockito.any(TransactionChainManager.class))).thenReturn(txChainFactory);
- Mockito.when(deviceState.getNodeInstanceIdentifier()).thenReturn(nodeKeyIdent);
- Mockito.when(deviceState.getNodeId()).thenReturn(nodeId);
-// txChainManager = new TransactionChainManager(dataBroker, deviceState);
+ Mockito.when(deviceInfo.getNodeInstanceIdentifier()).thenReturn(nodeKeyIdent);
+ Mockito.when(deviceInfo.getNodeId()).thenReturn(nodeId);
+ Mockito.when(deviceInfo.getDatapathId()).thenReturn(BigInteger.ONE);
final SettableFuture<RpcResult<GetAsyncReply>> settableFuture = SettableFuture.create();
final SettableFuture<RpcResult<MultipartReply>> settableFutureMultiReply = SettableFuture.create();
Mockito.when(requestContext.getFuture()).thenReturn(settableFuture);
- Mockito.doAnswer(new Answer<Object>() {
- @SuppressWarnings("unchecked")
- @Override
- public Object answer(final InvocationOnMock invocation) {
- settableFuture.set((RpcResult<GetAsyncReply>) invocation.getArguments()[0]);
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ settableFuture.set((RpcResult<GetAsyncReply>) invocation.getArguments()[0]);
+ return null;
}).when(requestContext).setResult(any(RpcResult.class));
Mockito.when(requestContextMultiReply.getFuture()).thenReturn(settableFutureMultiReply);
- Mockito.doAnswer(new Answer<Object>() {
- @SuppressWarnings("unchecked")
- @Override
- public Object answer(final InvocationOnMock invocation) {
- settableFutureMultiReply.set((RpcResult<MultipartReply>) invocation.getArguments()[0]);
- return null;
- }
+ Mockito.doAnswer(invocation -> {
+ settableFutureMultiReply.set((RpcResult<MultipartReply>) invocation.getArguments()[0]);
+ return null;
}).when(requestContextMultiReply).setResult(any(RpcResult.class));
Mockito.when(txChainFactory.newWriteOnlyTransaction()).thenReturn(wTx);
Mockito.when(dataBroker.newReadOnlyTransaction()).thenReturn(rTx);
Mockito.when(connectionContext.getOutboundQueueProvider()).thenReturn(outboundQueueProvider);
Mockito.when(connectionContext.getConnectionAdapter()).thenReturn(connectionAdapter);
+ Mockito.when(connectionContext.getDeviceInfo()).thenReturn(deviceInfo);
final FeaturesReply mockedFeaturesReply = mock(FeaturesReply.class);
when(connectionContext.getFeatures()).thenReturn(mockedFeaturesReply);
when(connectionContext.getFeatures().getCapabilities()).thenReturn(mock(Capabilities.class));
- Mockito.when(deviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
+ Mockito.when(deviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
Mockito.when(featuresOutput.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
Mockito.when(featuresOutput.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
- Mockito.when(deviceState.getFeatures()).thenReturn(featuresOutput);
- Mockito.when(messageTranslatorPacketReceived.translate(any(Object.class), any(DeviceState.class), any(Object.class))).thenReturn(mock(PacketReceived.class));
- Mockito.when(messageTranslatorFlowCapableNodeConnector.translate(any(Object.class), any(DeviceState.class), any(Object.class))).thenReturn(mock(FlowCapableNodeConnector.class));
+ Mockito.when(messageTranslatorPacketReceived.translate(any(Object.class), any(DeviceInfo.class), any(Object.class))).thenReturn(mock(PacketReceived.class));
+ Mockito.when(messageTranslatorFlowCapableNodeConnector.translate(any(Object.class), any(DeviceInfo.class), any(Object.class))).thenReturn(mock(FlowCapableNodeConnector.class));
Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3, PacketIn.class.getName())))).thenReturn(messageTranslatorPacketReceived);
Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3, PortGrouping.class.getName())))).thenReturn(messageTranslatorFlowCapableNodeConnector);
Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3,
.thenReturn(messageTranslatorFlowRemoved);
Mockito.when(lifecycleConductor.getMessageIntelligenceAgency()).thenReturn(messageIntelligenceAgency);
- deviceContext = new DeviceContextImpl(connectionContext, deviceState, dataBroker, lifecycleConductor, outboundQueueProvider, translatorLibrary, false);
-
+ deviceContext = new DeviceContextImpl(connectionContext, deviceState, dataBroker, lifecycleConductor, outboundQueueProvider, translatorLibrary);
deviceContextSpy = Mockito.spy(deviceContext);
xid = new Xid(atomicLong.incrementAndGet());
xidMulti = new Xid(atomicLong.incrementAndGet());
+
+ Mockito.doNothing().when(deviceContextSpy).writeToTransaction(Mockito.<LogicalDatastoreType>any(), Mockito.<InstanceIdentifier>any(), any());
}
@Test(expected = NullPointerException.class)
public void testDeviceContextImplConstructorNullDataBroker() throws Exception {
- new DeviceContextImpl(connectionContext, deviceState, null, lifecycleConductor, outboundQueueProvider, translatorLibrary, false).close();
+ new DeviceContextImpl(connectionContext, deviceState, null, lifecycleConductor, outboundQueueProvider, translatorLibrary).close();
}
@Test(expected = NullPointerException.class)
public void testDeviceContextImplConstructorNullDeviceState() throws Exception {
- new DeviceContextImpl(connectionContext, null, dataBroker, lifecycleConductor, outboundQueueProvider, translatorLibrary, false).close();
+ new DeviceContextImpl(connectionContext, null, dataBroker, lifecycleConductor, outboundQueueProvider, translatorLibrary).close();
}
@Test(expected = NullPointerException.class)
public void testDeviceContextImplConstructorNullTimer() throws Exception {
- new DeviceContextImpl(null, deviceState, dataBroker, lifecycleConductor, outboundQueueProvider, translatorLibrary, false).close();
+ new DeviceContextImpl(null, deviceState, dataBroker, lifecycleConductor, outboundQueueProvider, translatorLibrary).close();
}
@Test
public void testInitialSubmitTransaction() throws Exception {
Mockito.when(wTx.submit()).thenReturn(Futures.immediateCheckedFuture(null));
final InstanceIdentifier<Nodes> dummyII = InstanceIdentifier.create(Nodes.class);
- deviceContext.getTransactionChainManager().activateTransactionManager() ;
- deviceContext.getTransactionChainManager().enableSubmit();
+ ((DeviceContextImpl) deviceContext).getTransactionChainManager().activateTransactionManager() ;
+ ((DeviceContextImpl) deviceContext).getTransactionChainManager().enableSubmit();
deviceContext.addDeleteToTxChain(LogicalDatastoreType.CONFIGURATION, dummyII);
- deviceContext.initialSubmitTransaction();
+ ((DeviceContextImpl) deviceContext).initialSubmitTransaction();
verify(wTx).submit();
}
@Test
public void testAddDeleteToTxChain() throws Exception{
final InstanceIdentifier<Nodes> dummyII = InstanceIdentifier.create(Nodes.class);
- deviceContext.getTransactionChainManager().activateTransactionManager() ;
- deviceContext.getTransactionChainManager().enableSubmit();
+ ((DeviceContextImpl) deviceContext).getTransactionChainManager().activateTransactionManager() ;
+ ((DeviceContextImpl) deviceContext).getTransactionChainManager().enableSubmit();
deviceContext.addDeleteToTxChain(LogicalDatastoreType.CONFIGURATION, dummyII);
verify(wTx).delete(eq(LogicalDatastoreType.CONFIGURATION), eq(dummyII));
}
*/
@Test
public void testSubmitTransaction() throws Exception {
- deviceContext.getTransactionChainManager().activateTransactionManager() ;
- deviceContext.getTransactionChainManager().enableSubmit();
+ ((DeviceContextImpl) deviceContext).getTransactionChainManager().activateTransactionManager() ;
+ ((DeviceContextImpl) deviceContext).getTransactionChainManager().enableSubmit();
assertTrue(deviceContext.submitTransaction());
}
assertNotNull(deviceMeterRegistry);
}
- @Test
- public void testGetRpcContext() {
- final RpcContext rpcContext = mock(RpcContext.class);
- deviceContext.setRpcContext(rpcContext);
- assertNotNull(deviceContext.getRpcContext());
- }
-
@Test
public void testProcessReply() {
final Error mockedError = mock(Error.class);
when(connectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
final NodeId dummyNodeId = new NodeId("dummyNodeId");
- when(deviceState.getNodeId()).thenReturn(dummyNodeId);
+ when(deviceInfo.getNodeId()).thenReturn(dummyNodeId);
final ConnectionContext mockedAuxiliaryConnectionContext = prepareConnectionContext();
deviceContext.addAuxiliaryConnectionContext(mockedAuxiliaryConnectionContext);
assertEquals(messageIntelligenceAgency, pickedMessageSpy);
}
- @Test
- public void testNodeConnector() {
- final NodeConnectorRef mockedNodeConnectorRef = mock(NodeConnectorRef.class);
- deviceContext.storeNodeConnectorRef(DUMMY_PORT_NUMBER, mockedNodeConnectorRef);
- final NodeConnectorRef nodeConnectorRef = deviceContext.lookupNodeConnectorRef(DUMMY_PORT_NUMBER);
- assertEquals(mockedNodeConnectorRef, nodeConnectorRef);
-
- }
-
@Test
public void testOnPublished() {
final ConnectionContext auxiliaryConnectionContext = addDummyAuxiliaryConnectionContext();
}
@Test
- public void testPortStatusMessage() {
+ public void testPortStatusMessage() throws Exception{
final PortStatusMessage mockedPortStatusMessage = mock(PortStatusMessage.class);
final Class dummyClass = Class.class;
when(mockedPortStatusMessage.getImplementedInterface()).thenReturn(dummyClass);
final GetFeaturesOutput mockedFeature = mock(GetFeaturesOutput.class);
when(mockedFeature.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
- when(deviceState.getFeatures()).thenReturn(mockedFeature);
when(mockedPortStatusMessage.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
when(mockedPortStatusMessage.getReason()).thenReturn(PortReason.OFPPRADD);
+ when(mockedPortStatusMessage.getPortNo()).thenReturn(42L);
OpenflowPortsUtil.init();
- deviceContext.processPortStatusMessage(mockedPortStatusMessage);
-// verify(txChainManager).writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class), any(DataObject.class));
+ deviceContextSpy.processPortStatusMessage(mockedPortStatusMessage);
+ verify(deviceContextSpy).writeToTransaction(Mockito.<LogicalDatastoreType>any(), Mockito.<InstanceIdentifier>any(), any());
+ verify(deviceContextSpy).submitTransaction();
}
@Test
.setMatch(new MatchBuilder().build());
final NotificationPublishService mockedNotificationPublishService = mock(NotificationPublishService.class);
- Mockito.when(messageTranslatorFlowRemoved.translate(any(Object.class), any(DeviceState.class), any(Object.class)))
+ Mockito.when(messageTranslatorFlowRemoved.translate(any(Object.class), any(DeviceInfo.class), any(Object.class)))
.thenReturn(flowRemovedMdsalBld.build());
// insert flow+flowId into local registry
final NotificationPublishService mockedNotificationPublishService = mock(NotificationPublishService.class);
deviceContext.setNotificationPublishService(mockedNotificationPublishService);
- deviceContext.setExtensionConverterProvider(mockedExtensionConverterProvider);
+ ((DeviceContextImpl) deviceContext).setExtensionConverterProvider(mockedExtensionConverterProvider);
deviceContext.processExperimenterMessage(experimenterMessage);
verify(mockedNotificationPublishService).offerNotification(any(ExperimenterMessageFromDev.class));
assertEquals(0, deviceContext.getDeviceMeterRegistry().getAllMeterIds().size());
}
-
- @Test
- public void testOnClusterRoleChange() throws Exception {
- // test role.equals(oldRole)
- Assert.assertNull(deviceContextSpy.onClusterRoleChange(OfpRole.BECOMEMASTER, OfpRole.BECOMEMASTER).get());
-
- // test call transactionChainManager.deactivateTransactionManager()
- Assert.assertNull(deviceContextSpy.onClusterRoleChange(OfpRole.BECOMESLAVE, OfpRole.NOCHANGE).get());
-
- // test call MdSalRegistrationUtils.unregisterServices(rpcContext)
- final RpcContext rpcContext = mock(RpcContext.class);
- deviceContextSpy.setRpcContext(rpcContext);
- Assert.assertNull(deviceContextSpy.onClusterRoleChange(OfpRole.BECOMESLAVE, OfpRole.NOCHANGE).get());
-
- final StatisticsContext statisticsContext = mock(StatisticsContext.class);
- deviceContextSpy.setStatisticsContext(statisticsContext);
-
- deviceContextSpy.onClusterRoleChange(OfpRole.NOCHANGE, OfpRole.BECOMEMASTER);
- verify(deviceContextSpy).onDeviceTakeClusterLeadership();
-
- Mockito.when(wTx.submit()).thenReturn(Futures.immediateCheckedFuture(null));
- deviceContextSpy.onClusterRoleChange(OfpRole.NOCHANGE, OfpRole.BECOMESLAVE);
- verify(deviceContextSpy).onDeviceLostClusterLeadership();
- }
}
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
private static final long TEST_VALUE_GLOBAL_NOTIFICATION_QUOTA = 2000l;
private static final int barrierCountLimit = 25600;
private static final int barrierIntervalNanos = 500;
+ public static final NodeId DUMMY_NODE_ID = new NodeId("dummyNodeId");
@Mock
CheckedFuture<Void, TransactionCommitFailedException> mockedFuture;
private LifecycleConductor lifecycleConductor;
@Mock
private MessageIntelligenceAgency messageIntelligenceAgency;
+ @Mock
+ private DeviceInfo deviceInfo;
@Before
public void setUp() throws Exception {
OpenflowPortsUtil.init();
- when(mockConnectionContext.getNodeId()).thenReturn(new NodeId("dummyNodeId"));
+ when(mockConnectionContext.getNodeId()).thenReturn(DUMMY_NODE_ID);
when(mockConnectionContext.getFeatures()).thenReturn(mockFeatures);
when(mockConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
+ when(mockConnectionContext.getDeviceInfo()).thenReturn(deviceInfo);
when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockConnectionContext);
+ when(deviceInfo.getNodeId()).thenReturn(DUMMY_NODE_ID);
final Capabilities capabilitiesV13 = mock(Capabilities.class);
final CapabilitiesV10 capabilitiesV10 = mock(CapabilitiesV10.class);
final DeviceManagerImpl deviceManager = prepareDeviceManager(withException);
final DeviceState mockedDeviceState = mock(DeviceState.class);
when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
- when(mockedDeviceState.getNodeId()).thenReturn(mockedNodeId);
if (withException) {
doThrow(new IllegalStateException("dummy")).when(mockedDeviceContext).initialSubmitTransaction();
}
- deviceManager.addDeviceContextToMap(mockedNodeId, mockedDeviceContext);
- deviceManager.onDeviceContextLevelUp(mockedDeviceContext.getDeviceState().getNodeId());
+ deviceManager.addDeviceContextToMap(deviceInfo, mockedDeviceContext);
+ deviceManager.onDeviceContextLevelUp(deviceInfo);
if (withException) {
verify(mockedDeviceContext).close();
} else {
deviceManager.deviceConnected(mockConnectionContext);
final InOrder order = inOrder(mockConnectionContext);
- order.verify(mockConnectionContext).getFeatures();
order.verify(mockConnectionContext).setOutboundQueueProvider(any(OutboundQueueProvider.class));
order.verify(mockConnectionContext).setOutboundQueueHandleRegistration(
Mockito.<OutboundQueueHandlerRegistration<OutboundQueueProvider>>any());
- order.verify(mockConnectionContext).getNodeId();
- verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<NodeId>any());
+ verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<DeviceInfo>any());
}
@Test
.setPortNo(41L);
when(mockFeatures.getPhyPort()).thenReturn(Collections.singletonList(phyPort.build()));
final MessageTranslator<Object, Object> mockedTranslator = mock(MessageTranslator.class);
- when(mockedTranslator.translate(Matchers.<Object>any(), Matchers.<DeviceState>any(), Matchers.any()))
+ when(mockedTranslator.translate(Matchers.<Object>any(), Matchers.<DeviceInfo>any(), Matchers.any()))
.thenReturn(null);
when(translatorLibrary.lookupTranslator(Matchers.<TranslatorKey>any())).thenReturn(mockedTranslator);
deviceManager.deviceConnected(mockConnectionContext);
final InOrder order = inOrder(mockConnectionContext);
- order.verify(mockConnectionContext).getFeatures();
order.verify(mockConnectionContext).setOutboundQueueProvider(any(OutboundQueueProvider.class));
order.verify(mockConnectionContext).setOutboundQueueHandleRegistration(
Mockito.<OutboundQueueHandlerRegistration<OutboundQueueProvider>>any());
- order.verify(mockConnectionContext).getNodeId();
- verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<NodeId>any());
+ verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<DeviceInfo>any());
}
@Test
when(deviceContext.getPrimaryConnectionContext()).thenReturn(connectionContext);
when(deviceContext.getDeviceState()).thenReturn(deviceState);
- final ConcurrentHashMap<NodeId, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
- deviceContexts.put(mockedNodeId, deviceContext);
+ final ConcurrentHashMap<DeviceInfo, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
+ deviceContexts.put(deviceInfo, deviceContext);
deviceManager.onDeviceDisconnected(connectionContext);
public void testClose() throws Exception {
final DeviceContext deviceContext = mock(DeviceContext.class);
final DeviceManagerImpl deviceManager = prepareDeviceManager();
- final ConcurrentHashMap<NodeId, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
- deviceContexts.put(mockedNodeId, deviceContext);
+ final ConcurrentHashMap<DeviceInfo, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
+ deviceContexts.put(deviceInfo, deviceContext);
Assert.assertEquals(1, deviceContexts.size());
deviceManager.close();
verify(deviceContext, Mockito.never()).close();
}
- private static ConcurrentHashMap<NodeId, DeviceContext> getContextsCollection(final DeviceManagerImpl deviceManager) throws NoSuchFieldException, IllegalAccessException {
+ private static ConcurrentHashMap<DeviceInfo, DeviceContext> getContextsCollection(final DeviceManagerImpl deviceManager) throws NoSuchFieldException, IllegalAccessException {
// HACK: contexts collection for testing shall be accessed in some more civilized way
final Field contextsField = DeviceManagerImpl.class.getDeclaredField("deviceContexts");
Assert.assertNotNull(contextsField);
contextsField.setAccessible(true);
- return (ConcurrentHashMap<NodeId, DeviceContext>) contextsField.get(deviceManager);
+ return (ConcurrentHashMap<DeviceInfo, DeviceContext>) contextsField.get(deviceManager);
}
}
package org.opendaylight.openflowplugin.impl.device;
-import java.util.Arrays;
-import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
-import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPort;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPortBuilder;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
/**
* openflowplugin-impl
* org.opendaylight.openflowplugin.impl.device
*
* test of {@link DeviceStateImpl} - lightweight version, using basic ways (TDD)
- *
- * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
- *
- * Created: Mar 29, 2015
*/
@RunWith(MockitoJUnitRunner.class)
public class DeviceStateImplTest {
- private NodeId nodeId;
@Mock
- private FeaturesReply featuresReply;
- private DeviceStateImpl deviceState;
+ private DeviceInfo deviceInfo;
- private final short version = 13;
- private final long portNr = 10L;
- private final Long portBandwidth = 1024L;
- private final List<PhyPort> pPort = Arrays.asList(new PhyPortBuilder()
- .setPortNo(portNr).setMaxSpeed(portBandwidth).build());
+ private DeviceStateImpl deviceState;
@Before
public void initialization() {
- nodeId = new NodeId("test-node-id");
- Mockito.when(featuresReply.getVersion()).thenReturn(version);
- Mockito.when(featuresReply.getPhyPort()).thenReturn(pPort);
- deviceState = new DeviceStateImpl(featuresReply, nodeId);
- }
-
- /**
- * Test method for {@link DeviceStateImpl#DeviceStateImpl(FeaturesReply, NodeId)}.
- */
- @Test(expected=NullPointerException.class)
- public void testDeviceStateImplNullNodeId(){
- new DeviceStateImpl(featuresReply, null);
- }
-
- /**
- * Test method for {@link DeviceStateImpl#DeviceStateImpl(FeaturesReply, NodeId)}.
- */
- @Test(expected=IllegalArgumentException.class)
- public void testDeviceStateImplNullFeaturesReply(){
- new DeviceStateImpl(null, nodeId);
- }
-
- /**
- * Test method for {@link DeviceStateImpl#getNodeId()}.
- */
- @Test
- public void testGetNodeId(){
- final NodeId getNodeId = deviceState.getNodeId();
- Assert.assertNotNull(getNodeId);
- Assert.assertEquals(nodeId, getNodeId);
- }
-
- /**
- * Test method for {@link DeviceStateImpl#getFeatures()}.
- */
- @Test
- public void testGetFeatures(){
- final GetFeaturesOutputBuilder expetedResult = new GetFeaturesOutputBuilder(featuresReply);
- final GetFeaturesOutput getFeatures = deviceState.getFeatures();
- Assert.assertNotNull(getFeatures);
- Assert.assertEquals(expetedResult.getVersion(), getFeatures.getVersion());
- Assert.assertEquals(expetedResult.getPhyPort(), getFeatures.getPhyPort());
+ deviceState = new DeviceStateImpl(deviceInfo);
}
@Test
import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
@Mock
DeviceState deviceState;
@Mock
+ DeviceInfo deviceInfo;
+ @Mock
LifecycleConductor conductor;
@Mock
.thenReturn(txChain);
nodeId = new NodeId("h2g2:42");
nodeKeyIdent = DeviceStateUtil.createNodeInstanceIdentifier(nodeId);
- Mockito.when(deviceState.getNodeInstanceIdentifier()).thenReturn(nodeKeyIdent);
- Mockito.when(deviceState.getNodeId()).thenReturn(nodeId);
- txChainManager = new TransactionChainManager(dataBroker, deviceState, conductor);
+ Mockito.when(deviceInfo.getNodeInstanceIdentifier()).thenReturn(nodeKeyIdent);
+ Mockito.when(deviceInfo.getNodeId()).thenReturn(nodeId);
+ txChainManager = new TransactionChainManager(dataBroker, deviceInfo, conductor);
Mockito.when(txChain.newWriteOnlyTransaction()).thenReturn(writeTx);
path = InstanceIdentifier.create(Nodes.class).child(Node.class, new NodeKey(nodeId));
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
private DeviceContext deviceContext;
@Mock
private DeviceState deviceState;
+ @Mock
+ private DeviceInfo deviceInfo;
@Before
}
FLOWS_STATISTICS_UPDATE_BUILDER.setFlowAndStatisticsMapList(flowAndStatisticsMapListList);
Mockito.when(deviceContext.getDeviceState()).thenReturn(deviceState);
- Mockito.when(deviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
+ Mockito.when(deviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
}
@Test
import org.opendaylight.controller.md.sal.common.api.clustering.Entity;
import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration;
import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
import org.opendaylight.openflowplugin.api.openflow.role.RoleContext;
import org.opendaylight.openflowplugin.api.openflow.role.RoleManager;
@Mock
private LifecycleConductor conductor;
+ @Mock
+ private DeviceInfo deviceInfo;
+
private final NodeId nodeId = NodeId.getDefaultInstance("openflow:1");
private final Entity entity = new Entity(RoleManager.ENTITY_TYPE, nodeId.getValue());
private final Entity txEntity = new Entity(RoleManager.TX_ENTITY_TYPE, nodeId.getValue());
@Before
public void setup() throws CandidateAlreadyRegisteredException {
- roleContext = new RoleContextImpl(nodeId, entityOwnershipService, entity, txEntity, conductor);
+ roleContext = new RoleContextImpl(deviceInfo, entityOwnershipService, entity, txEntity, conductor);
Mockito.when(entityOwnershipService.registerCandidate(entity)).thenReturn(entityOwnershipCandidateRegistration);
Mockito.when(entityOwnershipService.registerCandidate(txEntity)).thenReturn(entityOwnershipCandidateRegistration);
+ Mockito.when(deviceInfo.getNodeId()).thenReturn(nodeId);
}
//@Test
@Test
public void testCreateRequestContext() throws Exception {
roleContext.createRequestContext();
- Mockito.verify(conductor).reserveXidForDeviceMessage(nodeId);
+ Mockito.verify(conductor).reserveXidForDeviceMessage(deviceInfo);
}
@Test(expected = NullPointerException.class)
@Test
public void testGetNodeId() throws Exception {
- Assert.assertTrue(roleContext.getNodeId().equals(nodeId));
+ Assert.assertTrue(roleContext.getDeviceInfo().getNodeId().equals(nodeId));
}
@Test
package org.opendaylight.openflowplugin.impl.role;
-import java.math.BigInteger;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
import com.google.common.base.VerifyException;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.Futures;
+import java.math.BigInteger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration;
import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.RoleChangeListener;
import org.opendaylight.openflowplugin.api.openflow.role.RoleContext;
+import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-
@RunWith(MockitoJUnitRunner.class)
public class RoleManagerImplTest {
@Mock
DeviceState deviceState;
+ @Mock
+ DeviceInfo deviceInfo;
+
+ @Mock
+ DeviceInfo deviceInfo2;
+
+ @Mock
+ MessageSpy messageSpy;
+
+ @Mock
+ OutboundQueue outboundQueue;
+
@Mock
GetFeaturesOutput featuresOutput;
private RoleManagerImpl roleManagerSpy;
private RoleContext roleContextSpy;
private final NodeId nodeId = NodeId.getDefaultInstance("openflow:1");
+ private final NodeId nodeId2 = NodeId.getDefaultInstance("openflow:2");
- private final EntityOwnershipChange masterEntity = new EntityOwnershipChange(RoleManagerImpl.makeEntity(nodeId), false, true, true);
- private final EntityOwnershipChange masterTxEntity = new EntityOwnershipChange(RoleManagerImpl.makeTxEntity(nodeId), false, true, true);
- private final EntityOwnershipChange slaveEntity = new EntityOwnershipChange(RoleManagerImpl.makeEntity(nodeId), true, false, true);
- private final EntityOwnershipChange slaveTxEntityLast = new EntityOwnershipChange(RoleManagerImpl.makeTxEntity(nodeId), true, false, false);
- private final EntityOwnershipChange masterEntityNotOwner = new EntityOwnershipChange(RoleManagerImpl.makeEntity(nodeId), true, false, true);
+
+ private final EntityOwnershipChange masterEntity = new EntityOwnershipChange(RoleManagerImpl.makeEntity(nodeId), false, true, true, false);
+ private final EntityOwnershipChange masterTxEntity = new EntityOwnershipChange(RoleManagerImpl.makeTxEntity(nodeId), false, true, true, false);
+ private final EntityOwnershipChange slaveEntity = new EntityOwnershipChange(RoleManagerImpl.makeEntity(nodeId), true, false, true, false);
+ private final EntityOwnershipChange slaveTxEntityLast = new EntityOwnershipChange(RoleManagerImpl.makeTxEntity(nodeId), true, false, false, false);
+ private final EntityOwnershipChange masterEntityNotOwner = new EntityOwnershipChange(RoleManagerImpl.makeEntity(nodeId), true, false, true, false);
private InOrder inOrder;
@Before
public void setUp() throws Exception {
CheckedFuture<Void, TransactionCommitFailedException> future = Futures.immediateCheckedFuture(null);
- Mockito.when(deviceState.getFeatures()).thenReturn(featuresOutput);
Mockito.when(entityOwnershipService.registerListener(Mockito.anyString(), Mockito.any(EntityOwnershipListener.class))).thenReturn(entityOwnershipListenerRegistration);
Mockito.when(entityOwnershipService.registerCandidate(Mockito.any(Entity.class))).thenReturn(entityOwnershipCandidateRegistration);
Mockito.when(deviceContext.getPrimaryConnectionContext()).thenReturn(connectionContext);
Mockito.when(deviceContext.getDeviceState()).thenReturn(deviceState);
+ Mockito.when(deviceContext.getDeviceInfo()).thenReturn(deviceInfo);
+ Mockito.when(deviceContext.getMessageSpy()).thenReturn(messageSpy);
+ Mockito.when(deviceContext.getPrimaryConnectionContext().getOutboundQueueProvider()).thenReturn(outboundQueue);
Mockito.when(connectionContext.getFeatures()).thenReturn(featuresReply);
Mockito.when(connectionContext.getNodeId()).thenReturn(nodeId);
Mockito.when(connectionContext.getConnectionState()).thenReturn(ConnectionContext.CONNECTION_STATE.WORKING);
- Mockito.when(featuresReply.getDatapathId()).thenReturn(new BigInteger("1"));
- Mockito.when(featuresReply.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
- Mockito.doNothing().when(deviceInitializationPhaseHandler).onDeviceContextLevelUp(Mockito.<NodeId>any());
- Mockito.doNothing().when(deviceTerminationPhaseHandler).onDeviceContextLevelDown(Mockito.<DeviceContext>any());
+ Mockito.when(deviceInfo.getDatapathId()).thenReturn(new BigInteger("1"));
+ Mockito.when(deviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
+ Mockito.when(deviceInfo.getNodeId()).thenReturn(nodeId);
+ Mockito.doNothing().when(deviceInitializationPhaseHandler).onDeviceContextLevelUp(Mockito.<DeviceInfo>any());
+ Mockito.doNothing().when(deviceTerminationPhaseHandler).onDeviceContextLevelDown(Mockito.<DeviceInfo>any());
Mockito.when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
Mockito.when(writeTransaction.submit()).thenReturn(future);
- Mockito.when(deviceManager.getDeviceContextFromNodeId(Mockito.<NodeId>any())).thenReturn(deviceContext);
+ Mockito.when(deviceInfo.getNodeId()).thenReturn(nodeId);
+ Mockito.when(deviceInfo2.getNodeId()).thenReturn(nodeId2);
+ Mockito.when(deviceInfo.getDatapathId()).thenReturn(BigInteger.TEN);
roleManager = new RoleManagerImpl(entityOwnershipService, dataBroker, conductor);
roleManager.setDeviceInitializationPhaseHandler(deviceInitializationPhaseHandler);
roleManager.setDeviceTerminationPhaseHandler(deviceTerminationPhaseHandler);
- Mockito.when(conductor.getDeviceContext(Mockito.<NodeId>any())).thenReturn(deviceContext);
+ Mockito.when(conductor.getDeviceContext(deviceInfo)).thenReturn(deviceContext);
roleManagerSpy = Mockito.spy(roleManager);
- roleManagerSpy.onDeviceContextLevelUp(nodeId);
- roleContextSpy = Mockito.spy(roleManager.getRoleContext(nodeId));
+ roleManagerSpy.onDeviceContextLevelUp(deviceInfo);
+ Mockito.doNothing().when(roleManagerSpy).makeDeviceRoleChange(Mockito.<OfpRole>any(), Mockito.<RoleContext>any(), Mockito.anyBoolean());
+ roleContextSpy = Mockito.spy(roleManager.getRoleContext(deviceInfo));
+ Mockito.when(roleContextSpy.getDeviceInfo()).thenReturn(deviceInfo);
+ Mockito.when(roleContextSpy.getDeviceInfo().getNodeId()).thenReturn(nodeId);
inOrder = Mockito.inOrder(entityOwnershipListenerRegistration, roleManagerSpy, roleContextSpy);
}
@Test(expected = VerifyException.class)
public void testOnDeviceContextLevelUp() throws Exception {
- roleManagerSpy.onDeviceContextLevelUp(nodeId);
- inOrder.verify(roleManagerSpy).onDeviceContextLevelUp(nodeId);
+ roleManagerSpy.onDeviceContextLevelUp(deviceInfo);
+ inOrder.verify(roleManagerSpy).onDeviceContextLevelUp(deviceInfo);
inOrder.verifyNoMoreInteractions();
}
roleManagerSpy.ownershipChanged(masterTxEntity);
roleManagerSpy.close();
inOrder.verify(entityOwnershipListenerRegistration, Mockito.calls(2)).close();
- inOrder.verify(roleManagerSpy).removeDeviceFromOperationalDS(nodeId);
+ inOrder.verify(roleManagerSpy).removeDeviceFromOperationalDS(deviceInfo);
inOrder.verifyNoMoreInteractions();
}
roleManagerSpy.ownershipChanged(slaveEntity);
roleManagerSpy.close();
inOrder.verify(entityOwnershipListenerRegistration, Mockito.calls(2)).close();
- inOrder.verify(roleManagerSpy, Mockito.never()).removeDeviceFromOperationalDS(nodeId);
+ inOrder.verify(roleManagerSpy, Mockito.never()).removeDeviceFromOperationalDS(deviceInfo);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testOnDeviceContextLevelDown() throws Exception {
- roleManagerSpy.onDeviceContextLevelDown(deviceContext);
- inOrder.verify(roleManagerSpy).onDeviceContextLevelDown(deviceContext);
+ roleManagerSpy.onDeviceContextLevelDown(deviceInfo);
+ inOrder.verify(roleManagerSpy).onDeviceContextLevelDown(deviceInfo);
inOrder.verifyNoMoreInteractions();
}
inOrder.verify(roleContextSpy, Mockito.atLeastOnce()).isTxCandidateRegistered();
inOrder.verify(roleContextSpy, Mockito.calls(1)).unregisterCandidate(Mockito.<Entity>any());
inOrder.verify(roleContextSpy, Mockito.never()).close();
- inOrder.verify(roleManagerSpy, Mockito.calls(1)).removeDeviceFromOperationalDS(Mockito.<NodeId>any());
+ inOrder.verify(roleManagerSpy, Mockito.calls(1)).removeDeviceFromOperationalDS(Mockito.<DeviceInfo>any());
}
@Test
Mockito.when(roleContextSpy.isTxCandidateRegistered()).thenReturn(false);
roleManagerSpy.changeOwnershipForTxEntity(slaveTxEntityLast, roleContextSpy);
verify(roleContextSpy).close();
- verify(roleContextSpy).getNodeId();
- verify(conductor).closeConnection(nodeId);
+ verify(conductor).closeConnection(deviceInfo);
}
@Test
Mockito.when(roleContextSpy.isTxCandidateRegistered()).thenReturn(true);
roleManagerSpy.changeOwnershipForTxEntity(masterEntityNotOwner, roleContextSpy);
verify(roleContextSpy).close();
- verify(conductor).closeConnection(nodeId);
+ verify(conductor).closeConnection(deviceInfo);
}
@Test
public void testAddListener() throws Exception {
roleManager.addRoleChangeListener((new RoleChangeListener() {
@Override
- public void roleInitializationDone(final NodeId nodeId, final boolean success) {
- Assert.assertTrue(nodeId.equals(nodeId));
+ public void roleInitializationDone(final DeviceInfo deviceInfo_, final boolean success) {
+ Assert.assertTrue(deviceInfo.equals(deviceInfo_));
Assert.assertTrue(success);
}
@Override
- public void roleChangeOnDevice(final NodeId nodeId_, final boolean success, final OfpRole newRole, final boolean initializationPhase) {
- Assert.assertTrue(nodeId.equals(nodeId_));
+ public void roleChangeOnDevice(final DeviceInfo deviceInfo_, final boolean success, final OfpRole newRole, final boolean initializationPhase) {
+ Assert.assertTrue(RoleManagerImplTest.this.deviceInfo.equals(deviceInfo_));
Assert.assertTrue(success);
Assert.assertFalse(initializationPhase);
Assert.assertTrue(newRole.equals(OfpRole.BECOMEMASTER));
}
}));
- roleManager.notifyListenersRoleInitializationDone(nodeId, true);
- roleManager.notifyListenersRoleChangeOnDevice(nodeId, true, OfpRole.BECOMEMASTER, false);
- }
-
- @Test
- public void testMakeDeviceRoleChange() throws Exception{
- roleManagerSpy.makeDeviceRoleChange(OfpRole.BECOMEMASTER, roleContextSpy, true);
- verify(roleManagerSpy, atLeastOnce()).sendRoleChangeToDevice(Mockito.<OfpRole>any(), Mockito.<RoleContext>any());
- verify(roleManagerSpy, atLeastOnce()).notifyListenersRoleChangeOnDevice(Mockito.<NodeId>any(), eq(true), Mockito.<OfpRole>any(), eq(true));
+ roleManager.notifyListenersRoleInitializationDone(deviceInfo, true);
+ roleManager.notifyListenersRoleChangeOnDevice(deviceInfo, true, OfpRole.BECOMEMASTER, false);
}
@Test
public void testServicesChangeDone() throws Exception {
- final NodeId nodeId2 = NodeId.getDefaultInstance("openflow:2");
- roleManagerSpy.setRoleContext(nodeId2, roleContextSpy);
- roleManagerSpy.servicesChangeDone(nodeId2, true);
+ roleManagerSpy.setRoleContext(deviceInfo2, roleContextSpy);
+ roleManagerSpy.servicesChangeDone(deviceInfo2, true);
verify(roleContextSpy).unregisterCandidate(Mockito.<Entity>any());
}
@Test
public void testServicesChangeDoneContextIsNull() throws Exception {
- final NodeId nodeId2 = NodeId.getDefaultInstance("openflow:2");
- roleManagerSpy.setRoleContext(nodeId, roleContextSpy);
- roleManagerSpy.servicesChangeDone(nodeId2, true);
+ roleManagerSpy.setRoleContext(deviceInfo, roleContextSpy);
+ roleManagerSpy.servicesChangeDone(deviceInfo2, true);
verify(roleContextSpy, never()).unregisterCandidate(Mockito.<Entity>any());
}
}
\ No newline at end of file
package org.opendaylight.openflowplugin.impl.rpc;
import static org.junit.Assert.assertNotNull;
+
import java.util.concurrent.Future;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.device.XidSequencer;
private NotificationPublishService notificationPublishService;
@Mock
private TestRpcService serviceInstance;
+ @Mock
+ private DeviceInfo deviceInfo;
private KeyedInstanceIdentifier<Node, NodeKey> nodeInstanceIdentifier;
nodeInstanceIdentifier = InstanceIdentifier.create(Nodes.class).child(Node.class, new NodeKey(nodeId));
when(deviceContext.getDeviceState()).thenReturn(deviceState);
- when(deviceState.getNodeInstanceIdentifier()).thenReturn(nodeInstanceIdentifier);
+ when(deviceInfo.getNodeInstanceIdentifier()).thenReturn(nodeInstanceIdentifier);
when(deviceContext.getMessageSpy()).thenReturn(messageSpy);
rpcContext = new RpcContextImpl(rpcProviderRegistry,deviceContext, messageSpy, MAX_REQUESTS,nodeInstanceIdentifier);
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+
import com.google.common.base.VerifyException;
import java.util.concurrent.ConcurrentMap;
import org.junit.Before;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
@Mock
private RpcContext removedContexts;
@Mock
- private ConcurrentMap<NodeId, RpcContext> contexts;
+ private ConcurrentMap<DeviceInfo, RpcContext> contexts;
+ @Mock
+ private DeviceInfo deviceInfo;
@Rule
public ExpectedException expectedException = ExpectedException.none();
Mockito.when(deviceContext.getPrimaryConnectionContext()).thenReturn(connectionContext);
Mockito.when(deviceContext.getDeviceState()).thenReturn(deviceState);
Mockito.when(deviceContext.getItemLifeCycleSourceRegistry()).thenReturn(itemLifeCycleRegistry);
- Mockito.when(deviceState.getNodeInstanceIdentifier()).thenReturn(nodePath);
- Mockito.when(deviceState.getFeatures()).thenReturn(featuresOutput);
+ Mockito.when(deviceInfo.getNodeInstanceIdentifier()).thenReturn(nodePath);
rpcManager.setDeviceTerminationPhaseHandler(deviceTerminationPhaseHandler);
Mockito.when(connectionContext.getFeatures()).thenReturn(features);
Mockito.when(deviceContext.getPrimaryConnectionContext()).thenReturn(connectionContext);
Mockito.when(deviceContext.getDeviceState()).thenReturn(deviceState);
Mockito.when(deviceContext.getItemLifeCycleSourceRegistry()).thenReturn(itemLifeCycleRegistry);
- Mockito.when(deviceState.getNodeInstanceIdentifier()).thenReturn(nodePath);
+ Mockito.when(deviceInfo.getNodeInstanceIdentifier()).thenReturn(nodePath);
Mockito.when(deviceContext.getMessageSpy()).thenReturn(messageSpy);
- Mockito.when(deviceState.getNodeId()).thenReturn(nodeKey.getId());
+ Mockito.when(deviceInfo.getNodeId()).thenReturn(nodeKey.getId());
Mockito.when(rpcProviderRegistry.addRoutedRpcImplementation(
Matchers.<Class<RpcService>>any(), Matchers.any(RpcService.class)))
.thenReturn(routedRpcRegistration);
- Mockito.when(conductor.getDeviceContext(Mockito.<NodeId>any())).thenReturn(deviceContext);
- Mockito.when(contexts.remove(nodeId)).thenReturn(removedContexts);
+ Mockito.when(conductor.getDeviceContext(deviceInfo)).thenReturn(deviceContext);
+ Mockito.when(contexts.remove(deviceInfo)).thenReturn(removedContexts);
}
@Test
public void onDeviceContextLevelUp() throws Exception {
- rpcManager.onDeviceContextLevelUp(nodeId);
- verify(conductor).getDeviceContext(Mockito.<NodeId>any());
+ rpcManager.onDeviceContextLevelUp(deviceInfo);
+ verify(conductor).getDeviceContext(deviceInfo);
}
@Test
public void onDeviceContextLevelUpTwice() throws Exception {
- rpcManager.onDeviceContextLevelUp(nodeId);
+ rpcManager.onDeviceContextLevelUp(deviceInfo);
expectedException.expect(VerifyException.class);
- rpcManager.onDeviceContextLevelUp(nodeId);
+ rpcManager.onDeviceContextLevelUp(deviceInfo);
}
@Test
public void testOnDeviceContextLevelUpMaster() throws Exception {
- rpcManager.onDeviceContextLevelUp(nodeId);
- verify(deviceINitializationPhaseHandler).onDeviceContextLevelUp(nodeId);
+ rpcManager.onDeviceContextLevelUp(deviceInfo);
+ verify(deviceINitializationPhaseHandler).onDeviceContextLevelUp(deviceInfo);
}
@Test
public void testOnDeviceContextLevelUpSlave() throws Exception {
- rpcManager.onDeviceContextLevelUp(nodeId);
- verify(deviceINitializationPhaseHandler).onDeviceContextLevelUp(nodeId);
+ rpcManager.onDeviceContextLevelUp(deviceInfo);
+ verify(deviceINitializationPhaseHandler).onDeviceContextLevelUp(deviceInfo);
}
@Test
public void testOnDeviceContextLevelUpOther() throws Exception {
- rpcManager.onDeviceContextLevelUp(nodeId);
- verify(deviceINitializationPhaseHandler).onDeviceContextLevelUp(nodeId);
+ rpcManager.onDeviceContextLevelUp(deviceInfo);
+ verify(deviceINitializationPhaseHandler).onDeviceContextLevelUp(deviceInfo);
}
@Test
public void testOnDeviceContextLevelDown() throws Exception {
- rpcManager.onDeviceContextLevelDown(deviceContext);
- verify(deviceTerminationPhaseHandler).onDeviceContextLevelDown(deviceContext);
+ rpcManager.onDeviceContextLevelDown(deviceInfo);
+ verify(deviceTerminationPhaseHandler).onDeviceContextLevelDown(deviceInfo);
}
/**
*/
@Test
public void onDeviceContextLevelDown1() {
- rpcManager.addRecordToContexts(nodeId,removedContexts);
- rpcManager.onDeviceContextLevelDown(deviceContext);
+ rpcManager.addRecordToContexts(deviceInfo,removedContexts);
+ rpcManager.onDeviceContextLevelDown(deviceInfo);
verify(removedContexts,times(1)).close();
- verify(deviceTerminationPhaseHandler,times(1)).onDeviceContextLevelDown(deviceContext);
+ verify(deviceTerminationPhaseHandler,times(1)).onDeviceContextLevelDown(deviceInfo);
}
*/
@Test
public void onDeviceContextLevelDown2() {
- rpcManager.onDeviceContextLevelDown(deviceContext);
+ rpcManager.onDeviceContextLevelDown(deviceInfo);
verify(removedContexts,never()).close();
- verify(deviceTerminationPhaseHandler,times(1)).onDeviceContextLevelDown(deviceContext);
+ verify(deviceTerminationPhaseHandler,times(1)).onDeviceContextLevelDown(deviceInfo);
}
@Test
public void close() {
- rpcManager.addRecordToContexts(nodeId,removedContexts);
+ rpcManager.addRecordToContexts(deviceInfo,removedContexts);
rpcManager.close();
verify(removedContexts,atLeastOnce()).close();
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
+
import com.google.common.util.concurrent.ListenableFuture;
import java.util.Collection;
import org.junit.Before;
private SendBarrierInput buildSendBarrierInput() {
return new SendBarrierInputBuilder()
- .setNode(new NodeRef(mockedDeviceState.getNodeInstanceIdentifier())).build();
+ .setNode(new NodeRef(mockedDeviceInfo.getNodeInstanceIdentifier())).build();
}
}
\ No newline at end of file
import static org.mockito.Mockito.times;
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 com.google.common.util.concurrent.Futures;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
@Mock
private DeviceState mockedDeviceState;
@Mock
+ private DeviceInfo mockedDeviceInfo;
+ @Mock
private GetFeaturesOutput mocketGetFeaturesOutput;
@Mock
private DeviceFlowRegistry mockedFlowRegistry;
when(mocketGetFeaturesOutput.getDatapathId()).thenReturn(BigInteger.valueOf(123L));
when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimaryConnection);
- when(mockedDeviceState.getNodeInstanceIdentifier()).thenReturn(NODE_PATH);
- when(mockedDeviceState.getFeatures()).thenReturn(mocketGetFeaturesOutput);
+ when(mockedDeviceInfo.getNodeInstanceIdentifier()).thenReturn(NODE_PATH);
when(mockedDeviceState.deviceSynchronized()).thenReturn(true);
- when(mockedDeviceState.getNodeId()).thenReturn(mockedNodeId);
+ when(mockedDeviceInfo.getNodeId()).thenReturn(mockedNodeId);
+ when(mockedDeviceInfo.getDatapathId()).thenReturn(BigInteger.TEN);
when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
+ when(mockedDeviceContext.getDeviceInfo()).thenReturn(mockedDeviceInfo);
when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(mockedFlowRegistry);
- final InstanceIdentifier<FlowCapableNode> nodePath = mockedDeviceState.getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
+ final InstanceIdentifier<FlowCapableNode> nodePath = mockedDeviceInfo.getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
final FlowCapableNodeBuilder flowNodeBuilder = new FlowCapableNodeBuilder();
flowNodeBuilder.setTable(Collections.<Table> emptyList());
final Optional<FlowCapableNode> flowNodeOpt = Optional.of(flowNodeBuilder.build());
}
};
multipartRequestOnTheFlyCallback = new MultipartRequestOnTheFlyCallback(dummyRequestContext, String.class,
- mockedDeviceContext.getMessageSpy(),dummyEventIdentifier, mockedDeviceContext.getDeviceState(),
+ mockedDeviceContext.getMessageSpy(),dummyEventIdentifier, mockedDeviceInfo,
mockedDeviceContext.getDeviceFlowRegistry(), mockedDeviceContext);
}
.setMultipartReplyBody(multipartReplyFlowCaseBuilder.build())
.setXid(21L);
- final InstanceIdentifier<FlowCapableNode> nodePath = mockedDeviceState.getNodeInstanceIdentifier()
+ final InstanceIdentifier<FlowCapableNode> nodePath = mockedDeviceInfo.getNodeInstanceIdentifier()
.augmentation(FlowCapableNode.class);
final FlowCapableNodeBuilder flowNodeBuilder = new FlowCapableNodeBuilder();
final TableBuilder tableDataBld = new TableBuilder();
private TransmitPacketInput buildTransmitPacketInput() {
TransmitPacketInputBuilder transmitPacketInputBld = new TransmitPacketInputBuilder()
.setBufferId(OFConstants.OFP_NO_BUFFER)
- .setNode(new NodeRef(mockedDeviceState.getNodeInstanceIdentifier()))
+ .setNode(new NodeRef(mockedDeviceInfo.getNodeInstanceIdentifier()))
.setPayload(ULTIMATE_PAYLOAD.getBytes())
.setEgress(new NodeConnectorRef(pathToNodeconnector));
return transmitPacketInputBld.build();
@Override
protected void setup() {
- salExperimenterMessageService = new SalExperimenterMessageServiceImpl(mockedRequestContextStack, mockedDeviceContext);
+ salExperimenterMessageService = new SalExperimenterMessageServiceImpl(mockedRequestContextStack, mockedDeviceContext, extensionConverterProvider);
Mockito.when(mockedDeviceContext.getExtensionConverterProvider()).thenReturn(extensionConverterProvider);
Mockito.when(extensionConverterProvider.getMessageConverter(Matchers.<TypeVersionKey>any()))
.thenReturn(extensionConverter);
private SendExperimenterInput buildSendExperimenterInput() {
SendExperimenterInputBuilder sendExperimenterInputBld = new SendExperimenterInputBuilder()
- .setNode(new NodeRef(mockedDeviceState.getNodeInstanceIdentifier()))
+ .setNode(new NodeRef(mockedDeviceInfo.getNodeInstanceIdentifier()))
.setExperimenterMessageOfChoice(new DummyExperimenter());
return sendExperimenterInputBld.build();
}
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
@Mock
private DeviceState mockedDeviceState;
@Mock
+ private DeviceInfo mockedDeviceInfo;
+ @Mock
private DeviceFlowRegistry deviceFlowRegistry;
@Mock
private GetFeaturesOutput mockedFeaturesOutput;
when(requestContext.getXid()).thenReturn(new Xid(84L));
when(requestContext.getFuture()).thenReturn(RpcResultBuilder.success().buildFuture());
- when(mockedDeviceState.getNodeInstanceIdentifier()).thenReturn(NODE_II);
- when(mockedDeviceState.getFeatures()).thenReturn(mockedFeaturesOutput);
+ when(mockedDeviceInfo.getNodeInstanceIdentifier()).thenReturn(NODE_II);
+ when(mockedDeviceInfo.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
+ when(mockedDeviceInfo.getVersion()).thenReturn(DUMMY_VERSION);
when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
+ when(mockedDeviceContext.getDeviceInfo()).thenReturn(mockedDeviceInfo);
salFlowService = new SalFlowServiceImpl(mockedRequestContextStack, mockedDeviceContext);
}
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock;
import static org.mockito.Mockito.verify;
import com.google.common.collect.Lists;
+import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.port.update.UpdatedPort;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.port.update.UpdatedPortBuilder;
-import java.util.List;
@RunWith(MockitoJUnitRunner.class)
public class SalPortServiceImplTest extends ServiceMocking {
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+
import com.google.common.util.concurrent.ListenableFuture;
import java.math.BigInteger;
import java.util.concurrent.Future;
import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
@Mock
private DeviceState mockDeviceState;
+ @Mock
+ private DeviceInfo mockDeviceInfo;
+
@Mock
private GetFeaturesOutput mockFeaturesOutput;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
- Mockito.when(mockDeviceState.getNodeId()).thenReturn(testNodeId);
- Mockito.when(mockDeviceState.getFeatures()).thenReturn(mockFeaturesOutput);
+ Mockito.when(mockDeviceInfo.getNodeId()).thenReturn(testNodeId);
+ Mockito.when(mockDeviceInfo.getDatapathId()).thenReturn(BigInteger.TEN);
Mockito.when(mockFeaturesOutput.getVersion()).thenReturn(testVersion);
Mockito.when(mockDeviceContext.getDeviceState()).thenReturn(mockDeviceState);
+ Mockito.when(mockDeviceContext.getDeviceInfo()).thenReturn(mockDeviceInfo);
Mockito.when(mockDeviceContext.getPrimaryConnectionContext()).thenReturn(mockConnectionContext);
Mockito.when(mockConnectionContext.getFeatures()).thenReturn(mockFeaturesReply);
Mockito.when(mockConnectionContext.getNodeId()).thenReturn(testNodeId);
package org.opendaylight.openflowplugin.impl.services;
import static org.mockito.Mockito.when;
+
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.math.BigInteger;
import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
@Mock
protected DeviceState mockedDeviceState;
@Mock
+ protected DeviceInfo mockedDeviceInfo;
+ @Mock
protected DeviceInitializationPhaseHandler mockedDevicePhaseHandler;
@Mock
protected RequestContext mockedRequestContext;
when(mockedPrimConnectionContext.getConnectionState()).thenReturn(ConnectionContext.CONNECTION_STATE.WORKING);
when(mockedPrimConnectionContext.getOutboundQueueProvider()).thenReturn(mockedOutboundQueue);
- when(mockedDeviceState.getNodeInstanceIdentifier()).thenReturn(NODE_II);
- when(mockedDeviceState.getFeatures()).thenReturn(mockedFeaturesOutput);
+ when(mockedDeviceInfo.getNodeInstanceIdentifier()).thenReturn(NODE_II);
+ when(mockedDeviceInfo.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
+ when(mockedDeviceInfo.getVersion()).thenReturn(DUMMY_VERSION);
when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimConnectionContext);
when(mockedDeviceContext.getMessageSpy()).thenReturn(mockedMessagSpy);
when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(new DeviceFlowRegistryImpl());
when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
+ when(mockedDeviceContext.getDeviceInfo()).thenReturn(mockedDeviceInfo);
when(mockedDeviceContext.getMultiMsgCollector(Matchers.<RequestContext<List<MultipartReply>>>any())).thenReturn(multiMessageCollector);
setup();
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+
import com.google.common.collect.Lists;
import java.math.BigInteger;
import java.util.Collections;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import java.math.BigInteger;
import org.junit.Before;
-import org.mockito.Mockito;
import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
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.openflow.protocol.rev130731.FeaturesReply;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
StatisticsGatheringService mockedStatisticsGatheringService;
StatisticsGatheringOnTheFlyService mockedStatisticsOnFlyGatheringService;
ConnectionContext mockedConnectionContext;
+ DeviceInfo mockedDeviceInfo;
static final KeyedInstanceIdentifier<Node, NodeKey> dummyNodeII = InstanceIdentifier.create(Nodes.class)
.child(Node.class, new NodeKey(new NodeId("dummyNodeId")));
mockedStatisticsOnFlyGatheringService = mock(StatisticsGatheringOnTheFlyService.class);
mockedConnectionContext = mock(ConnectionContext.class);
mockedDeviceState = mock(DeviceState.class);
+ mockedDeviceInfo = mock(DeviceInfo.class);
final FeaturesReply mockedFeatures = mock(FeaturesReply.class);
final MessageSpy mockedMessageSpy = mock(MessageSpy.class);
final OutboundQueue mockedOutboundQueue = mock(OutboundQueue.class);
final DeviceManager mockedDeviceManager = mock(DeviceManager.class);
- final GetFeaturesOutput mockedFeaturesOutput = mock(GetFeaturesOutput.class);
mockConductor = mock(LifecycleConductor.class);
+ when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
+ when(mockedDeviceContext.getDeviceInfo()).thenReturn(mockedDeviceInfo);
+ when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedConnectionContext);
+ when(mockedDeviceContext.getMessageSpy()).thenReturn(mockedMessageSpy);
+
when(mockedDeviceState.isTableStatisticsAvailable()).thenReturn(isTable);
when(mockedDeviceState.isFlowStatisticsAvailable()).thenReturn(isFlow);
when(mockedDeviceState.isGroupAvailable()).thenReturn(isGroup);
when(mockedDeviceState.isMetersAvailable()).thenReturn(isMeter);
when(mockedDeviceState.isPortStatisticsAvailable()).thenReturn(isPort);
when(mockedDeviceState.isQueueStatisticsAvailable()).thenReturn(isQueue);
- when(mockedDeviceState.getNodeInstanceIdentifier()).thenReturn(dummyNodeII);
- when(mockedDeviceState.getFeatures()).thenReturn(mockedFeaturesOutput);
+ when(mockedDeviceInfo.getNodeInstanceIdentifier()).thenReturn(dummyNodeII);
+ when(mockedDeviceInfo.getDatapathId()).thenReturn(BigInteger.TEN);
when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
+ when(mockedDeviceContext.getDeviceInfo()).thenReturn(mockedDeviceInfo);
when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedConnectionContext);
when(mockedDeviceContext.getMessageSpy()).thenReturn(mockedMessageSpy);
+ when(mockedDeviceInfo.getNodeId()).thenReturn(dummyNodeII.getKey().getId());
when(mockedConnectionContext.getNodeId()).thenReturn(dummyNodeII.getKey().getId());
when(mockedConnectionContext.getFeatures()).thenReturn(mockedFeatures);
when(mockedConnectionContext.getConnectionState()).thenReturn(ConnectionContext.CONNECTION_STATE.WORKING);
when(mockedConnectionContext.getOutboundQueueProvider()).thenReturn(mockedOutboundQueue);
- when(mockedDeviceManager.getDeviceContextFromNodeId(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
- mockConductor.setSafelyDeviceManager(mockedDeviceManager);
- when(mockConductor.getDeviceContext(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
+ mockConductor.setSafelyManager(mockedDeviceManager);
+ when(mockConductor.getDeviceContext(mockedDeviceInfo)).thenReturn(mockedDeviceContext);
}
}
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
+
import com.google.common.util.concurrent.ListenableFuture;
import java.util.Arrays;
import java.util.Collections;
public void gatherDynamicDataTest() {
- final StatisticsContextImpl statisticsContext = new StatisticsContextImpl(mockedDeviceContext.getDeviceState().getNodeId(), false, mockConductor);
+ final StatisticsContextImpl statisticsContext = new StatisticsContextImpl(mockedDeviceInfo, false, mockConductor);
final ListenableFuture<RpcResult<List<MultipartReply>>> rpcResult = immediateFuture(RpcResultBuilder.success(Collections.<MultipartReply>emptyList()).build());
when(mockedStatisticsGatheringService.getStatisticsOfType(any(EventIdentifier.class), any(MultipartType
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.EventIdentifier;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
@Before
public void setUp() throws Exception {
when(mockedDeviceContext.reserveXidForDeviceMessage()).thenReturn(TEST_XID);
- when(mockConductor.getDeviceContext(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
+ when(mockConductor.getDeviceContext(mockedDeviceInfo)).thenReturn(mockedDeviceContext);
initStatisticsContext();
}
private void initStatisticsContext() {
- statisticsContext = new StatisticsContextImpl(mockedDeviceContext.getDeviceState().getNodeId(), false, mockConductor);
+ statisticsContext = new StatisticsContextImpl(mockedDeviceInfo, false, mockConductor);
statisticsContext.setStatisticsGatheringService(mockedStatisticsGatheringService);
statisticsContext.setStatisticsGatheringOnTheFlyService(mockedStatisticsOnFlyGatheringService);
}
*/
@Test
public void testClose() throws Exception {
- final StatisticsContextImpl statisticsContext = new StatisticsContextImpl(mockedDeviceContext.getDeviceState().getNodeId(), false, mockConductor);
+ final StatisticsContextImpl statisticsContext = new StatisticsContextImpl(mockedDeviceInfo, false, mockConductor);
final RequestContext<Object> requestContext = statisticsContext.createRequestContext();
statisticsContext.close();
try {
@Test
public void testGatherDynamicData_all() throws Exception {
Mockito.reset(mockedDeviceState);
- when(mockedDeviceState.getFeatures()).thenReturn(mock(GetFeaturesOutput.class));
when(mockedDeviceState.isTableStatisticsAvailable()).thenReturn(Boolean.TRUE);
when(mockedDeviceState.isFlowStatisticsAvailable()).thenReturn(Boolean.TRUE);
when(mockedDeviceState.isGroupAvailable()).thenReturn(Boolean.TRUE);
when(mockedDeviceState.isMetersAvailable()).thenReturn(Boolean.TRUE);
when(mockedDeviceState.isPortStatisticsAvailable()).thenReturn(Boolean.TRUE);
when(mockedDeviceState.isQueueStatisticsAvailable()).thenReturn(Boolean.TRUE);
- when(mockedDeviceState.getNodeInstanceIdentifier()).thenReturn(dummyNodeII);
+ when(mockedDeviceInfo.getNodeInstanceIdentifier()).thenReturn(dummyNodeII);
initStatisticsContext();
when(mockedStatisticsGatheringService.getStatisticsOfType(Matchers.any(EventIdentifier.class), Matchers.any(MultipartType.class)))
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.CheckedFuture;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.TxFacade;
import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
@RunWith(MockitoJUnitRunner.class)
public class StatisticsGatheringUtilsTest {
- public static final String DUMMY_NODE_ID_VALUE = "1";
- public static final NodeId DUMMY_NODE_ID = new NodeId(DUMMY_NODE_ID_VALUE);
+ static final String DUMMY_NODE_ID_VALUE = "1";
+ static final NodeId DUMMY_NODE_ID = new NodeId(DUMMY_NODE_ID_VALUE);
private final KeyedInstanceIdentifier<Node, NodeKey> dummyNodePath = InstanceIdentifier.create(Nodes.class)
.child(Node.class, new NodeKey(DUMMY_NODE_ID));
private ConnectionContext connectionAdapter;
@Mock
private StatisticsGatherer statisticsService;
+ @Mock
+ private DeviceInfo deviceInfo;
+ @Mock
+ private TxFacade txFacade;
public StatisticsGatheringUtilsTest() {
OpenflowPortsUtil.init();
@Before
public void setUp() throws Exception {
when(deviceContext.getDeviceState()).thenReturn(deviceState);
+ when(deviceContext.getDeviceInfo()).thenReturn(deviceInfo);
when(deviceContext.getDeviceFlowRegistry()).thenReturn(deviceFlowRegistry);
when(deviceContext.getDeviceGroupRegistry()).thenReturn(deviceGroupRegistry);
when(deviceContext.getDeviceMeterRegistry()).thenReturn(deviceMeterRegistry);
when(deviceContext.getReadTransaction()).thenReturn(readTx);
+ when(txFacade.getReadTransaction()).thenReturn(readTx);
when(deviceContext.getPrimaryConnectionContext()).thenReturn(connectionAdapter);
when(connectionAdapter.getNodeId()).thenReturn(DUMMY_NODE_ID);
- when(deviceState.getFeatures()).thenReturn(features);
when(connectionAdapter.getFeatures()).thenReturn(features);
-
- when(features.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
when(features.getDatapathId()).thenReturn(BigInteger.ONE);
+ when(features.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
- when(deviceState.getNodeInstanceIdentifier()).thenReturn(dummyNodePath);
+ when(deviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
+ when(deviceInfo.getDatapathId()).thenReturn(BigInteger.ONE);
+ when(deviceInfo.getNodeInstanceIdentifier()).thenReturn(dummyNodePath);
+ when(deviceInfo.getNodeId()).thenReturn(DUMMY_NODE_ID);
}
@After
final ArgumentCaptor<Flow> flow = ArgumentCaptor.forClass(Flow.class);
StatisticsGatheringUtils.writeFlowStatistics(prepareFlowStatisticsData(),
- deviceContext.getDeviceState(), deviceContext.getDeviceFlowRegistry(), deviceContext);
+ deviceInfo, deviceContext.getDeviceFlowRegistry(), deviceContext);
Mockito.verify(deviceContext).writeToTransaction(
dataStoreType.capture(), flowPath.capture(), flow.capture());
.child(Group.class, new GroupKey(new org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId(groupIdValue)))
.augmentation(NodeGroupStatistics.class)
.child(GroupStatistics.class);
- verify(deviceContext).writeToTransaction(Matchers.eq(LogicalDatastoreType.OPERATIONAL),
+ verify(txFacade).writeToTransaction(Matchers.eq(LogicalDatastoreType.OPERATIONAL),
Matchers.eq(groupPath), Matchers.any(GroupStatistics.class));
}
verify(deviceContext, Mockito.never()).addDeleteToTxChain(Matchers.eq(LogicalDatastoreType.OPERATIONAL), Matchers.<InstanceIdentifier<?>> any());
verify(deviceGroupRegistry).removeMarked();
verify(deviceGroupRegistry).store(storedGroupId);
- verify(deviceContext).writeToTransaction(
+ verify(txFacade).writeToTransaction(
Matchers.eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(groupPath), Matchers.any(Group.class));
}
.child(Meter.class, new MeterKey(new org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId(meterIdValue)))
.augmentation(NodeMeterStatistics.class)
.child(MeterStatistics.class);
- verify(deviceContext).writeToTransaction(Matchers.eq(LogicalDatastoreType.OPERATIONAL),
+ verify(txFacade).writeToTransaction(Matchers.eq(LogicalDatastoreType.OPERATIONAL),
Matchers.eq(meterPath), Matchers.any(MeterStatistics.class));
}
.child(NodeConnector.class, new NodeConnectorKey(new NodeConnectorId("openflow:" + DUMMY_NODE_ID_VALUE + ":11")))
.augmentation(FlowCapableNodeConnectorStatisticsData.class)
.child(FlowCapableNodeConnectorStatistics.class);
- verify(deviceContext).writeToTransaction(
+ verify(txFacade).writeToTransaction(
Matchers.eq(LogicalDatastoreType.OPERATIONAL),
Matchers.eq(portPath),
Matchers.any(FlowCapableNodeConnectorStatistics.class));
.child(Table.class, new TableKey((short) 0))
.augmentation(FlowTableStatisticsData.class)
.child(FlowTableStatistics.class);
- verify(deviceContext).writeToTransaction(
+ verify(txFacade).writeToTransaction(
Matchers.eq(LogicalDatastoreType.OPERATIONAL),
Matchers.eq(tablePath),
Matchers.any(FlowTableStatistics.class));
.child(NodeConnector.class, new NodeConnectorKey(new NodeConnectorId("openflow:" + DUMMY_NODE_ID_VALUE + ":11")))
.augmentation(FlowCapableNodeConnector.class)
.child(Queue.class, new QueueKey(new QueueId(queueIdValue)));
- verify(deviceContext).writeToTransaction(
+ verify(txFacade).writeToTransaction(
Matchers.eq(LogicalDatastoreType.OPERATIONAL),
Matchers.eq(queuePath),
Matchers.any(Queue.class));
@Test
public void testGatherStatistics_flow() throws Exception {
+ final short tableId = 0;
final MultipartType type = MultipartType.OFPMPFLOW;
when(deviceFlowRegistry.storeIfNecessary(Matchers.any(FlowRegistryKey.class), Matchers.anyShort()))
.thenReturn(new FlowId("openflow:21"));
+ final InstanceIdentifier<FlowCapableNode> nodePath = deviceInfo.getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
+ final TableBuilder tableDataBld = new TableBuilder();
+ tableDataBld.setId(tableId);
+ final FlowCapableNodeBuilder flowNodeBuilder = new FlowCapableNodeBuilder();
+ flowNodeBuilder.setTable(Collections.singletonList(tableDataBld.build()));
+ final Optional<FlowCapableNode> flowNodeOpt = Optional.of(flowNodeBuilder.build());
+ final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowNodeFuture = Futures.immediateCheckedFuture(flowNodeOpt);
+ when(readTx.read(LogicalDatastoreType.OPERATIONAL, nodePath)).thenReturn(flowNodeFuture);
+
final org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.MatchBuilder matchBld =
new org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.MatchBuilder()
.setMatchEntry(Collections.<MatchEntry>emptyList());
.child(Flow.class, new FlowKey(new FlowId("openflow:21")));
verify(deviceContext, Mockito.never()).addDeleteToTxChain(Matchers.eq(LogicalDatastoreType.OPERATIONAL), Matchers.<InstanceIdentifier<?>>any());
verify(deviceFlowRegistry).storeIfNecessary(FlowRegistryKeyFactory.create(flowBld.build()), (short) 0);
- verify(deviceContext).writeToTransaction(Matchers.eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(flowPath), Matchers.any(Flow.class));
+ verify(txFacade).writeToTransaction(Matchers.eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(flowPath), Matchers.any(Flow.class));
}
@Test
.child(Meter.class, new MeterKey(meterId));
verify(deviceContext, Mockito.never()).addDeleteToTxChain(Matchers.eq(LogicalDatastoreType.OPERATIONAL), Matchers.<InstanceIdentifier<?>>any());
verify(deviceMeterRegistry).store(meterId);
- verify(deviceContext).writeToTransaction(Matchers.eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(meterPath), Matchers.any(Meter.class));
+ verify(txFacade).writeToTransaction(Matchers.eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(meterPath), Matchers.any(Meter.class));
}
private void fireAndCheck(final MultipartType type, final List<MultipartReply> statsData) throws InterruptedException, ExecutionException, TimeoutException {
when(statisticsService.getStatisticsOfType(Matchers.any(EventIdentifier.class), Matchers.eq(type)))
.thenReturn(Futures.immediateFuture(RpcResultBuilder.success(statsData).build()));
- final ListenableFuture<Boolean> gatherStatisticsResult = StatisticsGatheringUtils.gatherStatistics(statisticsService, deviceContext, type);
+ final ListenableFuture<Boolean> gatherStatisticsResult = StatisticsGatheringUtils.gatherStatistics(
+ statisticsService,
+ deviceInfo,
+ type,
+ txFacade,
+ deviceContext,
+ false);
Assert.assertTrue(gatherStatisticsResult.get(1, TimeUnit.SECONDS).booleanValue());
- verify(deviceContext).submitTransaction();
+ verify(txFacade).submitTransaction();
}
private static MultipartReplyMessage assembleMPReplyMessage(final MultipartType type, final MultipartReplyBody mpReplyGroupCaseBld) {
return new BucketStatsBuilder().setByteCount(BigInteger.valueOf(byteCount)).setPacketCount(BigInteger.valueOf(packetCount)).build();
}
- @Test
- public void testDeleteAllKnownFlowsNotSync() throws Exception {
- when(deviceState.deviceSynchronized()).thenReturn(false);
- StatisticsGatheringUtils.deleteAllKnownFlows(deviceContext.getDeviceState(),
- deviceContext.getDeviceFlowRegistry(), deviceContext);
- Mockito.verifyNoMoreInteractions(deviceFlowRegistry);
- }
-
@Test
public void testDeleteAllKnownFlows() throws Exception {
final short tableId = 0;
when(deviceState.deviceSynchronized()).thenReturn(true);
- final InstanceIdentifier<FlowCapableNode> nodePath = deviceState.getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
+ final InstanceIdentifier<FlowCapableNode> nodePath = deviceInfo.getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
final TableBuilder tableDataBld = new TableBuilder();
tableDataBld.setId(tableId);
final FlowCapableNodeBuilder flowNodeBuilder = new FlowCapableNodeBuilder();
final Optional<FlowCapableNode> flowNodeOpt = Optional.of(flowNodeBuilder.build());
final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowNodeFuture = Futures.immediateCheckedFuture(flowNodeOpt);
when(readTx.read(LogicalDatastoreType.OPERATIONAL, nodePath)).thenReturn(flowNodeFuture);
- final KeyedInstanceIdentifier<Table, TableKey> tablePath = deviceState.getNodeInstanceIdentifier()
+ final KeyedInstanceIdentifier<Table, TableKey> tablePath = deviceInfo.getNodeInstanceIdentifier()
.augmentation(FlowCapableNode.class).child(Table.class, new TableKey(tableId));
- StatisticsGatheringUtils.deleteAllKnownFlows(deviceContext.getDeviceState(),
- deviceContext.getDeviceFlowRegistry(), deviceContext);
+ StatisticsGatheringUtils.deleteAllKnownFlows(deviceInfo,
+ deviceContext.getDeviceFlowRegistry(), txFacade);
- verify(deviceContext).writeToTransaction(
+ verify(txFacade).writeToTransaction(
LogicalDatastoreType.OPERATIONAL,
tablePath,
tableDataBld.setFlow(Collections.<Flow>emptyList()).build());
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import com.google.common.base.Optional;
+
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import io.netty.util.HashedWheelTimer;
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.junit.Assert;
import org.junit.Before;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
private static final BigInteger DUMMY_DATAPATH_ID = new BigInteger("444");
private static final Short DUMMY_VERSION = OFConstants.OFP_VERSION_1_3;
+ public static final NodeId NODE_ID = new NodeId("ofp-unit-dummy-node-id");
@Mock
RequestContextStack mockedRequestContextStack;
@Mock
DeviceState mockedDeviceState;
@Mock
+ DeviceInfo mockedDeviceInfo;
+ @Mock
DeviceInitializationPhaseHandler mockedDevicePhaseHandler;
@Mock
DeviceTerminationPhaseHandler mockedTerminationPhaseHandler;
private GetFeaturesOutput featuresOutput;
@Mock
private DeviceInitializationPhaseHandler deviceInitializationPhaseHandler;
+ @Mock
+ private DeviceInfo deviceInfo;
private RequestContext<List<MultipartReply>> currentRequestContext;
private StatisticsManagerImpl statisticsManager;
.create(Nodes.class)
.child(Node.class, new NodeKey(new NodeId("openflow:10")));
- when(mockedFeatures.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
- when(mockedFeatures.getVersion()).thenReturn(DUMMY_VERSION);
- when(mockedFeaturesOutput.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
- when(mockedFeaturesOutput.getVersion()).thenReturn(DUMMY_VERSION);
-
when(mockedPrimConnectionContext.getFeatures()).thenReturn(mockedFeatures);
when(mockedPrimConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
when(mockedPrimConnectionContext.getConnectionState()).thenReturn(ConnectionContext.CONNECTION_STATE.WORKING);
- when(mockedPrimConnectionContext.getNodeId()).thenReturn(new NodeId("ut-node:123"));
+ when(mockedPrimConnectionContext.getNodeId()).thenReturn(NODE_ID);
when(mockedPrimConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueue);
when(mockedDeviceState.isFlowStatisticsAvailable()).thenReturn(Boolean.TRUE);
when(mockedDeviceState.isPortStatisticsAvailable()).thenReturn(Boolean.TRUE);
when(mockedDeviceState.isQueueStatisticsAvailable()).thenReturn(Boolean.TRUE);
when(mockedDeviceState.isTableStatisticsAvailable()).thenReturn(Boolean.TRUE);
- when(mockedDeviceState.getFeatures()).thenReturn(featuresOutput);
- when(mockedDeviceState.getNodeInstanceIdentifier()).thenReturn(nodePath);
-
- when(mockedDeviceState.getNodeId()).thenReturn(new NodeId("ofp-unit-dummy-node-id"));
+ when(mockedDeviceInfo.getNodeInstanceIdentifier()).thenReturn(nodePath);
+ when(mockedDeviceInfo.getDatapathId()).thenReturn(BigInteger.TEN);
+ when(mockedDeviceInfo.getNodeId()).thenReturn(new NodeId("ofp-unit-dummy-node-id"));
+ when(mockedDeviceContext.getDeviceInfo()).thenReturn(mockedDeviceInfo);
when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimConnectionContext);
when(mockedDeviceContext.getMessageSpy()).thenReturn(mockedMessagSpy);
when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(new DeviceFlowRegistryImpl());
statisticsManager = new StatisticsManagerImpl(rpcProviderRegistry, false, conductor);
statisticsManager.setDeviceInitializationPhaseHandler(deviceInitializationPhaseHandler);
- when(deviceManager.getDeviceContextFromNodeId(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
- when(conductor.getDeviceContext(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
+ when(conductor.getDeviceContext(deviceInfo)).thenReturn(mockedDeviceContext);
}
@Test
.commitEntry(Matchers.anyLong(), Matchers.<OfHeader>any(), Matchers.<FutureCallback<OfHeader>>any());
statisticsManager.setDeviceInitializationPhaseHandler(mockedDevicePhaseHandler);
- statisticsManager.onDeviceContextLevelUp(mockedDeviceContext.getDeviceState().getNodeId());
- verify(mockedDevicePhaseHandler).onDeviceContextLevelUp(mockedDeviceContext.getDeviceState().getNodeId());
+ statisticsManager.onDeviceContextLevelUp(deviceInfo);
+ verify(mockedDevicePhaseHandler).onDeviceContextLevelUp(deviceInfo);
}
@Test
public void testOnDeviceContextClosed() throws Exception {
final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
- final Map<NodeId, StatisticsContext> contextsMap = getContextsMap(statisticsManager);
+ final Map<DeviceInfo, StatisticsContext> contextsMap = getContextsMap(statisticsManager);
- contextsMap.put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
+ contextsMap.put(deviceInfo, statisticContext);
Assert.assertEquals(1, contextsMap.size());
statisticsManager.setDeviceTerminationPhaseHandler(mockedTerminationPhaseHandler);
- statisticsManager.onDeviceContextLevelDown(mockedDeviceContext);
+ statisticsManager.onDeviceContextLevelDown(deviceInfo);
verify(statisticContext).close();
- verify(mockedTerminationPhaseHandler).onDeviceContextLevelDown(mockedDeviceContext);
+ verify(mockedTerminationPhaseHandler).onDeviceContextLevelDown(deviceInfo);
Assert.assertEquals(0, contextsMap.size());
}
- private static Map<NodeId, StatisticsContext> getContextsMap(final StatisticsManagerImpl statisticsManager)
+ private static Map<DeviceInfo, StatisticsContext> getContextsMap(final StatisticsManagerImpl statisticsManager)
throws NoSuchFieldException, IllegalAccessException {
// HACK: contexts map for testing shall be accessed in some more civilized way
final Field contextsField = StatisticsManagerImpl.class.getDeclaredField("contexts");
Assert.assertNotNull(contextsField);
contextsField.setAccessible(true);
- return (Map<NodeId, StatisticsContext>) contextsField.get(statisticsManager);
+ return (Map<DeviceInfo, StatisticsContext>) contextsField.get(statisticsManager);
}
@Test
@Test
public void testChangeStatisticsWorkMode1() throws Exception {
final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
- when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
when(statisticContext.getPollTimeout()).thenReturn(
- Optional.<Timeout>absent());
+ Optional.<Timeout>empty());
when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
Collections.<ItemLifeCycleSource>emptyList());
- getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
+ getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
new ChangeStatisticsWorkModeInputBuilder()
Mockito.verify(statisticContext).getPollTimeout();
}
- private static void checkWorkModeChangeOutcome(Future<RpcResult<Void>> workMode) throws InterruptedException, java.util.concurrent.ExecutionException {
+ private static void checkWorkModeChangeOutcome(Future<RpcResult<Void>> workMode) throws InterruptedException, ExecutionException {
Assert.assertTrue(workMode.isDone());
Assert.assertTrue(workMode.get().isSuccessful());
}
final Timeout pollTimeout = Mockito.mock(Timeout.class);
final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
- when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
when(statisticContext.getPollTimeout()).thenReturn(
Optional.of(pollTimeout));
when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
Collections.singletonList(itemLifecycleSource));
- getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
+ getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
new ChangeStatisticsWorkModeInputBuilder()
.setItemLifecycleListener(itemLifeCycleListenerCapt.capture());
final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
- when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
when(statisticContext.getPollTimeout()).thenReturn(
Optional.of(pollTimeout));
when(statisticContext.getItemLifeCycleListener()).thenReturn(
when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
Collections.singletonList(itemLifecycleSource));
- getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
+ getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
new ChangeStatisticsWorkModeInputBuilder()
@Test
public void testCalculateTimerDelay() throws Exception {
final TimeCounter timeCounter = Mockito.mock(TimeCounter.class);
- when(timeCounter.getAverageTimeBetweenMarks()).thenReturn((Long)2000L, (Long)4000L);
+ when(timeCounter.getAverageTimeBetweenMarks()).thenReturn(2000L, (Long)4000L);
statisticsManager.calculateTimerDelay(timeCounter);
Assert.assertEquals(3000L, StatisticsManagerImpl.getCurrentTimerDelay());
final StatisticsContext statisticsContext = Mockito.mock(StatisticsContext.class);
final TimeCounter mockTimerCounter = Mockito.mock(TimeCounter.class);
- statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
+ statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
verify(mockedDeviceContext).getDeviceState();
when(mockedDeviceContext.getDeviceState().isValid()).thenReturn(true);
- statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
- // TODO Make scheduleNextPolling visible for tests?
+ statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
when(mockedDeviceContext.getDeviceState().isStatisticsPollingEnabled()).thenReturn(true);
- statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
- // TODO Make scheduleNextPolling visible for tests?
+ statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateCheckedFuture(Boolean.TRUE));
when(statisticsContext.isSchedulingEnabled()).thenReturn(Boolean.TRUE);
- statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
+ statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
Mockito.verify(mockTimerCounter).markStart();
Mockito.verify(mockTimerCounter).addTimeMark();
when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateFailedFuture(new Throwable("error msg")));
- statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
+ statisticsManager.pollStatistics(mockedDeviceContext.getDeviceState(), statisticsContext, mockTimerCounter, mockedDeviceInfo);
Mockito.verify(mockTimerCounter,times(2)).addTimeMark();
}
}
\ No newline at end of file
package org.opendaylight.openflowplugin.impl.statistics.ofpspecific;
import static org.junit.Assert.assertTrue;
+
import java.util.List;
import org.junit.Test;
import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
protected TranslatorLibrary translatorLibrary;
@Mock
protected DeviceState deviceState;
+ @Mock
+ protected DeviceInfo deviceInfo;
public static final NodeId NODE_ID = new NodeId("unit-test-node:123");
Mockito.when(deviceContext.getMultiMsgCollector(Matchers.any(RequestContext.class))).thenReturn(multiMsgCollector);
Mockito.when(deviceContext.oook()).thenReturn(translatorLibrary);
Mockito.when(deviceContext.getDeviceState()).thenReturn(deviceState);
- Mockito.when(deviceState.getNodeId()).thenReturn(NODE_ID);
- Mockito.when(deviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
- Mockito.when(deviceState.getFeatures()).thenReturn(getFeaturesOutput);
+ Mockito.when(deviceContext.getDeviceInfo()).thenReturn(deviceInfo);
+ Mockito.when(deviceInfo.getNodeId()).thenReturn(NODE_ID);
+ Mockito.when(deviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
+ Mockito.when(deviceInfo.getDatapathId()).thenReturn(BigInteger.TEN);
Mockito.when(connectionContext.getFeatures()).thenReturn(features);
Mockito.when(connectionContext.getOutboundQueueProvider()).thenReturn(outboundQueueProvider);
Mockito.when(features.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
}
).when(multiMsgCollector).endCollecting(Matchers.any(EventIdentifier.class));
Mockito.when(translator.translate(
- Matchers.any(MultipartReply.class), Matchers.same(deviceState), Matchers.isNull())
+ Matchers.any(MultipartReply.class), Matchers.same(deviceInfo), Matchers.isNull())
).thenReturn(new AggregatedFlowStatisticsBuilder().build());
import org.mockito.stubbing.Answer;
import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
import org.opendaylight.openflowplugin.api.OFConstants;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
@Mock
private DeviceState deviceState;
@Mock
+ private DeviceInfo deviceInfo;
+ @Mock
private MessageTranslator<Object, Object> translator;
@Mock
private GetFeaturesOutput featuresOutput;
Mockito.when(featuresOutput.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
Mockito.when(rqContextStack.<Object>createRequestContext()).thenReturn(rqContext);
Mockito.when(deviceContext.getDeviceState()).thenReturn(deviceState);
- Mockito.when(deviceState.getNodeId()).thenReturn(NODE_ID);
- Mockito.when(deviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
- Mockito.when(deviceState.getFeatures()).thenReturn(featuresOutput);
+ Mockito.when(deviceContext.getDeviceInfo()).thenReturn(deviceInfo);
+ Mockito.when(deviceInfo.getNodeId()).thenReturn(NODE_ID);
+ Mockito.when(deviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
Mockito.doAnswer(closeRequestFutureAnswer).when(multiMsgCollector).endCollecting();
Mockito.doAnswer(closeRequestFutureAnswer).when(multiMsgCollector).endCollecting(Matchers.any(EventIdentifier.class));
.setFlowCount(new Counter32(12L))
.setPacketCount(new Counter64(BigInteger.valueOf(13L)))
.build();
- Mockito.when(translator.translate(Matchers.any(MultipartReply.class), Matchers.eq(deviceState), Matchers.any()))
+ Mockito.when(translator.translate(Matchers.any(MultipartReply.class), Matchers.eq(deviceInfo), Matchers.any()))
.thenReturn(aggregatedStats);
.setNode(createNodeRef("unitProt:123"))
.setTableId(new TableId((short) 1));
- Mockito.when(translator.translate(Matchers.any(MultipartReply.class), Matchers.eq(deviceState), Matchers.any()))
+ Mockito.when(translator.translate(Matchers.any(MultipartReply.class), Matchers.eq(deviceInfo), Matchers.any()))
.thenReturn(new AggregatedFlowStatisticsBuilder()
.setByteCount(new Counter64(BigInteger.valueOf(50L)))
.setPacketCount(new Counter64(BigInteger.valueOf(51L)))
protected void setup() {
statisticsGatheringService = new StatisticsGatheringOnTheFlyService(mockedRequestContextStack, mockedDeviceContext);
Mockito.doReturn(NODE_ID).when(mockedPrimConnectionContext).getNodeId();
- Mockito.when(mockedDeviceContext.getDeviceState().getNodeId()).thenReturn(NODE_ID);
+ Mockito.when(mockedDeviceInfo.getNodeId()).thenReturn(NODE_ID);
+ Mockito.when(mockedDeviceContext.getDeviceInfo().getNodeId()).thenReturn(NODE_ID);
}
@Test
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
+
+import java.math.BigInteger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
-import java.math.BigInteger;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.when;
-
@RunWith(MockitoJUnitRunner.class)
public abstract class AbstractDirectStatisticsServiceTest {
protected static final Long PORT_NO = 1L;
@Mock
protected DeviceState deviceState;
@Mock
+ protected DeviceInfo deviceInfo;
+ @Mock
protected GetFeaturesOutput getFeaturesOutput;
protected NodeConnectorId nodeConnectorId;
when(deviceContext.getMultiMsgCollector(any())).thenReturn(multiMsgCollector);
when(deviceContext.oook()).thenReturn(translatorLibrary);
when(deviceContext.getDeviceState()).thenReturn(deviceState);
- when(deviceContext.getDeviceState()).thenReturn(deviceState);
- when(deviceState.getNodeInstanceIdentifier()).thenReturn(nodeInstanceIdentifier);
- when(deviceState.getNodeId()).thenReturn(new NodeId(NODE_ID));
- when(deviceState.getVersion()).thenReturn(OF_VERSION);
- when(deviceState.getFeatures()).thenReturn(getFeaturesOutput);
+ when(deviceContext.getDeviceInfo()).thenReturn(deviceInfo);
+ when(deviceInfo.getNodeInstanceIdentifier()).thenReturn(nodeInstanceIdentifier);
+ when(deviceInfo.getNodeId()).thenReturn(new NodeId(NODE_ID));
+ when(deviceInfo.getVersion()).thenReturn(OF_VERSION);
+ when(deviceInfo.getDatapathId()).thenReturn(DATAPATH_ID);
when(getFeaturesOutput.getVersion()).thenReturn(OF_VERSION);
when(getFeaturesOutput.getDatapathId()).thenReturn(DATAPATH_ID);
when(connectionContext.getFeatures()).thenReturn(features);
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
import org.opendaylight.yang.gen.v1.urn.opendaylight.direct.statistics.rev160511.GetFlowStatisticsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestFlowCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.flow._case.MultipartRequestFlow;
-import java.math.BigInteger;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
public class FlowDirectStatisticsServiceTest extends AbstractDirectStatisticsServiceTest {
static final Short TABLE_NO = 1;
private FlowDirectStatisticsService service;
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.List;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.direct.statistics.rev160511.GetGroupStatisticsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.direct.statistics.rev160511.GetGroupStatisticsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestGroupCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.group._case.MultipartRequestGroup;
-import java.math.BigInteger;
-import java.util.Arrays;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
public class GroupDirectStatisticsServiceTest extends AbstractDirectStatisticsServiceTest {
static final Long GROUP_NO = 1L;
private GroupDirectStatisticsService service;
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.List;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.direct.statistics.rev160511.GetMeterStatisticsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.direct.statistics.rev160511.GetMeterStatisticsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestMeterCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.meter._case.MultipartRequestMeter;
-import java.math.BigInteger;
-import java.util.Arrays;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
public class MeterDirectStatisticsServiceTest extends AbstractDirectStatisticsServiceTest {
static final Long METER_NO = 1L;
private MeterDirectStatisticsService service;
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.List;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.direct.statistics.rev160511.GetNodeConnectorStatisticsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.direct.statistics.rev160511.GetNodeConnectorStatisticsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.port.stats._case.MultipartRequestPortStats;
import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMap;
-import java.math.BigInteger;
-import java.util.Arrays;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
public class NodeConnectorDirectStatisticsServiceTest extends AbstractDirectStatisticsServiceTest {
private NodeConnectorDirectStatisticsService service;
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opendaylight.yangtools.yang.common.RpcError;
import org.opendaylight.yangtools.yang.common.RpcResult;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
@RunWith(MockitoJUnitRunner.class)
public class OpendaylightDirectStatisticsServiceImplTest {
@Mock
package org.opendaylight.openflowplugin.impl.statistics.services.direct;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.math.BigInteger;
+import java.util.Arrays;
+import java.util.List;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.direct.statistics.rev160511.GetQueueStatisticsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.direct.statistics.rev160511.GetQueueStatisticsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.queue._case.MultipartRequestQueue;
import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.queue.id.and.statistics.map.QueueIdAndStatisticsMap;
-import java.math.BigInteger;
-import java.util.Arrays;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
public class QueueDirectStatisticsServiceTest extends AbstractDirectStatisticsServiceTest {
static final Long QUEUE_NO = 1L;
private QueueDirectStatisticsService service;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
-import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.get.aggregate.flow.statistics.from.flow.table._for.given.match.output.AggregatedFlowStatistics;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyAggregateCaseBuilder;
private AggregatedFlowStatisticsTranslator translator;
@Mock
- private DeviceState deviceState;
+ private DeviceInfo deviceInfo;
@Before
public void setUp() throws Exception {
MultipartReplyMessageBuilder mpInputBld = new MultipartReplyMessageBuilder()
.setMultipartReplyBody(inputBld.build());
- final AggregatedFlowStatistics statistics = translator.translate(mpInputBld.build(), deviceState, null);
+ final AggregatedFlowStatistics statistics = translator.translate(mpInputBld.build(), deviceInfo, null);
Assert.assertEquals(aggregateStatsValueBld.getByteCount(), statistics.getByteCount().getValue());
Assert.assertEquals(aggregateStatsValueBld.getFlowCount(), statistics.getFlowCount().getValue());
import java.math.BigInteger;
import java.util.Collections;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.FlowWildcardsV10;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.TableId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntry;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.MatchBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.v10.grouping.MatchV10Builder;
@Mock
private DeviceState deviceState;
+ @Mock
+ private DeviceInfo deviceInfo;
+
@Mock
private GetFeaturesOutput features;
translatorV10 = new FlowRemovedV10Translator();
when(deviceContext.getDeviceState()).thenReturn(deviceState);
- when(deviceState.getNodeInstanceIdentifier()).thenReturn(nodeId);
- when(deviceState.getFeatures()).thenReturn(features);
+ when(deviceInfo.getNodeInstanceIdentifier()).thenReturn(nodeId);
when(features.getDatapathId()).thenReturn(BigInteger.TEN);
}
@Test
public void testTranslate() throws Exception {
org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved flowRemovedMessage = buildMessage(false);
- final FlowRemoved flowRemoved = translator.translate(flowRemovedMessage, deviceState, null);
+ final FlowRemoved flowRemoved = translator.translate(flowRemovedMessage, deviceInfo, null);
assertEquals(flowRemovedMessage.getCookie(), flowRemoved.getCookie().getValue());
assertEquals(flowRemovedMessage.getPriority(), flowRemoved.getPriority());
@Test
public void testTranslateV10() throws Exception {
org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved flowRemovedMessage = buildMessage(true);
- final FlowRemoved flowRemoved = translatorV10.translate(flowRemovedMessage, deviceState, null);
+ final FlowRemoved flowRemoved = translatorV10.translate(flowRemovedMessage, deviceInfo, null);
assertEquals(flowRemovedMessage.getCookie(), flowRemoved.getCookie().getValue());
assertEquals(flowRemovedMessage.getPriority(), flowRemoved.getPriority());
builder.setMatchV10(new MatchV10Builder().setWildcards(flowWildcards).build());
} else {
builder.setMatch(new MatchBuilder().setMatchEntry(Collections.<MatchEntry>emptyList()).build())
- .setTableId(new TableId(42l));
+ .setTableId(new TableId(42L));
}
return builder.build();
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
-
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.openflow.md.util.OpenflowPortsUtil;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
@Mock
DeviceContext deviceContext;
@Mock
+ DeviceInfo deviceInfo;
+ @Mock
List<PhyPort> phyPorts;
@Mock
PhyPort phyPort;
Mockito.when(connectionContext.getFeatures()).thenReturn(featuresReply);
Mockito.when(featuresReply.getDatapathId()).thenReturn(BigInteger.TEN);
Mockito.when(deviceContext.getDeviceState()).thenReturn(deviceState);
- Mockito.when(deviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
- Mockito.when(deviceState.getFeatures()).thenReturn(getFeaturesOutput);
+ Mockito.when(deviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
+ Mockito.when(deviceInfo.getDatapathId()).thenReturn(BigInteger.TEN);
Mockito.when(getFeaturesOutput.getDatapathId()).thenReturn(BigInteger.TEN);
Mockito.when(getFeaturesOutput.getPhyPort()).thenReturn(phyPorts);
Mockito.when(phyPort.getPortNo()).thenReturn(PORT_NO_DS);
.child(Node.class, new NodeKey(new NodeId("openflow:10")));
final PacketReceivedTranslator packetReceivedTranslator = new PacketReceivedTranslator();
final PacketInMessage packetInMessage = createPacketInMessage(DATA.getBytes(), PORT_NO);
- Mockito.when(deviceState.getNodeInstanceIdentifier()).thenReturn(nodePath);
+ Mockito.when(deviceInfo.getNodeInstanceIdentifier()).thenReturn(nodePath);
- final PacketReceived packetReceived = packetReceivedTranslator.translate(packetInMessage, deviceState, null);
+ final PacketReceived packetReceived = packetReceivedTranslator.translate(packetInMessage, deviceInfo, null);
Assert.assertArrayEquals(packetInMessage.getData(), packetReceived.getPayload());
Assert.assertEquals("org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.SendToController",
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
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.FlowCapableNodeConnector;
private DeviceContext deviceContext;
@Mock
private DeviceState deviceState;
+ @Mock
+ private DeviceInfo deviceInfo;
private org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortConfig portConfig;
private StateBuilder portStateBld;
@Before
public void setUp() throws Exception {
- Mockito.when(deviceContext.getDeviceState()).thenReturn(deviceState);
+ Mockito.when(deviceContext.getDeviceInfo()).thenReturn(deviceInfo);
portUpdateTranslator = new PortUpdateTranslator();
portStateBld = new StateBuilder().setLive(true);
@Test
public void testTranslate_13() throws Exception {
- Mockito.when(deviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
+ Mockito.when(deviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
final org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures portFeatures =
org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures
.getDefaultInstance("hundredGbFd");
- final FlowCapableNodeConnector nodeConnector = portUpdateTranslator.translate(portBld.build(), deviceState, null);
+ final FlowCapableNodeConnector nodeConnector = portUpdateTranslator.translate(portBld.build(), deviceInfo, null);
commonCheck(nodeConnector);
@Test
public void testTranslate_10() throws Exception {
- Mockito.when(deviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_0);
+ Mockito.when(deviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_0);
final org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures portFeatures =
new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures(
null, null, null, false, false, true, null, null,
null, false, false, null, null, null, null, null
);
- final FlowCapableNodeConnector nodeConnector = portUpdateTranslator.translate(portBld.build(), deviceState, null);
+ final FlowCapableNodeConnector nodeConnector = portUpdateTranslator.translate(portBld.build(), deviceInfo, null);
commonCheck(nodeConnector);
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
-
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opendaylight.openflowplugin.api.OFConstants;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
@Mock
private DeviceContextImpl mockedDeviceContext;
@Mock
+ private DeviceInfo mockedDeviceInfo;
+ @Mock
private DeviceInitializationUtils deviceInitializationUtils;
+ @Mock
+ private DeviceInfo deviceInfo;
@Before
public void setUp() throws Exception {
when(mockConnectionContext.getFeatures()).thenReturn(mockFeatures);
when(mockConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockConnectionContext);
+ when(mockedDeviceContext.getDeviceInfo()).thenReturn(mockedDeviceInfo);
final Capabilities capabilitiesV13 = mock(Capabilities.class);
final CapabilitiesV10 capabilitiesV10 = mock(CapabilitiesV10.class);
GetFeaturesOutput mockedFeatures = mock(GetFeaturesOutput.class);
when(mockedFeatures.getTables()).thenReturn((short) 2);
- when(mockedDeviceState.getFeatures()).thenReturn(mockedFeatures);
- when(mockedDeviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_0);
+ when(mockedDeviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_0);
- when(mockedDeviceState.getNodeInstanceIdentifier()).thenReturn(DUMMY_NODE_II);
+ when(mockedDeviceInfo.getNodeInstanceIdentifier()).thenReturn(DUMMY_NODE_II);
when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
when(mockedDeviceContext.getMultiMsgCollector(Mockito.any(RequestContext.class))).thenReturn(msgCollector);
when(mockedDeviceContext.oook()).thenReturn(tLibrary);
final GetFeaturesOutput mockedFeatures = mock(GetFeaturesOutput.class);
when(mockedFeatures.getTables()).thenReturn((short) 2);
- when(mockedDeviceState.getFeatures()).thenReturn(mockedFeatures);
+ when(mockConnectionContext.getFeatures()).thenReturn(mockedFeatures);
- when(mockedDeviceState.getNodeInstanceIdentifier()).thenReturn(DUMMY_NODE_II);
+ when(mockedDeviceInfo.getNodeInstanceIdentifier()).thenReturn(DUMMY_NODE_II);
when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
final RpcResult<List<MultipartReply>> mockedRpcResult = mock(RpcResult.class);
when(mockedPrimaryConnectionContext.getFeatures()).thenReturn(mockedFeatures);
when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimaryConnectionContext);
final DeviceState mockedDeviceState = mock(DeviceState.class);
- when(mockedDeviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_0);
+ when(mockedDeviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_0);
when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
final MessageTranslator mockedTranslator = mock(MessageTranslator.class);
when(translatorLibrary.lookupTranslator(any(TranslatorKey.class))).thenReturn(mockedTranslator);
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import java.math.BigInteger;
import org.junit.Test;
import org.mockito.Matchers;
import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
+import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
import org.opendaylight.yangtools.yang.binding.RpcService;
final ConnectionContext mockedConnectionContext = mock(ConnectionContext.class);
final DeviceState mockedDeviceState = mock(DeviceState.class);
+ final DeviceInfo mockedDeviceInfo = mock(DeviceInfo.class);
when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
+ when(mockedDeviceContext.getDeviceInfo()).thenReturn(mockedDeviceInfo);
final FeaturesReply mockedFeatures = mock(FeaturesReply.class);
when(mockedConnectionContext.getFeatures()).thenReturn(mockedFeatures);
- final GetFeaturesOutput mockedFeaturesOutput = mock(GetFeaturesOutput.class);
- when(mockedDeviceState.getFeatures()).thenReturn(mockedFeaturesOutput);
-
final BigInteger mockedDataPathId = mock(BigInteger.class);
when(mockedFeatures.getDatapathId()).thenReturn(mockedDataPathId);
- when(mockedFeaturesOutput.getDatapathId()).thenReturn(mockedDataPathId);
+ when(mockedDeviceInfo.getDatapathId()).thenReturn(mockedDataPathId);
when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedConnectionContext);
- MdSalRegistrationUtils.registerMasterServices(mockedRpcContext, mockedDeviceContext, OfpRole.BECOMEMASTER);
+
+ final ExtensionConverterProvider extensionConverterProvider = mock(ExtensionConverterProvider.class);
+ MdSalRegistrationUtils.registerMasterServices(mockedRpcContext, mockedDeviceContext, OfpRole.BECOMEMASTER, extensionConverterProvider);
verify(mockedRpcContext, times(NUMBER_OF_RPC_SERVICE_REGISTRATION)).registerRpcServiceImplementation(
Matchers.<Class<RpcService>> any(), any(RpcService.class));
}