From: Jozef Bacigal Date: Mon, 3 Jul 2017 11:45:17 +0000 (+0200) Subject: Remove He-design statistics manager X-Git-Tag: release/nitrogen~38^2 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?a=commitdiff_plain;h=9caf2f230e8f11ac1ca4f77341d1e27dcc37553e;p=openflowplugin.git Remove He-design statistics manager See also:Bug8656 Change-Id: Ie7f2be3af703303691a31aa40eaae31d4ea35eb9 Signed-off-by: Jozef Bacigal --- diff --git a/applications/pom.xml b/applications/pom.xml index 8547f7f34a..b17a24b17e 100644 --- a/applications/pom.xml +++ b/applications/pom.xml @@ -91,7 +91,6 @@ notification-supplier inventory-manager - statistics-manager topology-manager forwardingrules-manager forwardingrules-sync diff --git a/applications/statistics-manager/pom.xml b/applications/statistics-manager/pom.xml deleted file mode 100644 index d50b3c10f4..0000000000 --- a/applications/statistics-manager/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - 4.0.0 - - org.opendaylight.openflowplugin - applications - 0.5.0-SNAPSHOT - - org.opendaylight.openflowplugin.applications - statistics-manager - bundle - - - - com.google.guava - guava - - - - junit - junit - - - org.opendaylight.controller - sal-binding-broker-impl - test - - - org.opendaylight.controller - sal-binding-broker-impl - ${mdsal.version} - test - test-jar - - - org.opendaylight.controller - sal-binding-api - - - org.opendaylight.controller - sal-binding-config - - - org.opendaylight.controller - sal-common-util - - - org.opendaylight.openflowplugin.model - model-flow-base - - - org.opendaylight.openflowplugin.model - model-flow-statistics - - - org.opendaylight.openflowplugin - openflowplugin-common - - - org.slf4j - slf4j-log4j12 - test - - - org.mockito - mockito-core - test - - - - - - - org.apache.felix - maven-bundle-plugin - - - * - - - - - org.opendaylight.yangtools - yang-maven-plugin - - - - - - - scm:git:ssh://git.opendaylight.org:29418/openflowplugin.git - scm:git:ssh://git.opendaylight.org:29418/openflowplugin.git - https://wiki.opendaylight.org/view/OpenDaylight_OpenFlow_Plugin:Main - HEAD - - - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatListeningCommiter.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatListeningCommiter.java deleted file mode 100644 index d40e4cbcf2..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatListeningCommiter.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager; - -import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.binding.NotificationListener; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager - * - * StatListeningCommiter - * Definition Interface for {@link DataTreeChangeListener} implementer class rule. - * Interface represent a contract between Config/DataStore changes and - * Operational/DataStore commits. All Operational/DataStore commit have - * to by represent as RPC Device response Notification processing. So - * Operational/DS could contains only real mirror of OF Device - * - * @author Vaclav Demcak - * - * Created: Aug 27, 2014 - */ -public interface StatListeningCommiter extends DataTreeChangeListener, StatNotifyCommiter { - - - /** - * All StatListeningCommiter implementer has to clean its actual state - * for all cached data related to disconnected node. - * Method prevents unwanted dataStore changes. - * - * @param nodeIdent - */ - void cleanForDisconnect(InstanceIdentifier nodeIdent); -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatNodeRegistration.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatNodeRegistration.java deleted file mode 100644 index 0a6e51e976..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatNodeRegistration.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.flow.node.SwitchFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.OpendaylightInventoryListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager.impl - * - * StatNodeRegistration - * Class represents {@link org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode} - * {@link org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener} in Operational/DataStore for ADD / REMOVE - * actions which are represented connect / disconnect OF actions. Connect functionality are expecting - * - * @author Vaclav Demcak - * - * Created: Sep 5, 2014 - */ -public interface StatNodeRegistration extends OpendaylightInventoryListener, AutoCloseable { - - /** - * Method contains {@link org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode} registration to {@link StatisticsManager} - * for permanently collecting statistics by {@link StatPermCollector} and - * as a prevention to use a validation check to the Operational/DS for identify - * connected {@link org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode}. - * - * @param keyIdent - * @param data - * @param nodeIdent - */ - void connectFlowCapableNode(InstanceIdentifier keyIdent, - SwitchFeatures data, InstanceIdentifier nodeIdent); - - /** - * Method cut {@link Node} registration for {@link StatPermCollector} - * - * @param keyIdent - */ - void disconnectFlowCapableNode(InstanceIdentifier keyIdent); - - /** - * Method returns if *this* instance of the stats-manager is owner of the node - * @param node Given Node - * @return true if owner, else false - */ - boolean isFlowCapableNodeOwner(NodeId node); -} diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatNotifyCommiter.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatNotifyCommiter.java deleted file mode 100644 index 9d633317e8..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatNotifyCommiter.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager; - -import org.opendaylight.yangtools.yang.binding.NotificationListener; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager - * - * StatNotifyCommiter - * Definition Interface for notification implementer class rule - * Interface represent a contract between RPC Device Notification - * and Operational/DataStore commits. - * - * - * @author Vaclav Demcak - * - * Created: Aug 28, 2014 - */ -public interface StatNotifyCommiter extends AutoCloseable, NotificationListener { - - -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatPermCollector.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatPermCollector.java deleted file mode 100644 index 113cad97ab..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatPermCollector.java +++ /dev/null @@ -1,141 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager; - -import java.util.List; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager - * - * StatPermCollector - * Class implement {@link Runnable} and inside is running statistic collecting - * process DataObject statistics by DataObject statistics for every {@link org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode}. - * Every statistics wait to finish previous statistics. Only if all statistics finish, - * next {@link org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode} - * Statistics should be collecting. We are able to set minimal time for start next round cross all Network, - * but all depends on network possibility. - * - * @author Vaclav Demcak - * - * Created: Aug 28, 2014 - */ -public interface StatPermCollector extends Runnable, AutoCloseable { - - /** - * StatCapType - * Enum class refers ofp_statistics capabilities fields from OF Switch - * capabilities specification which have to come as a post HandShake - * information from OF Switch and Inventory Manager adds all to the - * Operational/DS. - * If the capabilities are not add (for any reason) NodeRegistrator - * adds all StatCapTypes for the {@link Node}. - */ - public enum StatCapabTypes { - /** - * OFPC_FLOW_STATS - */ - FLOW_STATS, - /** - * OFPC_TABLE_STATS - */ - TABLE_STATS, - /** - * OFPC_PORT_STATS - */ - PORT_STATS, - /** - * OFPC_GROUP_STATS - */ - GROUP_STATS, - /** - * OFPC_QUEUE_STATS - */ - QUEUE_STATS, - /** - * Meter statistics has no support from OF Switch capabilities - * so we have to try get statistics for it and wait for response - * Error or response package with results. - */ - METER_STATS, - - //Custom flags for meter feature stats - METER_FEATURE_STATS, - - //Custom flags for group feature stats - GROUP_FEATURE_STATS - } - - /** - * Add new connected node for permanent statistics collecting process - * - * @param nodeIdent - * @param statTypes - * @param nrOfSwitchTables - * @return true/false if the {@link Node} added successful - */ - boolean connectedNodeRegistration(InstanceIdentifier nodeIdent, - List statTypes, Short nrOfSwitchTables); - - /** - * All disconnected Nodes need be removed from stat list Nodes - * - * @param nodeIdent - * @return true/false if the {@link Node} removed successful - */ - boolean disconnectedNodeUnregistration(InstanceIdentifier nodeIdent); - - /** - * Method add new feature {@link StatCapabTypes} to Node identified by - * nodeIdent -> InstanceIdentifier<Node> - * - * @param nodeIdent - * @return true/false if the {@link StatCapabTypes} add successful - */ - boolean registerAdditionalNodeFeature(InstanceIdentifier nodeIdent, StatCapabTypes statCapab); - - /** - * Method remove stats {@link StatCapabTypes} from Node identified by - * nodeIdent -> InstanceIdentifier<Node> - * - * @param nodeIdent - * @return true/false if the {@link StatCapabTypes} remove successful - */ - boolean unregisterNodeStats(InstanceIdentifier nodeIdent, StatCapabTypes statCapab); - - /** - * Method return true only and only if {@link StatPermCollector} contain - * valid node registration in its internal {@link Node} map. - * Otherwise return false. - * - * @param nodeIdent - * @return - */ - boolean isProvidedFlowNodeActive(InstanceIdentifier nodeIdent); - - /** - * Object notification for continue statistics collecting process. - * It is call from collecting allStatistics methods as a future result for - * Operational/DS statistic store call (does not matter in the outcome). - */ - void collectNextStatistics(TransactionId xid); - - /** - * Method returns true if collector has registered some active nodes - * otherwise return false. - * - * @return - */ - boolean hasActiveNodes(); -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatRpcMsgManager.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatRpcMsgManager.java deleted file mode 100644 index 3ec705086e..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatRpcMsgManager.java +++ /dev/null @@ -1,189 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager; - -import java.util.List; -import java.util.concurrent.Future; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionAware; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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.table.types.rev131026.TableId; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.common.RpcResult; - -import com.google.common.base.Optional; -import com.google.common.util.concurrent.SettableFuture; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager - * - * StatRpcMsgManager - * It represent access point for Device statistics RPC services which are - * filtered for needed methods only and they are wrapped in simply way. - * Many statistics responses are Multipart messages, so StatRpcMsgManager - * provide a functionality to add all multipart msg and provides back whole - * stack to listener when listener catch the last Multipart msg. - * - * @author Vaclav Demcak - * - * Created: Aug 29, 2014 - */ -public interface StatRpcMsgManager { - /** - * Transaction container is definition for Multipart transaction - * join container for all Multipart msg with same TransactionId - * Input {@link DataObject} is a possible light-weight DataObject - * which is used for identification (e.g. Flow -> Priority,Match,Cookie,FlowId) - * - * @param - */ - interface TransactionCacheContainer { - - void addNotif(T notification); - - TransactionId getId(); - - NodeId getNodeId(); - - Optional getConfInput(); - - List getNotifications(); - } - - /** - * Method is used for check a transaction registration - * for multipart cache holder - * - * @param id - * @return true if the transaction has been correctly registered - */ - Future isExpectedStatistics(TransactionId id, NodeId nodeId); - - /** - * Method converts {@link java.util.concurrent.Future} object to listenenable future which - * is registered for Multipart Notification Statistics Collecting processing. - * - * @param future - result every Device RPC call - */ - void registrationRpcFutureCallBack( - Future> future, D inputObj, NodeRef ref, SettableFuture resultTransId); - - /** - * Method adds Notification which is marked as Multipart to the transaction cash - * to wait for the last one. - * - * @param notification - */ - void addNotification(T notification, NodeId nodeId); - - /** - * The last Multipart should inform code about possibility to take all previous - * messages for next processing. The method take all msg and possible input object - * and build all to TransactionCacheContainer Object to return. This process clean - * all instances in Cache. - * - * @param id - * @return TransactionCacheContainer - */ - Future>> getTransactionCacheContainer(TransactionId id, NodeId nodeId); - - /** - * Method wraps OpendaylightGroupStatisticsService.getAllGroupStatistics - * and registers to Transaction Cache - * - * @param nodeRef - */ - Future getAllGroupsStat(NodeRef nodeRef); - - /** - * Method wraps OpendaylightGroupStatisticsService.getGroupDescription - * and registers to Transaction Cache - * - * @param nodeRef - */ - Future getAllGroupsConfStats(NodeRef nodeRef); - - /** - * Method wraps OpendaylightMeterStatisticsService.getGroupFeatures - * and registers to Transaction Cache - * - * @param nodeRef - */ - void getGroupFeaturesStat(NodeRef nodeRef); - - /** - * Method wraps OpendaylightMeterStatisticsService.getAllMeterStatistics - * and registers to Transaction Cache - * - * @param nodeRef - */ - Future getAllMetersStat(NodeRef nodeRef); - - /** - * Method wraps OpendaylightMeterStatisticsService.getAllMeterConfigStatistics - * and registers to Transaction Cache - * - * @param nodeRef - */ - Future getAllMeterConfigStat(NodeRef nodeRef); - - /** - * Method wraps OpendaylightMeterStatisticsService.getMeterFeatures - * and registers to Transaction Cache - * - * @param nodeRef - */ - void getMeterFeaturesStat(NodeRef nodeRef); - - /** - * Method wraps OpendaylightFlowStatisticsService.getAllFlowsStatisticsFromAllFlowTables - * and registers to Transaction Cache - * - * @param nodeRef - */ - Future getAllFlowsStat(NodeRef nodeRef); - - /** - * Method wraps OpendaylightFlowStatisticsService.getAggregateFlowStatisticsFromFlowTableForAllFlows - * and registers to Transaction Cache - * - * @param nodeRef - * @param tableId - */ - void getAggregateFlowStat(NodeRef nodeRef, TableId tableId); - - /** - * Method wraps OpendaylightPortStatisticsService.getAllNodeConnectorsStatistics - * and registers to Transaction Cache - * - * @param nodeRef - */ - Future getAllPortsStat(NodeRef nodeRef); - - /** - * Method wraps OpendaylightFlowTableStatisticsService.getFlowTablesStatistics - * and registers to Transaction Cache - * - * @param nodeRef - */ - Future getAllTablesStat(NodeRef nodeRef); - - /** - * Method wraps OpendaylightQueueStatisticsService.getAllQueuesStatisticsFromAllPorts - * and registers to Transaction Cache - * - * @param nodeRef - */ - Future getAllQueueStat(NodeRef nodeRef); - -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatisticsManager.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatisticsManager.java deleted file mode 100644 index 109920614a..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatisticsManager.java +++ /dev/null @@ -1,297 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager; - -import java.util.List; -import java.util.UUID; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService; -import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; -import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcConsumerRegistry; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatPermCollector.StatCapabTypes; -import org.opendaylight.openflowplugin.applications.statistics.manager.impl.StatisticsManagerConfig; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.OpendaylightFlowStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.OpendaylightFlowTableStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.Queue; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.OpendaylightGroupStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group; -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.meter.statistics.rev131111.OpendaylightMeterStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.OpendaylightPortStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.OpendaylightQueueStatisticsListener; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager - * - * StatisticsManager - * It represent a central point for whole module. Implementation - * StatisticsManager registers all Operation/DS {@link StatNotifyCommiter} and - * Config/DS {@link StatListeningCommiter}, as well as {@link StatPermCollector} - * for statistic collecting and {@link StatRpcMsgManager} as Device RPCs provider. - * In next, StatisticsManager provides all DS contact Transaction services. - * - * @author Vaclav Demcak - * - * Created: Aug 27, 2014 - */ -public interface StatisticsManager extends AutoCloseable, TransactionChainListener { - - /** - * StatDataStoreOperation - * Interface represent functionality to submit changes to DataStore. - * Internal {@link TransactionChainListener} joining all DS commits - * to Set of chained changes for prevent often DataStore touches. - */ - abstract class StatDataStoreOperation { - public enum StatsManagerOperationType { - /** - * Operation will carry out work related to new node addition / - * update - */ - NODE_UPDATE, - /** - * Operation will carry out work related to node removal - */ - NODE_REMOVAL, - /** - * Operation will commit data to the operational data store - */ - DATA_COMMIT_OPER_DS - } - - private NodeId nodeId; - private StatsManagerOperationType operationType = StatsManagerOperationType.DATA_COMMIT_OPER_DS; - private UUID nodeUUID; - - public StatDataStoreOperation(final StatsManagerOperationType operType, final NodeId id){ - if(operType != null){ - operationType = operType; - } - nodeId = id; - nodeUUID = generatedUUIDForNode(); - } - - public final StatsManagerOperationType getType() { - return operationType; - } - - public final NodeId getNodeId(){ - return nodeId; - } - - public UUID getNodeUUID() { - return nodeUUID; - } - - /** - * Apply all read / write (put|merge) operation for DataStore - * - * @param tx {@link ReadWriteTransaction} - */ - public abstract void applyOperation(ReadWriteTransaction tx); - - protected abstract UUID generatedUUIDForNode(); - - public InstanceIdentifier getNodeIdentifier() { - final InstanceIdentifier nodeIdent = InstanceIdentifier.create(Nodes.class) - .child(Node.class, new NodeKey(nodeId)); - return nodeIdent; - } - - } - - - class Pair { - - private final L left; - private final R right; - - public Pair(L left, R right) { - this.left = left; - this.right = right; - } - - public L getLeft() { return left; } - public R getRight() { return right; } - - @Override - public int hashCode() { return left.hashCode() ^ right.hashCode(); } - - @Override - public boolean equals(Object o) { - if (!(o instanceof Pair)) return false; - Pair pairo = (Pair) o; - return this.left.equals(pairo.getLeft()) && - this.right.equals(pairo.getRight()); - } - - } - - /** - * Method starts whole StatisticManager functionality - * - * @param notifService - * @param rpcRegistry - */ - void start(final NotificationProviderService notifService, - final RpcConsumerRegistry rpcRegistry); - - /** - * Method provides read/write DataStore functionality cross applyOperation - * defined in {@link StatDataStoreOperation} - * - * @param inventoryOper - operation for DataStore - */ - void enqueue(final StatDataStoreOperation inventoryOper); - - /** - * Method wraps {@link StatisticsManager#isProvidedFlowNodeActive(InstanceIdentifier)} method - * to provide parallel statCollection process for Set of Nodes. So it has to - * identify correct Node Set by NodeIdentifier - * - * @param nodeIdent - */ - boolean isProvidedFlowNodeActive(InstanceIdentifier nodeIdent); - - /** - * Method wraps {@link StatPermCollector}.collectNextStatistics to provide - * parallel statCollection process for Set of Nodes. So it has to - * identify correct Node Set by NodeIdentifier. - * - * @param nodeIdent - */ - void collectNextStatistics(InstanceIdentifier nodeIdent, TransactionId xid); - - /** - * Method wraps {@link StatPermCollector}.connectedNodeRegistration to provide - * parallel statCollection process for Set of Nodes. So it has to - * connect node to new or not full Node statCollector Set. - * - * @param nodeIdent - * @param statTypes - * @param nrOfSwitchTables - */ - void connectedNodeRegistration(InstanceIdentifier nodeIdent, - List statTypes, Short nrOfSwitchTables); - - /** - * Method wraps {@link StatPermCollector}.disconnectedNodeUnregistration to provide - * parallel statCollection process for Set of Nodes. So it has to identify - * correct collector for disconnect node. - * - * @param nodeIdent - */ - void disconnectedNodeUnregistration(InstanceIdentifier nodeIdent); - - /** - * Method wraps {@link StatPermCollector}.registerAdditionalNodeFeature to provide - * possibility to register additional Node Feature {@link StatCapabTypes} for - * statistics collecting. - * - * @param nodeIdent - * @param statCapab - */ - void registerAdditionalNodeFeature(InstanceIdentifier nodeIdent, StatCapabTypes statCapab); - - /** - * Method wraps {@link StatPermCollector}.unregisterNodeStats to provide - * possibility to unregister Node stats type {@link StatCapabTypes} from - * statistics collecting. - * - * @param nodeIdent - * @param statCapab - */ - void unregisterNodeStats(InstanceIdentifier nodeIdent, StatCapabTypes statCapab); - - /** - * Method provides access to Device RPC methods by wrapped - * internal method. In next {@link StatRpcMsgManager} is registered all - * Multipart device msg response and joining all to be able run all - * collected statistics in one time (easy identification Data for delete) - * - * @return {@link StatRpcMsgManager} - */ - StatRpcMsgManager getRpcMsgManager(); - - /** - * Define Method : {@link org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode} - * Operational/DS data change listener -> impl. target -> register FlowCapableNode to Statistic Collecting process - * @return {@link StatNodeRegistration} - */ - StatNodeRegistration getNodeRegistrator(); - - /** - * Define Method : Flow Config/DS data change listener -> impl. target -> - * -> make pair between Config/DS FlowId and Device Flow response Hash - * @return - */ - StatListeningCommiter getFlowListenComit(); - - /** - * Define Method : Meter Config/DS data change listener and Operation/DS notify commit - * functionality - * @return - */ - StatListeningCommiter getMeterListenCommit(); - - /** - * Define Method : Group Config/DS data change listener and Operation/DS notify commit - * functionality - * @return - */ - StatListeningCommiter getGroupListenCommit(); - - /** - * Define Method : Queue Config/DS change listener and Operation/DS notify commit functionality - * @return - */ - StatListeningCommiter getQueueNotifyCommit(); - - /** - * Define Method : Table Operation/DS notify commit functionality - * @return - */ - StatNotifyCommiter getTableNotifCommit(); - - /** - * Define Method : Port Operation/DS notify commit functionality - * @return - */ - StatNotifyCommiter getPortNotifyCommit(); - - StatisticsManagerConfig getConfiguration(); - - /** - * A unique UUID is generated with each node added by the statistics manager implementation in order to uniquely - * identify a session. - * @param nodeInstanceIdentifier - */ - UUID getGeneratedUUIDForNode(InstanceIdentifier nodeInstanceIdentifier); - - /* - * Setting entity-ownership-service - */ - void setOwnershipService(EntityOwnershipService ownershipService); - - /** - * Getting entity-ownership-service - */ - EntityOwnershipService getOwnershipService(); - -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatisticsManagerFactory.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatisticsManagerFactory.java deleted file mode 100644 index fde568e9a1..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/StatisticsManagerFactory.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.applications.statistics.manager; - -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcConsumerRegistry; -import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.app.statistics.manager.config.rev160509.StatisticsManagerAppConfig; - -/** - * Factory for creating StatisticsManager instances. - * - * @author Thomas Pantelis - */ -public interface StatisticsManagerFactory { - StatisticsManager newInstance(StatisticsManagerAppConfig statsManagerAppConfig, DataBroker dataBroker, - NotificationProviderService notifService, RpcConsumerRegistry rpcRegistry, - EntityOwnershipService entityOwnershipService); - -} diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatAbstractListenCommit.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatAbstractListenCommit.java deleted file mode 100644 index 740f82378c..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatAbstractListenCommit.java +++ /dev/null @@ -1,194 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -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.controller.md.sal.common.api.data.ReadFailedException; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatListeningCommiter; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.openflowplugin.common.wait.SimpleTaskRetryLooper; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.binding.NotificationListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager.impl - * - * StatAbstractListeneningCommiter - * Class is abstract implementation for all Configuration/DataStore DataTreeModification - * listenable DataObjects like flows, groups, meters. It is a holder for common - * functionality needed by construction/destruction class and for DataTreeModification - * event processing. - */ -public abstract class StatAbstractListenCommit - extends StatAbstractNotifyCommit implements StatListeningCommiter { - - private static final Logger LOG = LoggerFactory.getLogger(StatAbstractListenCommit.class); - - private ListenerRegistration> listenerRegistration; - - protected final Map, Map, Integer>> mapNodesForDelete = new ConcurrentHashMap<>(); - protected final Map, Integer> mapNodeFeautureRepeater = new ConcurrentHashMap<>(); - protected final Map, ArrayList> removedDataBetweenStatsCycle = new - ConcurrentHashMap<>(); - - private final Class clazz; - - protected final DataBroker dataBroker; - - protected final StatNodeRegistration nodeRegistrationManager; - - private ReadOnlyTransaction currentReadTx; - private volatile boolean currentReadTxStale; - - private static final int STARTUP_LOOP_TICK = 500; - private static final int STARTUP_LOOP_MAX_RETRIES = 8; - - private final DataTreeIdentifier treeId = - new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, getWildCardedRegistrationPath()); - - /* Constructor has to make a registration */ - public StatAbstractListenCommit(final StatisticsManager manager, final DataBroker db, - final NotificationProviderService nps, final Class clazz, final StatNodeRegistration nodeRegistrationManager) { - super(manager,nps, nodeRegistrationManager); - this.clazz = Preconditions.checkNotNull(clazz, "Referenced Class can not be null"); - Preconditions.checkArgument(db != null, "DataBroker can not be null!"); - this.dataBroker = db; - this.nodeRegistrationManager = nodeRegistrationManager; - - SimpleTaskRetryLooper looper = new SimpleTaskRetryLooper(STARTUP_LOOP_TICK, STARTUP_LOOP_MAX_RETRIES); - try { - listenerRegistration = looper.loopUntilNoException(new Callable>>() { - @Override - public ListenerRegistration> call() throws Exception { - return db.registerDataTreeChangeListener(treeId,StatAbstractListenCommit.this); - } - }); - } catch (final Exception ex) { - LOG.debug(" StatAbstractListenCommit DataTreeChangeListener registration failed {}", ex.getMessage()); - throw new IllegalStateException("Notification supplier startup fail! System needs restart.", ex); - } - } - - /** - * Method returns WildCarded Path which is used for registration as a listening path changes in - * {@link org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener} - * @return - */ - protected abstract InstanceIdentifier getWildCardedRegistrationPath(); - - protected abstract void processDataChange(Collection> changes); - - @Override - public void onDataTreeChanged(Collection> changes) { - Preconditions.checkNotNull(changes, "Changes must not be null!"); - /* - * If we have opened read transaction for configuration data store, we need to mark it as stale. - * - * Latest read transaction will be allocated on another read using readLatestConfiguration - */ - currentReadTxStale = true; - processDataChange(changes); - } - - @SuppressWarnings("unchecked") - protected void removeData(final InstanceIdentifier key, final Integer value) { - if (clazz.equals(key.getTargetType())) { - final InstanceIdentifier nodeIdent = key.firstIdentifierOf(Node.class); - Map, Integer> map = null; - if (mapNodesForDelete.containsKey(nodeIdent)) { - map = mapNodesForDelete.get(nodeIdent); - } - if (map == null) { - map = new ConcurrentHashMap<>(); - mapNodesForDelete.put(nodeIdent, map); - } - map.put((InstanceIdentifier) key, value); - } - } - - @Override - public void cleanForDisconnect(final InstanceIdentifier nodeIdent) { - mapNodesForDelete.remove(nodeIdent); - removedDataBetweenStatsCycle.remove(nodeIdent); - } - - @Override - public void close() { - if (listenerRegistration != null) { - try { - listenerRegistration.close(); - } catch (final Exception e) { - LOG.error("Error by stop {} DataTreeChangeListener StatListeningCommiter.", clazz.getSimpleName(), e); - } - listenerRegistration = null; - } - - super.close(); - } - - /** - * Method return actual DataObject identified by InstanceIdentifier from Config/DS - * @param path - * @return - */ - protected final Optional readLatestConfiguration(final InstanceIdentifier path) { - for(int i = 0; i < 2; i++) { - boolean localReadTxStale = currentReadTxStale; - - // This non-volatile read piggy backs the volatile currentReadTxStale read above to - // ensure visibility in case this method is called across threads (although not concurrently). - ReadOnlyTransaction localReadTx = currentReadTx; - if(localReadTx == null || localReadTxStale) { - if(localReadTx != null) { - localReadTx.close(); - } - - localReadTx = dataBroker.newReadOnlyTransaction(); - - currentReadTx = localReadTx; - - // Note - this volatile write also publishes the non-volatile currentReadTx write above. - currentReadTxStale = false; - } - - try { - return localReadTx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet(); - } catch (final ReadFailedException e) { - LOG.debug("It wasn't possible to read {} from datastore. Exception: {}", path, e); - - // Loop back and try again with a new Tx. - currentReadTxStale = true; - } - } - - return Optional.absent(); - } - -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatAbstractNotifyCommit.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatAbstractNotifyCommit.java deleted file mode 100644 index dcb64734cf..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatAbstractNotifyCommit.java +++ /dev/null @@ -1,165 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNotifyCommiter; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatRpcMsgManager.TransactionCacheContainer; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.binding.NotificationListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager.impl - * - * StatAbstratNotifiCommiter - * Class is abstract implementation for all no Configuration/DataStore DataObjects - * and represent common functionality for all DataObject Statistics Commiters. - * Class defines contract between DataObject and relevant Statistics NotificationListener. - * - */ -public abstract class StatAbstractNotifyCommit implements StatNotifyCommiter { - - private static final Logger LOG = LoggerFactory.getLogger(StatAbstractNotifyCommit.class); - - private static final long MAX_WAIT_TIME = 10; - - protected final StatisticsManager manager; - private ListenerRegistration notifyListenerRegistration; - protected final StatNodeRegistration nodeRegistrationManager; - - - public StatAbstractNotifyCommit(final StatisticsManager manager, - final NotificationProviderService nps, - final StatNodeRegistration nodeRegistrationManager) { - Preconditions.checkArgument(nps != null, "NotificationProviderService can not be null!"); - this.manager = Preconditions.checkNotNull(manager, "StatisticManager can not be null!"); - notifyListenerRegistration = nps.registerNotificationListener(getStatNotificationListener()); - this.nodeRegistrationManager = nodeRegistrationManager; - } - - @Override - public void close() { - if (notifyListenerRegistration != null) { - try { - notifyListenerRegistration.close(); - } - catch (final Exception e) { - LOG.error("Error by stop {} StatNotificationListener. Exception {}", - this.getClass().getSimpleName(), e); - } - notifyListenerRegistration = null; - } - } - - /** - * Method returns Statistics Notification Listener for relevant DataObject implementation, - * which is declared for {@link StatNotifyCommiter} interface. - * - * @return - */ - protected abstract N getStatNotificationListener(); - - /** - * PreConfigurationCheck - Node identified by input InstanceIdentifier<Node> - * has to be registered in {@link org.opendaylight.openflowplugin.applications.statistics.manager.StatPermCollector} - * - * @param nodeIdent - */ - protected boolean preConfigurationCheck(final InstanceIdentifier nodeIdent) { - Preconditions.checkNotNull(nodeIdent, "FlowCapableNode ident can not be null!"); - return manager.isProvidedFlowNodeActive(nodeIdent); - } - - protected void notifyToCollectNextStatistics(final InstanceIdentifier nodeIdent, final TransactionId xid) { - Preconditions.checkNotNull(nodeIdent, "FlowCapableNode ident can not be null!"); - manager.collectNextStatistics(nodeIdent, xid); - } - - /** - * Wrapping Future object call for {@link org.opendaylight.openflowplugin.applications.statistics.manager.StatRpcMsgManager} - * getTransactionCacheContainer with 10sec TimeOut. - * Method has returned {@link Optional} which could contains a {@link TransactionCacheContainer} - * - * @param transId - * @param nodeId - * @return - */ - protected Optional> getTransactionCacheContainer(final TransactionId transId, final NodeId nodeId) { - Optional> txContainer; - try { - txContainer = manager.getRpcMsgManager().getTransactionCacheContainer(transId, nodeId).get(MAX_WAIT_TIME, TimeUnit.SECONDS); - } - catch (InterruptedException | ExecutionException | TimeoutException e) { - LOG.warn("Get TransactionCacheContainer fail!", e); - txContainer = Optional.absent(); - } - return txContainer; - } - - /** - * Method validate TransactionCacheContainer. It needs to call before every txCacheContainer processing. - * - * @param txCacheContainer - * @return - */ - protected boolean isTransactionCacheContainerValid(final Optional> txCacheContainer) { - if ( ! txCacheContainer.isPresent()) { - LOG.debug("Transaction Cache Container is not presented!"); - return false; - } - if (txCacheContainer.get().getNodeId() == null) { - LOG.debug("Transaction Cache Container {} don't have Node ID!", txCacheContainer.get().getId()); - return false; - } - if (txCacheContainer.get().getNotifications() == null) { - LOG.debug("Transaction Cache Container {} for {} node don't have Notifications!", - txCacheContainer.get().getId(), txCacheContainer.get().getNodeId()); - return false; - } - return true; - } - - /** - * Wrapping Future object call to {@link org.opendaylight.openflowplugin.applications.statistics.manager.StatRpcMsgManager} - * isExpectedStatistics with 10sec TimeOut. - * Method has checked registration for provided {@link TransactionId} and {@link NodeId} - * - * @param transId - Transaction identification - * @param nodeId - Node identification - * @return boolean - */ - protected boolean isExpectedStatistics(final TransactionId transId, final NodeId nodeId) { - Boolean isExpectedStat = Boolean.FALSE; - try { - isExpectedStat = manager.getRpcMsgManager().isExpectedStatistics(transId, nodeId).get(MAX_WAIT_TIME, TimeUnit.SECONDS); - } - catch (InterruptedException | ExecutionException | TimeoutException e) { - LOG.warn("Check Transaction registraion {} fail!", transId, e); - return false; - } - return isExpectedStat.booleanValue(); - } -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitFlow.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitFlow.java deleted file mode 100644 index 49068c7161..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitFlow.java +++ /dev/null @@ -1,562 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import com.google.common.base.Optional; -import com.google.common.collect.BiMap; -import com.google.common.collect.HashBiMap; -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.DataTreeModification; -import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatRpcMsgManager.TransactionCacheContainer; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager.StatDataStoreOperation; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager.StatDataStoreOperation.StatsManagerOperationType; -import org.opendaylight.openflowplugin.applications.statistics.manager.impl.helper.FlowComparator; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowHashIdMapping; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowHashIdMappingBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.nodes.node.table.FlowHashIdMap; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.nodes.node.table.FlowHashIdMapBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.nodes.node.table.FlowHashIdMapKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.AggregateFlowStatisticsData; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.AggregateFlowStatisticsDataBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.AggregateFlowStatisticsUpdate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowStatisticsData; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowStatisticsDataBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowsStatisticsUpdate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.OpendaylightFlowStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.aggregate.flow.statistics.AggregateFlowStatisticsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.flow.and.statistics.map.list.FlowAndStatisticsMapList; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.flow.and.statistics.map.list.FlowAndStatisticsMapListBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.flow.statistics.FlowStatisticsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionAware; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie; -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.DataObject; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager.impl - * - * StatListenCommitFlow - * Class is a NotifyListener for FlowStatistics and DataTreeChangeListener for Config/DataStore for Flow node. - * All expected (registered) FlowStatistics will be builded and commit to Operational/DataStore. - * DataTreeModification should call create/delete Flow in Operational/DS create process needs to pair - * Device Flow HashCode and FlowId from Config/DS - */ -public class StatListenCommitFlow extends StatAbstractListenCommit - implements OpendaylightFlowStatisticsListener { - - protected static final Logger LOG = LoggerFactory.getLogger(StatListenCommitFlow.class); - - private static final String ALIEN_SYSTEM_FLOW_ID = "#UF$TABLE*"; - - private static final Integer REMOVE_AFTER_MISSING_COLLECTION = 1; - private static final int TRUNCATED_LOG_MESSAGE_LENGTH = 30; - - private final AtomicInteger unaccountedFlowsCounter = new AtomicInteger(0); - - public StatListenCommitFlow (final StatisticsManager manager, final DataBroker db, - final NotificationProviderService nps, - final StatNodeRegistration nrm){ - super(manager, db, nps, Flow.class,nrm); - } - - @Override - protected OpendaylightFlowStatisticsListener getStatNotificationListener() { - return this; - } - - @Override - protected InstanceIdentifier getWildCardedRegistrationPath() { - return InstanceIdentifier.create(Nodes.class).child(Node.class) - .augmentation(FlowCapableNode.class).child(Table.class).child(Flow.class); - } - - @Override - public void onAggregateFlowStatisticsUpdate(final AggregateFlowStatisticsUpdate notification) { - final TransactionId transId = notification.getTransactionId(); - final NodeId nodeId = notification.getId(); - if ( ! isExpectedStatistics(transId, nodeId)) { - LOG.debug("STAT-MANAGER - AggregateFlowStatisticsUpdate: unregistred notification detect TransactionId {}", transId); - return; - } - manager.getRpcMsgManager().addNotification(notification, nodeId); - if (notification.isMoreReplies()) { - return; - } - /* check flow Capable Node and write statistics */ - manager.enqueue(new StatDataStoreOperation(StatsManagerOperationType.DATA_COMMIT_OPER_DS,nodeId) { - @Override - public void applyOperation(final ReadWriteTransaction tx) { - - final Optional> txContainer = getTransactionCacheContainer(transId, nodeId); - if (( ! txContainer.isPresent()) || txContainer.get().getNotifications() == null) { - return; - } - final Optional inputObj = txContainer.get().getConfInput(); - if (( ! inputObj.isPresent()) || ( ! (inputObj.get() instanceof Table))) { - return; - } - - if(!nodeRegistrationManager.isFlowCapableNodeOwner(nodeId)) { return; } - - final Table table = (Table) inputObj.get(); - final List cacheNotifs = txContainer.get().getNotifications(); - for (final TransactionAware notif : cacheNotifs) { - if (notif instanceof AggregateFlowStatisticsUpdate) { - final AggregateFlowStatisticsData stats = new AggregateFlowStatisticsDataBuilder() - .setAggregateFlowStatistics(new AggregateFlowStatisticsBuilder(notification).build()).build(); - final InstanceIdentifier fNodeIdent = InstanceIdentifier.create(Nodes.class) - .child(Node.class, new NodeKey(nodeId)).augmentation(FlowCapableNode.class); - final InstanceIdentifier tableRef = fNodeIdent.child(Table.class, table.getKey()); - final InstanceIdentifier tableStatRef = tableRef - .augmentation(AggregateFlowStatisticsData.class); - Optional fNode = Optional.absent(); - try { - fNode = tx.read(LogicalDatastoreType.OPERATIONAL, fNodeIdent).checkedGet(); - } catch (final ReadFailedException e) { - LOG.debug("Read Operational/DS for FlowCapableNode fail! {}", fNodeIdent, e); - return; - } - if (fNode.isPresent()) { - ensureTable(tx, table.getId(), tableRef); - tx.put(LogicalDatastoreType.OPERATIONAL, tableStatRef, stats); - } - } - } - } - - @Override - public UUID generatedUUIDForNode() { - return manager.getGeneratedUUIDForNode(getNodeIdentifier()); - } - }); - } - - public void ensureTable(final ReadWriteTransaction tx, final Short tableId, final InstanceIdentifier
tableRef) { - final Table tableNew = new TableBuilder().setId(tableId).build(); - tx.merge(LogicalDatastoreType.OPERATIONAL, tableRef, tableNew); - } - - protected void processDataChange(Collection> changes) { - if (!changes.isEmpty()) { - for (DataTreeModification dataChange : changes) { - if (dataChange.getRootNode().getModificationType() == DataObjectModification.ModificationType.DELETE) { - final InstanceIdentifier nodeIdent = dataChange.getRootPath().getRootIdentifier() - .firstIdentifierOf(Node.class); - if (!removedDataBetweenStatsCycle.containsKey(nodeIdent)) { - removedDataBetweenStatsCycle.put(nodeIdent, new ArrayList<>()); - } - Flow data = dataChange.getRootNode().getDataBefore(); - removedDataBetweenStatsCycle.get(nodeIdent).add(data); - LOG.debug("Node: {} :: Flow removed {}",nodeIdent.firstKeyOf(Node.class).getId(), data.toString()); - } - } - } - } - - @Override - public void onFlowsStatisticsUpdate(final FlowsStatisticsUpdate notification) { - final TransactionId transId = notification.getTransactionId(); - final NodeId nodeId = notification.getId(); - if ( ! isExpectedStatistics(transId, nodeId)) { - LOG.debug("STAT-MANAGER - FlowsStatisticsUpdate: unregistered notification detect TransactionId {}", - transId); - return; - } - manager.getRpcMsgManager().addNotification(notification, nodeId); - if (notification.isMoreReplies()) { - LOG.trace("Next notification for join txId {}", transId); - return; - } - /* add flow's statistics */ - manager.enqueue(new StatDataStoreOperation(StatsManagerOperationType.DATA_COMMIT_OPER_DS,nodeId) { - @Override - public void applyOperation(final ReadWriteTransaction tx) { - final Optional> txContainer = getTransactionCacheContainer(transId, nodeId); - if (( ! txContainer.isPresent()) || txContainer.get().getNotifications() == null) { - return; - } - if(!nodeRegistrationManager.isFlowCapableNodeOwner(nodeId)) { return; } - - final List flowStats = new ArrayList(10); - final InstanceIdentifier nodeIdent = InstanceIdentifier.create(Nodes.class) - .child(Node.class, new NodeKey(nodeId)); - final List cacheNotifs = txContainer.get().getNotifications(); - for (final TransactionAware notif : cacheNotifs) { - if (notif instanceof FlowsStatisticsUpdate) { - final List notifList = - ((FlowsStatisticsUpdate) notif).getFlowAndStatisticsMapList(); - if (notifList != null) { - flowStats.addAll(notifList); - } - } - } - - statsFlowCommitAll(flowStats, nodeIdent, tx); - /* cleaning all not cached hash collisions */ - final Map, Integer> listAliens = mapNodesForDelete.get(nodeIdent); - if (listAliens != null) { - for (final Entry, Integer> nodeForDelete : listAliens.entrySet()) { - final Integer lifeIndex = nodeForDelete.getValue(); - if (nodeForDelete.getValue() > 0) { - nodeForDelete.setValue(Integer.valueOf(lifeIndex.intValue() - 1)); - } else { - final InstanceIdentifier flowNodeIdent = nodeForDelete.getKey(); - mapNodesForDelete.get(nodeIdent).remove(flowNodeIdent); - tx.delete(LogicalDatastoreType.OPERATIONAL, flowNodeIdent); - } - } - } - /* Notification for continue collecting statistics */ - notifyToCollectNextStatistics(nodeIdent, transId); - } - - @Override - public UUID generatedUUIDForNode() { - return manager.getGeneratedUUIDForNode(getNodeIdentifier()); - } - - }); - } - - private void statsFlowCommitAll(final List list, - final InstanceIdentifier nodeIdent, final ReadWriteTransaction tx) { - - final InstanceIdentifier fNodeIdent = nodeIdent.augmentation(FlowCapableNode.class); - - //cleanup the hashmap ID for the flows deleted between two stats cycle, also cleanup the - // data change cache as well. - ArrayList deletedFlows = removedDataBetweenStatsCycle.remove(nodeIdent); - - if (deletedFlows != null && !deletedFlows.isEmpty()) { - LOG.trace("Number of flows deleted from node {} between two stats cycles are {}", nodeIdent, deletedFlows - .size()); - } - - final Optional fNode; - try { - fNode = tx.read(LogicalDatastoreType.OPERATIONAL, fNodeIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read FlowCapableNode {} in Operational/DS fail! Statistic scan not be updated.", nodeIdent, e); - return; - } - if ( ! fNode.isPresent()) { - LOG.trace("FlowCapableNode {} is not presented in Operational/DS. Statisticscan not be updated.", nodeIdent); - return; - } - - final NodeUpdateState nodeState = new NodeUpdateState(fNodeIdent,fNode.get()); - - for (final FlowAndStatisticsMapList flowStat : list) { - final TableKey tableKey = new TableKey(flowStat.getTableId()); - final TableFlowUpdateState tableState = nodeState.getTable(tableKey, tx); - Flow removedConfigFlow = getFlowIfRemoved(flowStat, deletedFlows); - if (removedConfigFlow == null) { - tableState.reportFlow(flowStat,tx, false); - } else { - deletedFlows.remove(removedConfigFlow); - tableState.reportFlow(flowStat,tx, true); - } - } - - if (deletedFlows != null ) { - deletedFlows.clear(); - } - for (final TableFlowUpdateState table : nodeState.getTables()) { - table.removeUnreportedFlows(tx); - } - } - - private Flow getFlowIfRemoved(FlowAndStatisticsMapList flowStat, ArrayList deletedFlows) { - if (deletedFlows != null && !deletedFlows.isEmpty()) { - for (Flow flow : deletedFlows) { - final FlowAndStatisticsMapList configFlowStats = new FlowAndStatisticsMapListBuilder(flow).build(); - if ( flowStat.getMatch().equals(configFlowStats.getMatch()) && - flowStat.getPriority().equals(configFlowStats.getPriority()) && - flowStat.getCookie().equals(configFlowStats.getCookie()!=null?configFlowStats.getCookie(): - new FlowCookie(new BigInteger("0")))) { - LOG.debug("Flow statistics {} are related to flow {}, but it's REMOVED from the config data store" + - "store", flowStat, flow); - return flow; - } - } - } - return null; - } - /** - * Method adds statistics to Flow - * - * @param flowBuilder - * @param deviceFlow - */ - private void addStatistics(final FlowBuilder flowBuilder, final FlowAndStatisticsMapList deviceFlow) { - final FlowAndStatisticsMapListBuilder stats = new FlowAndStatisticsMapListBuilder(deviceFlow); - final FlowStatisticsBuilder flowStatisticsBuilder = new FlowStatisticsBuilder(stats.build()); - final FlowStatisticsDataBuilder flowStatisticsData =new FlowStatisticsDataBuilder(); - flowStatisticsData.setFlowStatistics(flowStatisticsBuilder.build()); - flowBuilder.addAugmentation(FlowStatisticsData.class, flowStatisticsData.build()); - } - - /** - * build pseudoUnique hashCode for flow in table - * for future easy identification - * - * FIXME: we expect same version for YANG models for all clusters and that has to be fix - * FIXME: CREATE BETTER KEY - for flow (MATCH is the problem) - */ - static String buildFlowIdOperKey(final FlowAndStatisticsMapList deviceFlow) { - return new StringBuilder().append(deviceFlow.getMatch()) - .append(deviceFlow.getPriority()).append(deviceFlow.getCookie().getValue()).toString(); - } - - private class NodeUpdateState { - private final InstanceIdentifier nodeIdentifier; - private final Map tables = new HashMap<>(); - - public NodeUpdateState(final InstanceIdentifier fNodeIdent, final FlowCapableNode flowCapableNode) { - nodeIdentifier = fNodeIdent; - final List
tableList = flowCapableNode.getTable(); - if(tableList != null) { - for (final Table table : tableList) { - final TableKey tableKey = table.getKey(); - tables.put(tableKey, new TableFlowUpdateState(nodeIdentifier.child(Table.class,tableKey),table)); - } - } - } - - public Iterable getTables() { - return tables.values(); - } - - TableFlowUpdateState getTable(final TableKey key,final ReadWriteTransaction tx) { - TableFlowUpdateState table = tables.get(key); - if(table == null) { - table = new TableFlowUpdateState(nodeIdentifier.child(Table.class, key), null); - tables.put(key, table); - } - return table; - } - } - - private class TableFlowUpdateState { - - private boolean tableEnsured = false; - final KeyedInstanceIdentifier tableRef; - final TableKey tableKey; - final BiMap flowIdByHash; - List configFlows; - - public TableFlowUpdateState(final KeyedInstanceIdentifier tablePath, final Table table) { - tableRef = tablePath; - tableKey = tablePath.getKey(); - flowIdByHash = HashBiMap.create(); - if(table != null) { - final FlowHashIdMapping flowHashMapping = table.getAugmentation(FlowHashIdMapping.class); - if (flowHashMapping != null) { - final List flowHashMap = flowHashMapping.getFlowHashIdMap() != null - ? flowHashMapping.getFlowHashIdMap() : Collections. emptyList(); - for (final FlowHashIdMap flowHashId : flowHashMap) { - try { - flowIdByHash.put(flowHashId.getKey(), flowHashId.getFlowId()); - } catch (final Exception e) { - //flowHashId.getKey() too verbose for standard log. - if(LOG.isDebugEnabled()) { - final FlowId currData = flowIdByHash.get(flowHashId.getKey()); - LOG.debug("Flow hashing hit a duplicate for {} -> {}. Curr value: {} Equals:{}. " + - "Exception was raised:", - flowHashId.getKey(), flowHashId.getFlowId(), currData, flowHashId.getFlowId().equals(currData), e); - } - else - { - LOG.warn("Flow hashing hit a duplicate {}. Exception was raised: {}. Enable DEBUG for" + - " more detail.", - flowHashId.getFlowId().toString().substring(0, Math.min(TRUNCATED_LOG_MESSAGE_LENGTH,flowHashId.getFlowId().toString().length())), - e.getMessage().substring(0,Math.min(TRUNCATED_LOG_MESSAGE_LENGTH,e.getMessage().length()))); - } - } - } - } - } - } - - private void ensureTableFowHashIdMapping(final ReadWriteTransaction tx) { - if( ! tableEnsured) { - ensureTable(tx, tableKey.getId(), tableRef); - final FlowHashIdMapping emptyMapping = new FlowHashIdMappingBuilder() - .setFlowHashIdMap(Collections. emptyList()).build(); - tx.merge(LogicalDatastoreType.OPERATIONAL, tableRef.augmentation(FlowHashIdMapping.class), emptyMapping); - tableEnsured = true; - } - } - - private FlowKey searchInConfiguration(final FlowAndStatisticsMapList flowStat, final ReadWriteTransaction trans) { - initConfigFlows(); - final Iterator it = configFlows.iterator(); - while(it.hasNext()) { - final Flow cfgFlow = it.next(); - final FlowKey cfgKey = cfgFlow.getKey(); - final FlowId cfgFlowId = cfgKey.getId(); - - if(! flowIdByHash.inverse().containsKey(cfgFlowId)) { - if(FlowComparator.flowEquals(flowStat, cfgFlow)) { - return cfgKey; - } - } - } - return null; - } - - private void initConfigFlows() { - final Optional
table = readLatestConfiguration(tableRef); - List localList = null; - if(table.isPresent()) { - localList = table.get().getFlow(); - } - if(localList == null) { - configFlows = Collections.emptyList(); - } else { - configFlows = new ArrayList<>(localList); - } - } - - private FlowKey getFlowKeyByHash(final FlowHashIdMapKey key) { - final FlowId ret = flowIdByHash.get(key); - if(ret != null) { - return new FlowKey(ret); - } - return null; - } - - /* Returns FlowKey which doesn't exist in any DataStore for now */ - private FlowKey makeAlienFlowKey() { - final StringBuilder sBuilder = new StringBuilder(ALIEN_SYSTEM_FLOW_ID) - .append(tableKey.getId()).append("-").append(unaccountedFlowsCounter.incrementAndGet()); - final FlowId flowId = new FlowId(sBuilder.toString()); - return new FlowKey(flowId); - } - - private Map getRemovalList() { - return flowIdByHash; - } - - void reportFlow(final FlowAndStatisticsMapList flowStat, - final ReadWriteTransaction trans, - boolean wasRemoved) { - ensureTableFowHashIdMapping(trans); - final FlowHashIdMapKey hashingKey = new FlowHashIdMapKey(buildFlowIdOperKey(flowStat)); - FlowKey flowKey = getFlowKeyByHash(hashingKey); - if (flowKey == null || wasRemoved) { - flowKey = searchInConfiguration(flowStat, trans); - if ( flowKey == null) { - flowKey = makeAlienFlowKey(); - } - updateHashCache(trans,flowKey,hashingKey); - } else { - flowIdByHash.remove(hashingKey); - } - final FlowBuilder flowBuilder = new FlowBuilder(flowStat); - flowBuilder.setKey(flowKey); - addStatistics(flowBuilder, flowStat); - final InstanceIdentifier flowIdent = tableRef.child(Flow.class, flowKey); - trans.put(LogicalDatastoreType.OPERATIONAL, flowIdent, flowBuilder.build()); - /* check life for Alien flows */ - if (flowKey.getId().getValue().startsWith(ALIEN_SYSTEM_FLOW_ID)) { - removeData(flowIdent, REMOVE_AFTER_MISSING_COLLECTION); - } - } - - /* Build and deploy new FlowHashId map */ - private void updateHashCache(final ReadWriteTransaction trans, final FlowKey flowKey, final FlowHashIdMapKey hashingKey) { - final FlowHashIdMapBuilder flHashIdMap = new FlowHashIdMapBuilder(); - flHashIdMap.setFlowId(flowKey.getId()); - flHashIdMap.setKey(hashingKey); - final KeyedInstanceIdentifier flHashIdent = tableRef - .augmentation(FlowHashIdMapping.class).child(FlowHashIdMap.class, hashingKey); - /* Add new FlowHashIdMap */ - trans.put(LogicalDatastoreType.OPERATIONAL, flHashIdent, flHashIdMap.build()); - } - - void removeUnreportedFlows(final ReadWriteTransaction tx) { - final InstanceIdentifier nodeIdent = tableRef.firstIdentifierOf(Node.class); - final List> listMissingConfigFlows = notStatReportedConfigFlows(); - final Map, Integer> nodeDeleteMap = mapNodesForDelete.get(nodeIdent); - final Map listForRemove = getRemovalList(); - for (final Entry entryForRemove : listForRemove.entrySet()) { - final FlowKey flowKey = new FlowKey(entryForRemove.getValue()); - final InstanceIdentifier flowRef = tableRef.child(Flow.class, flowKey); - if (nodeDeleteMap != null && flowKey.getId().getValue().startsWith(ALIEN_SYSTEM_FLOW_ID)) { - final Integer lifeIndex = nodeDeleteMap.get(flowRef); - if (lifeIndex != null && lifeIndex > 0) { - break; - } else { - nodeDeleteMap.remove(flowRef); - } - } else { - if (listMissingConfigFlows.remove(flowRef)) { - // it is probable that some multipart message was lost - break; - } - } - final InstanceIdentifier flHashIdent = - tableRef.augmentation(FlowHashIdMapping.class).child(FlowHashIdMap.class, entryForRemove.getKey()); - tx.delete(LogicalDatastoreType.OPERATIONAL, flowRef); - tx.delete(LogicalDatastoreType.OPERATIONAL, flHashIdent); - } - } - - List> notStatReportedConfigFlows() { - if (configFlows != null) { - final List> returnList = new ArrayList<>(configFlows.size()); - for (final Flow confFlow : configFlows) { - final InstanceIdentifier confFlowIdent = tableRef.child(Flow.class, confFlow.getKey()); - returnList.add(confFlowIdent); - } - return returnList; - } - return Collections.emptyList(); - } - } -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitGroup.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitGroup.java deleted file mode 100644 index 278b5486b5..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitGroup.java +++ /dev/null @@ -1,385 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import java.util.UUID; -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.DataTreeModification; -import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatPermCollector.StatCapabTypes; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatRpcMsgManager.TransactionCacheContainer; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager.StatDataStoreOperation; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager.StatDataStoreOperation.StatsManagerOperationType; -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.transaction.rev150304.TransactionAware; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupDescStatsUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupFeaturesUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupStatisticsUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupDescStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupDescStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupStatistics; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupStatisticsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.OpendaylightGroupStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.group.desc.GroupDescBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.group.features.GroupFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.group.features.GroupFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.group.statistics.GroupStatistics; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.group.statistics.GroupStatisticsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.desc.stats.reply.GroupDescStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.statistics.reply.GroupStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.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.DataObject; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager.impl - * - * StatListenCommitGroup - * Class is a NotifyListener for GroupStatistics and DataTreeChangeListener for Config/DataStore for Group node. - * All expected (registered) GroupStatistics will be builded and commit to Operational/DataStore. - * DataTreeModification should call create/delete Group in Operational/DS - */ -public class StatListenCommitGroup extends StatAbstractListenCommit - implements OpendaylightGroupStatisticsListener { - - private static final Logger LOG = LoggerFactory.getLogger(StatListenCommitGroup.class); - - public StatListenCommitGroup(final StatisticsManager manager, final DataBroker db, - final NotificationProviderService nps, - final StatNodeRegistration nrm) { - super(manager, db, nps, Group.class,nrm); - } - - @Override - protected OpendaylightGroupStatisticsListener getStatNotificationListener() { - return this; - } - - @Override - protected InstanceIdentifier getWildCardedRegistrationPath() { - return InstanceIdentifier.create(Nodes.class).child(Node.class) - .augmentation(FlowCapableNode.class).child(Group.class); - } - - @Override - protected void processDataChange(Collection> changes) { - //NO-OP - } - - @Override - public void onGroupDescStatsUpdated(final GroupDescStatsUpdated notification) { - final TransactionId transId = notification.getTransactionId(); - final NodeId nodeId = notification.getId(); - if ( ! isExpectedStatistics(transId, nodeId)) { - LOG.debug("Unregistred notification detect TransactionId {}", transId); - return; - } - manager.getRpcMsgManager().addNotification(notification, nodeId); - if (notification.isMoreReplies()) { - return; - } - - /* Don't block RPC Notification thread */ - manager.enqueue(new StatDataStoreOperation(StatsManagerOperationType.DATA_COMMIT_OPER_DS,nodeId) { - @Override - public void applyOperation(final ReadWriteTransaction tx) { - final InstanceIdentifier nodeIdent = InstanceIdentifier - .create(Nodes.class).child(Node.class, new NodeKey(nodeId)); - /* Validate exist FlowCapableNode */ - final InstanceIdentifier fNodeIdent = nodeIdent.augmentation(FlowCapableNode.class); - Optional fNode = Optional.absent(); - try { - fNode = tx.read(LogicalDatastoreType.OPERATIONAL,fNodeIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read Operational/DS for FlowCapableNode fail! {}", fNodeIdent, e); - } - if ( ! fNode.isPresent()) { - return; - } - /* Get and Validate TransactionCacheContainer */ - final Optional> txContainer = getTransactionCacheContainer(transId, nodeId); - if ( ! isTransactionCacheContainerValid(txContainer)) { - return; - } - - if(!nodeRegistrationManager.isFlowCapableNodeOwner(nodeId)) { return; } - - /* Prepare List actual Groups and not updated Groups will be removed */ - final List existGroups = fNode.get().getGroup() != null - ? fNode.get().getGroup() : Collections. emptyList(); - final List existGroupKeys = new ArrayList<>(); - for (final Group group : existGroups) { - existGroupKeys.add(group.getKey()); - } - /* GroupDesc processing */ - statGroupDescCommit(txContainer, tx, fNodeIdent, existGroupKeys); - /* Delete all not presented Group Nodes */ - deleteAllNotPresentNode(fNodeIdent, tx, Collections.unmodifiableList(existGroupKeys)); - /* Notification for continue collecting statistics */ - notifyToCollectNextStatistics(nodeIdent, transId); - } - - @Override - public UUID generatedUUIDForNode() { - return manager.getGeneratedUUIDForNode(getNodeIdentifier()); - } - }); - } - - @Override - public void onGroupFeaturesUpdated(final GroupFeaturesUpdated notification) { - Preconditions.checkNotNull(notification); - final TransactionId transId = notification.getTransactionId(); - final NodeId nodeId = notification.getId(); - if ( ! isExpectedStatistics(transId, nodeId)) { - LOG.debug("Unregistred notification detect TransactionId {}", transId); - return; - } - manager.getRpcMsgManager().addNotification(notification, nodeId); - if (notification.isMoreReplies()) { - return; - } - - /* Don't block RPC Notification thread */ - manager.enqueue(new StatDataStoreOperation(StatsManagerOperationType.DATA_COMMIT_OPER_DS,nodeId) { - @Override - public void applyOperation(final ReadWriteTransaction tx) { - /* Get and Validate TransactionCacheContainer */ - final Optional> txContainer = getTransactionCacheContainer(transId, nodeId); - if ( ! isTransactionCacheContainerValid(txContainer)) { - return; - } - - final InstanceIdentifier nodeIdent = InstanceIdentifier - .create(Nodes.class).child(Node.class, new NodeKey(nodeId)); - - manager.registerAdditionalNodeFeature(nodeIdent, StatCapabTypes.GROUP_STATS); - - if(!nodeRegistrationManager.isFlowCapableNodeOwner(nodeId)) { return; } - - final List cacheNotifs = txContainer.get().getNotifications(); - for (final TransactionAware notif : cacheNotifs) { - if ( ! (notif instanceof GroupFeaturesUpdated)) { - break; - } - final GroupFeatures stats = new GroupFeaturesBuilder((GroupFeaturesUpdated)notif).build(); - final InstanceIdentifier nodeGroupFeatureIdent = - nodeIdent.augmentation(NodeGroupFeatures.class); - final InstanceIdentifier groupFeatureIdent = nodeGroupFeatureIdent - .child(GroupFeatures.class); - Optional node = Optional.absent(); - try { - node = tx.read(LogicalDatastoreType.OPERATIONAL, nodeIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read Operational/DS for Node fail! {}", nodeIdent, e); - } - if (node.isPresent()) { - tx.merge(LogicalDatastoreType.OPERATIONAL, nodeGroupFeatureIdent, new NodeGroupFeaturesBuilder().build(), true); - tx.put(LogicalDatastoreType.OPERATIONAL, groupFeatureIdent, stats); - manager.unregisterNodeStats(nodeIdent, StatCapabTypes.GROUP_FEATURE_STATS); - } else { - LOG.debug("Node {} is NOT present in the operational data store",nodeId); - } - } - } - - @Override - public UUID generatedUUIDForNode() { - return manager.getGeneratedUUIDForNode(getNodeIdentifier()); - } - }); - } - - @Override - public void onGroupStatisticsUpdated(final GroupStatisticsUpdated notification) { - Preconditions.checkNotNull(notification); - final TransactionId transId = notification.getTransactionId(); - final NodeId nodeId = notification.getId(); - if ( ! isExpectedStatistics(transId, nodeId)) { - LOG.debug("STAT-MANAGER - GroupStatisticsUpdated: unregistred notification detect TransactionId {}", transId); - return; - } - manager.getRpcMsgManager().addNotification(notification, nodeId); - if (notification.isMoreReplies()) { - return; - } - - /* Don't block RPC Notification thread */ - manager.enqueue(new StatDataStoreOperation(StatsManagerOperationType.DATA_COMMIT_OPER_DS,nodeId) { - @Override - public void applyOperation(final ReadWriteTransaction tx) { - - final InstanceIdentifier nodeIdent = InstanceIdentifier - .create(Nodes.class).child(Node.class, new NodeKey(nodeId)); - /* Node exist check */ - Optional node = Optional.absent(); - try { - node = tx.read(LogicalDatastoreType.OPERATIONAL, nodeIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read Operational/DS for Node fail! {}", nodeIdent, e); - } - if ( ! node.isPresent()) { - return; - } - - /* Get and Validate TransactionCacheContainer */ - final Optional> txContainer = getTransactionCacheContainer(transId, nodeId); - if ( ! isTransactionCacheContainerValid(txContainer)) { - return; - } - - if(!nodeRegistrationManager.isFlowCapableNodeOwner(nodeId)) { return; } - - final List cacheNotifs = txContainer.get().getNotifications(); - - Optional notifGroup = Optional.absent(); - final Optional inputObj = txContainer.get().getConfInput(); - if (inputObj.isPresent() && inputObj.get() instanceof Group) { - notifGroup = Optional. of((Group)inputObj.get()); - } - for (final TransactionAware notif : cacheNotifs) { - if ( ! (notif instanceof GroupStatisticsUpdated)) { - break; - } - statGroupCommit(((GroupStatisticsUpdated) notif).getGroupStats(), nodeIdent, tx); - } - if ( ! notifGroup.isPresent()) { - notifyToCollectNextStatistics(nodeIdent, transId); - } - } - - public UUID generatedUUIDForNode() { - return manager.getGeneratedUUIDForNode(getNodeIdentifier()); - } - }); - } - - private void statGroupCommit(final List groupStats, final InstanceIdentifier nodeIdent, - final ReadWriteTransaction tx) { - - Preconditions.checkNotNull(groupStats); - Preconditions.checkNotNull(nodeIdent); - Preconditions.checkNotNull(tx); - - final InstanceIdentifier fNodeIdent = nodeIdent.augmentation(FlowCapableNode.class); - - for (final GroupStats gStat : groupStats) { - final GroupStatistics stats = new GroupStatisticsBuilder(gStat).build(); - - final InstanceIdentifier groupIdent = fNodeIdent.child(Group.class, new GroupKey(gStat.getGroupId())); - final InstanceIdentifier nGroupStatIdent =groupIdent - .augmentation(NodeGroupStatistics.class); - final InstanceIdentifier gsIdent = nGroupStatIdent.child(GroupStatistics.class); - /* Statistics Writing */ - Optional group = Optional.absent(); - try { - group = tx.read(LogicalDatastoreType.OPERATIONAL, groupIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read Operational/DS for Group node fail! {}", groupIdent, e); - } - if (group.isPresent()) { - tx.merge(LogicalDatastoreType.OPERATIONAL, nGroupStatIdent, new NodeGroupStatisticsBuilder().build(), true); - tx.put(LogicalDatastoreType.OPERATIONAL, gsIdent, stats); - } - } - } - - private void statGroupDescCommit(final Optional> txContainer, final ReadWriteTransaction tx, - final InstanceIdentifier fNodeIdent, final List existGroupKeys) { - - Preconditions.checkNotNull(existGroupKeys); - Preconditions.checkNotNull(txContainer); - Preconditions.checkNotNull(fNodeIdent); - Preconditions.checkNotNull(tx); - - final List cacheNotifs = txContainer.get().getNotifications(); - for (final TransactionAware notif : cacheNotifs) { - if ( ! (notif instanceof GroupDescStatsUpdated)) { - break; - } - final List groupStats = ((GroupDescStatsUpdated) notif).getGroupDescStats(); - if (groupStats == null) { - break; - } - for (final GroupDescStats group : groupStats) { - if (group.getGroupId() != null) { - final GroupBuilder groupBuilder = new GroupBuilder(group); - final GroupKey groupKey = new GroupKey(group.getGroupId()); - final InstanceIdentifier groupRef = fNodeIdent.child(Group.class,groupKey); - - final NodeGroupDescStatsBuilder groupDesc= new NodeGroupDescStatsBuilder(); - groupDesc.setGroupDesc(new GroupDescBuilder(group).build()); - //Update augmented data - groupBuilder.addAugmentation(NodeGroupDescStats.class, groupDesc.build()); - existGroupKeys.remove(groupKey); - tx.put(LogicalDatastoreType.OPERATIONAL, groupRef, groupBuilder.build()); - } - } - } - } - - private void deleteAllNotPresentNode(final InstanceIdentifier fNodeIdent, - final ReadWriteTransaction trans, final List deviceGroupKeys) { - - Preconditions.checkNotNull(fNodeIdent); - Preconditions.checkNotNull(trans); - - if (deviceGroupKeys == null) { - return; - } - - for (final GroupKey key : deviceGroupKeys) { - final InstanceIdentifier delGroupIdent = fNodeIdent.child(Group.class, key); - LOG.trace("Group {} has to removed.", key); - Optional delGroup = Optional.absent(); - try { - delGroup = trans.read(LogicalDatastoreType.OPERATIONAL, delGroupIdent).checkedGet(); - } - catch (final ReadFailedException e) { - // NOOP - probably another transaction delete that node - LOG.debug("Group {} was probably deleted via other transaction. Exception {}", delGroupIdent, e); - } - if (delGroup.isPresent()) { - trans.delete(LogicalDatastoreType.OPERATIONAL, delGroupIdent); - } - } - } -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitMeter.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitMeter.java deleted file mode 100644 index 58b57b7891..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitMeter.java +++ /dev/null @@ -1,384 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.UUID; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.api.DataTreeModification; -import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatPermCollector.StatCapabTypes; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatRpcMsgManager.TransactionCacheContainer; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager.StatDataStoreOperation; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager.StatDataStoreOperation.StatsManagerOperationType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionAware; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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.meter.statistics.rev131111.MeterConfigStatsUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterFeaturesUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterStatisticsUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterConfigStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterConfigStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterStatistics; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterStatisticsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.OpendaylightMeterStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.nodes.node.MeterFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.nodes.node.MeterFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.nodes.node.meter.MeterConfigStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.nodes.node.meter.MeterStatistics; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.nodes.node.meter.MeterStatisticsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.config.stats.reply.MeterConfigStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.statistics.reply.MeterStats; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager.impl - * - * StatListenCommitMeter - * Class is a NotifyListener for MeterStatistics and DataTreeChangeListener for Config/DataStore for Meter node. - * All expected (registered) MeterStatistics will be builded and commit to Operational/DataStore. - * DataTreeModification should call create/delete Meter in Operational/DS - */ -public class StatListenCommitMeter extends StatAbstractListenCommit - implements OpendaylightMeterStatisticsListener { - - private static final Logger LOG = LoggerFactory.getLogger(StatListenCommitMeter.class); - - public StatListenCommitMeter(final StatisticsManager manager, final DataBroker db, - final NotificationProviderService nps, - final StatNodeRegistration nrm) { - super(manager, db, nps, Meter.class,nrm); - } - - @Override - protected InstanceIdentifier getWildCardedRegistrationPath() { - return InstanceIdentifier.create(Nodes.class).child(Node.class) - .augmentation(FlowCapableNode.class).child(Meter.class); - } - - @Override - protected void processDataChange(Collection> changes) { - //NO-OP - } - - @Override - protected OpendaylightMeterStatisticsListener getStatNotificationListener() { - return this; - } - - @Override - public void onMeterConfigStatsUpdated(final MeterConfigStatsUpdated notification) { - final TransactionId transId = notification.getTransactionId(); - final NodeId nodeId = notification.getId(); - if ( ! isExpectedStatistics(transId, nodeId)) { - LOG.debug("STAT-MANAGER - MeterConfigStatsUpdated: unregistred notification detect TransactionId {}", transId); - return; - } - manager.getRpcMsgManager().addNotification(notification, nodeId); - if (notification.isMoreReplies()) { - return; - } - - /* Don't block RPC Notification thread */ - manager.enqueue(new StatDataStoreOperation(StatsManagerOperationType.DATA_COMMIT_OPER_DS,nodeId) { - @Override - public void applyOperation(final ReadWriteTransaction tx) { - - final InstanceIdentifier nodeIdent = InstanceIdentifier - .create(Nodes.class).child(Node.class, new NodeKey(nodeId)); - - /* Validate exist FlowCapableNode */ - final InstanceIdentifier fNodeIdent = nodeIdent.augmentation(FlowCapableNode.class); - Optional fNode = Optional.absent(); - try { - fNode = tx.read(LogicalDatastoreType.OPERATIONAL,fNodeIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read Operational/DS for FlowCapableNode fail! {}", fNodeIdent, e); - } - if ( ! fNode.isPresent()) { - return; - } - /* Get and Validate TransactionCacheContainer */ - final Optional> txContainer = getTransactionCacheContainer(transId, nodeId); - if ( ! isTransactionCacheContainerValid(txContainer)) { - return; - } - - if(!nodeRegistrationManager.isFlowCapableNodeOwner(nodeId)) { return; } - /* Prepare List actual Meters and not updated Meters will be removed */ - final List existMeters = fNode.get().getMeter() != null - ? fNode.get().getMeter() : Collections. emptyList(); - final List existMeterKeys = new ArrayList<>(); - for (final Meter meter : existMeters) { - existMeterKeys.add(meter.getKey()); - } - /* MeterConfig processing */ - comitConfMeterStats(txContainer, tx, fNodeIdent, existMeterKeys); - /* Delete all not presented Meter Nodes */ - deleteAllNotPresentedNodes(fNodeIdent, tx, Collections.unmodifiableList(existMeterKeys)); - /* Notification for continue collecting statistics */ - notifyToCollectNextStatistics(nodeIdent, transId); - } - - public UUID generatedUUIDForNode() { - return manager.getGeneratedUUIDForNode(getNodeIdentifier()); - } - }); - } - - @Override - public void onMeterFeaturesUpdated(final MeterFeaturesUpdated notification) { - Preconditions.checkNotNull(notification); - final TransactionId transId = notification.getTransactionId(); - final NodeId nodeId = notification.getId(); - if ( ! isExpectedStatistics(transId, nodeId)) { - LOG.debug("STAT-MANAGER - MeterFeaturesUpdated: unregistred notification detect TransactionId {}", transId); - return; - } - manager.getRpcMsgManager().addNotification(notification, nodeId); - if (notification.isMoreReplies()) { - return; - } - - /* Don't block RPC Notification thread */ - manager.enqueue(new StatDataStoreOperation(StatsManagerOperationType.DATA_COMMIT_OPER_DS,nodeId) { - @Override - public void applyOperation(final ReadWriteTransaction tx) { - /* Get and Validate TransactionCacheContainer */ - final Optional> txContainer = getTransactionCacheContainer(transId, nodeId); - if ( ! isTransactionCacheContainerValid(txContainer)) { - return; - } - - final InstanceIdentifier nodeIdent = InstanceIdentifier - .create(Nodes.class).child(Node.class, new NodeKey(nodeId)); - - //Register meter feature irrespective of whether this instance is - //master instance of the device or not. In cluster mode, all instances - // should have knowledge if meter is supported by the device. - manager.registerAdditionalNodeFeature(nodeIdent, StatCapabTypes.METER_STATS); - - if(!nodeRegistrationManager.isFlowCapableNodeOwner(nodeId)) { return; } - - final List cacheNotifs = txContainer.get().getNotifications(); - for (final TransactionAware notif : cacheNotifs) { - if ( ! (notif instanceof MeterFeaturesUpdated)) { - break; - } - final MeterFeatures stats = new MeterFeaturesBuilder((MeterFeaturesUpdated)notif).build(); - final InstanceIdentifier nodeMeterFeatureIdent = - nodeIdent.augmentation(NodeMeterFeatures.class); - final InstanceIdentifier meterFeatureIdent = nodeMeterFeatureIdent - .child(MeterFeatures.class); - Optional node = Optional.absent(); - try { - node = tx.read(LogicalDatastoreType.OPERATIONAL, nodeIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read Operational/DS for Node fail! {}", nodeIdent, e); - } - if (node.isPresent()) { - tx.merge(LogicalDatastoreType.OPERATIONAL, nodeMeterFeatureIdent, new NodeMeterFeaturesBuilder().build(), true); - tx.put(LogicalDatastoreType.OPERATIONAL, meterFeatureIdent, stats); - manager.unregisterNodeStats(nodeIdent, StatCapabTypes.METER_FEATURE_STATS); - } else { - LOG.debug("Node {} is NOT present in the operational data store",nodeId); - } - } - } - - @Override - public UUID generatedUUIDForNode() { - return manager.getGeneratedUUIDForNode(getNodeIdentifier()); - } - }); - } - - @Override - public void onMeterStatisticsUpdated(final MeterStatisticsUpdated notification) { - Preconditions.checkNotNull(notification); - final TransactionId transId = notification.getTransactionId(); - final NodeId nodeId = notification.getId(); - if ( ! isExpectedStatistics(transId, nodeId)) { - LOG.debug("STAT-MANAGER - MeterStatisticsUpdated: unregistred notification detect TransactionId {}", transId); - return; - } - manager.getRpcMsgManager().addNotification(notification, nodeId); - if (notification.isMoreReplies()) { - return; - } - - /* Don't block RPC Notification thread */ - manager.enqueue(new StatDataStoreOperation(StatsManagerOperationType.DATA_COMMIT_OPER_DS,nodeId) { - @Override - public void applyOperation(final ReadWriteTransaction tx) { - - final InstanceIdentifier nodeIdent = InstanceIdentifier - .create(Nodes.class).child(Node.class, new NodeKey(nodeId)); - /* Node exist check */ - Optional node = Optional.absent(); - try { - node = tx.read(LogicalDatastoreType.OPERATIONAL, nodeIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read Operational/DS for Node fail! {}", nodeIdent, e); - } - if ( ! node.isPresent()) { - return; - } - - /* Get and Validate TransactionCacheContainer */ - final Optional> txContainer = getTransactionCacheContainer(transId, nodeId); - if ( ! isTransactionCacheContainerValid(txContainer)) { - return; - } - if(!nodeRegistrationManager.isFlowCapableNodeOwner(nodeId)) { return; } - - final List cacheNotifs = txContainer.get().getNotifications(); - - Optional notifMeter = Optional.absent(); - final Optional inputObj = txContainer.get().getConfInput(); - if (inputObj.isPresent() && inputObj.get() instanceof Meter) { - notifMeter = Optional. of((Meter)inputObj.get()); - } - for (final TransactionAware notif : cacheNotifs) { - if ( ! (notif instanceof MeterStatisticsUpdated)) { - break; - } - statMeterCommit(((MeterStatisticsUpdated) notif).getMeterStats(), nodeIdent, tx); - } - if ( ! notifMeter.isPresent()) { - notifyToCollectNextStatistics(nodeIdent, transId); - } - } - - @Override - public UUID generatedUUIDForNode() { - return manager.getGeneratedUUIDForNode(getNodeIdentifier()); - } - }); - } - - private void statMeterCommit(final List meterStats, - final InstanceIdentifier nodeIdent, final ReadWriteTransaction tx) { - - Preconditions.checkNotNull(meterStats); - Preconditions.checkNotNull(nodeIdent); - Preconditions.checkNotNull(tx); - - final InstanceIdentifier fNodeIdent = nodeIdent.augmentation(FlowCapableNode.class); - - for (final MeterStats mStat : meterStats) { - final MeterStatistics stats = new MeterStatisticsBuilder(mStat).build(); - - final InstanceIdentifier meterIdent = fNodeIdent.child(Meter.class, new MeterKey(mStat.getMeterId())); - final InstanceIdentifier nodeMeterStatIdent = meterIdent - .augmentation(NodeMeterStatistics.class); - final InstanceIdentifier msIdent = nodeMeterStatIdent.child(MeterStatistics.class); - /* Meter Statistics commit */ - Optional meter = Optional.absent(); - try { - meter = tx.read(LogicalDatastoreType.OPERATIONAL, meterIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read Operational/DS for FlowCapableNode fail! {}", fNodeIdent, e); - } - if (meter.isPresent()) { - tx.merge(LogicalDatastoreType.OPERATIONAL, nodeMeterStatIdent, new NodeMeterStatisticsBuilder().build(), true); - tx.put(LogicalDatastoreType.OPERATIONAL, msIdent, stats); - } - } - } - - private void comitConfMeterStats(final Optional> txContainer, final ReadWriteTransaction tx, - final InstanceIdentifier fNodeIdent, final List existMeterKeys) { - - Preconditions.checkNotNull(existMeterKeys); - Preconditions.checkNotNull(txContainer); - Preconditions.checkNotNull(fNodeIdent); - Preconditions.checkNotNull(tx); - - final List cacheNotifs = txContainer.get().getNotifications(); - for (final TransactionAware notif : cacheNotifs) { - if ( ! (notif instanceof MeterConfigStatsUpdated)) { - break; - } - final List meterStats = ((MeterConfigStatsUpdated) notif).getMeterConfigStats(); - if (meterStats == null) { - break; - } - for (final MeterConfigStats meterStat : meterStats) { - if (meterStat.getMeterId() != null) { - final MeterBuilder meterBuilder = new MeterBuilder(meterStat); - final MeterKey meterKey = new MeterKey(meterStat.getMeterId()); - final InstanceIdentifier meterRef = fNodeIdent.child(Meter.class, meterKey); - - final NodeMeterConfigStatsBuilder meterConfig = new NodeMeterConfigStatsBuilder(); - meterConfig.setMeterConfigStats(new MeterConfigStatsBuilder(meterStat).build()); - //Update augmented data - meterBuilder.addAugmentation(NodeMeterConfigStats.class, meterConfig.build()); - existMeterKeys.remove(meterKey); - tx.put(LogicalDatastoreType.OPERATIONAL, meterRef, meterBuilder.build()); - } - } - } - } - - private void deleteAllNotPresentedNodes(final InstanceIdentifier fNodeIdent, - final ReadWriteTransaction tx, final List deviceMeterKeys) { - - Preconditions.checkNotNull(fNodeIdent); - Preconditions.checkNotNull(tx); - - if (deviceMeterKeys == null) { - return; - } - - for (final MeterKey key : deviceMeterKeys) { - final InstanceIdentifier delMeterIdent = fNodeIdent.child(Meter.class, key); - LOG.trace("Meter {} has to removed.", key); - Optional delMeter = Optional.absent(); - try { - delMeter = tx.read(LogicalDatastoreType.OPERATIONAL, delMeterIdent).checkedGet(); - } - catch (final ReadFailedException e) { - // NOOP - probably another transaction delete that node - LOG.debug("Meter {} was probably deleted via other transaction. Exception {}", delMeterIdent, e); - } - if (delMeter.isPresent()) { - tx.delete(LogicalDatastoreType.OPERATIONAL, delMeterIdent); - } - } - } -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitQueue.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitQueue.java deleted file mode 100644 index cdfb8ced88..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitQueue.java +++ /dev/null @@ -1,233 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import java.util.UUID; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.api.DataTreeModification; -import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatRpcMsgManager.TransactionCacheContainer; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager.StatDataStoreOperation; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager.StatDataStoreOperation.StatsManagerOperationType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionAware; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.Queue; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.QueueBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.QueueKey; -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.node.NodeConnectorKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.FlowCapableNodeConnectorQueueStatisticsData; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.FlowCapableNodeConnectorQueueStatisticsDataBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.OpendaylightQueueStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.QueueStatisticsUpdate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.flow.capable.node.connector.queue.statistics.FlowCapableNodeConnectorQueueStatistics; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.flow.capable.node.connector.queue.statistics.FlowCapableNodeConnectorQueueStatisticsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.queue.id.and.statistics.map.QueueIdAndStatisticsMap; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager.impl - * - * StatNotifyCommitQueue - * Class is a NotifyListner for Queues Statistics - * All expected (registered) queueStatistics will be builded and - * commit to Operational/DataStore - * - * @author Vaclav Demcak - * - */ -public class StatListenCommitQueue extends StatAbstractListenCommit - implements OpendaylightQueueStatisticsListener { - - private static final Logger LOG = LoggerFactory.getLogger(StatListenCommitQueue.class); - - public StatListenCommitQueue(final StatisticsManager manager, final DataBroker db, - final NotificationProviderService nps, - final StatNodeRegistration nrm) { - super(manager, db, nps, Queue.class,nrm); - } - - @Override - protected OpendaylightQueueStatisticsListener getStatNotificationListener() { - return this; - } - - @Override - protected InstanceIdentifier getWildCardedRegistrationPath() { - return InstanceIdentifier.create(Nodes.class).child(Node.class).child(NodeConnector.class) - .augmentation(FlowCapableNodeConnector.class).child(Queue.class); - } - - @Override - protected void processDataChange(Collection> changes) { - //NO-OP - } - - @Override - public void onQueueStatisticsUpdate(final QueueStatisticsUpdate notification) { - final TransactionId transId = notification.getTransactionId(); - final NodeId nodeId = notification.getId(); - if ( ! isExpectedStatistics(transId, nodeId)) { - LOG.debug("STAT-MANAGER - QueueStatisticsUpdate: unregistred notification detect TransactionId {}", transId); - return; - } - manager.getRpcMsgManager().addNotification(notification, nodeId); - if (notification.isMoreReplies()) { - return; - } - - /* Don't block RPC Notification thread */ - manager.enqueue(new StatDataStoreOperation(StatsManagerOperationType.DATA_COMMIT_OPER_DS,nodeId) { - @Override - public void applyOperation(final ReadWriteTransaction tx) { - - final InstanceIdentifier nodeIdent = InstanceIdentifier.create(Nodes.class) - .child(Node.class, new NodeKey(nodeId)); - - /* Validate exist Node */ - Optional fNode = Optional.absent(); - try { - fNode = tx.read(LogicalDatastoreType.OPERATIONAL, nodeIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read Operational/DS for Node fail! {}", nodeIdent, e); - } - if ( ! fNode.isPresent()) { - LOG.trace("Read Operational/DS for Node fail! Node {} doesn't exist.", nodeIdent); - return; - } - - /* Get and Validate TransactionCacheContainer */ - final Optional> txContainer = getTransactionCacheContainer(transId, nodeId); - if ( ! isTransactionCacheContainerValid(txContainer)) { - return; - } - - if(!nodeRegistrationManager.isFlowCapableNodeOwner(nodeId)) { return; } - - /* Prepare List actual Queues and not updated Queues will be removed */ - final List existConnectors = fNode.get().getNodeConnector() != null - ? fNode.get().getNodeConnector() : Collections. emptyList(); - final Map existQueueKeys = new HashMap<>(); - for (final NodeConnector connect : existConnectors) { - if(connect.getAugmentation(FlowCapableNodeConnector.class) != null){ - final List listQueues = connect.getAugmentation(FlowCapableNodeConnector.class).getQueue(); - if (listQueues != null) { - for (final Queue queue : listQueues) { - existQueueKeys.put(queue.getKey(), connect.getKey()); - } - } - } - } - /* Queue processing */ - statQueueCommit(txContainer, tx, nodeIdent, existQueueKeys); - /* Delete all not presented Group Nodes */ - deleteAllNotPresentedNodes(nodeIdent, tx, Collections.unmodifiableMap(existQueueKeys)); - /* Notification for continue collecting statistics */ - notifyToCollectNextStatistics(nodeIdent, transId); - } - - @Override - public UUID generatedUUIDForNode() { - return manager.getGeneratedUUIDForNode(getNodeIdentifier()); - } - }); - } - - private void statQueueCommit( - final Optional> txContainer, final ReadWriteTransaction tx, - final InstanceIdentifier nodeIdent, final Map existQueueKeys) { - - Preconditions.checkNotNull(existQueueKeys); - Preconditions.checkNotNull(txContainer); - Preconditions.checkNotNull(nodeIdent); - Preconditions.checkNotNull(tx); - - final List cacheNotifs = txContainer.get().getNotifications(); - for (final TransactionAware notif : cacheNotifs) { - if ( ! (notif instanceof QueueStatisticsUpdate)) { - break; - } - final List queueStats = ((QueueStatisticsUpdate) notif).getQueueIdAndStatisticsMap(); - if (queueStats == null) { - break; - } - for (final QueueIdAndStatisticsMap queueStat : queueStats) { - if (queueStat.getQueueId() != null) { - final FlowCapableNodeConnectorQueueStatistics statChild = - new FlowCapableNodeConnectorQueueStatisticsBuilder(queueStat).build(); - final FlowCapableNodeConnectorQueueStatisticsDataBuilder statBuild = - new FlowCapableNodeConnectorQueueStatisticsDataBuilder(); - statBuild.setFlowCapableNodeConnectorQueueStatistics(statChild); - final QueueKey qKey = new QueueKey(queueStat.getQueueId()); - final InstanceIdentifier queueIdent = nodeIdent - .child(NodeConnector.class, new NodeConnectorKey(queueStat.getNodeConnectorId())) - .augmentation(FlowCapableNodeConnector.class) - .child(Queue.class, qKey); - final InstanceIdentifier queueStatIdent = queueIdent.augmentation(FlowCapableNodeConnectorQueueStatisticsData.class); - existQueueKeys.remove(qKey); - tx.merge(LogicalDatastoreType.OPERATIONAL, queueIdent, new QueueBuilder().setKey(qKey).build()); - tx.put(LogicalDatastoreType.OPERATIONAL, queueStatIdent, statBuild.build()); - } - } - } - } - - private void deleteAllNotPresentedNodes(final InstanceIdentifier nodeIdent, - final ReadWriteTransaction tx, final Map existQueueKeys) { - - Preconditions.checkNotNull(nodeIdent); - Preconditions.checkNotNull(tx); - - if (existQueueKeys == null) { - return; - } - - for (final Entry entry : existQueueKeys.entrySet()) { - final InstanceIdentifier queueIdent = nodeIdent.child(NodeConnector.class, entry.getValue()) - .augmentation(FlowCapableNodeConnector.class).child(Queue.class, entry.getKey()); - LOG.trace("Queue {} has to removed.", queueIdent); - Optional delQueue = Optional.absent(); - try { - delQueue = tx.read(LogicalDatastoreType.OPERATIONAL, queueIdent).checkedGet(); - } - catch (final ReadFailedException e) { - // NOOP - probably another transaction delete that node - LOG.debug("Queue {} was probably deleted via another transaction. Exception {}", queueIdent, e); - } - if (delQueue.isPresent()) { - tx.delete(LogicalDatastoreType.OPERATIONAL, queueIdent); - } - } - } -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatNodeRegistrationImpl.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatNodeRegistrationImpl.java deleted file mode 100644 index b590f3356e..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatNodeRegistrationImpl.java +++ /dev/null @@ -1,265 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; -import org.opendaylight.controller.md.sal.common.api.clustering.Entity; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListenerRegistration; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatPermCollector.StatCapabTypes; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FeatureCapability; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityFlowStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityGroupStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityPortStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityQueueStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityTableStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.flow.node.SwitchFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRemoved; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRemoved; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; -import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager.impl - * - * @author Vaclav Demcak - * - * Created: Aug 28, 2014 - */ -public class StatNodeRegistrationImpl implements StatNodeRegistration,EntityOwnershipListener { - - private static final Logger LOG = LoggerFactory.getLogger(StatNodeRegistrationImpl.class); - - private static final QName ENTITY_QNAME = - org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.core.general.entity.rev150820.Entity.QNAME; - private static final QName ENTITY_NAME = QName.create(ENTITY_QNAME, "name"); - - private final StatisticsManager manager; - private ListenerRegistration notifListenerRegistration; - //private DataBroker db; - private EntityOwnershipListenerRegistration ofListenerRegistration = null; - private final Map nodeOwnershipState = new ConcurrentHashMap(); - - - public StatNodeRegistrationImpl(final StatisticsManager manager, final DataBroker db, - final NotificationProviderService notificationService) { - this.manager = Preconditions.checkNotNull(manager, "StatisticManager can not be null!"); - //this.db = Preconditions.checkNotNull(db, "DataBroker can not be null!"); - Preconditions.checkArgument(notificationService != null, "NotificationProviderService can not be null!"); - notifListenerRegistration = notificationService.registerNotificationListener(this); - - if(manager.getOwnershipService() != null) { - ofListenerRegistration = manager.getOwnershipService().registerListener("openflow", this); - } - } - - @Override - public void close() throws Exception { - - if (notifListenerRegistration != null) { - try { - notifListenerRegistration.close(); - } - catch (final Exception e) { - LOG.warn("Error by stop FlowCapableNode Notification StatNodeRegistration. Exception {}", e); - } - notifListenerRegistration = null; - } - - if (ofListenerRegistration!= null) { - try { - ofListenerRegistration.close(); - } catch (final Exception e) { - LOG.warn("Error by stop FlowCapableNode EntityOwnershipListener.", e); - } - ofListenerRegistration = null; - } - } - - @Override - public void connectFlowCapableNode(final InstanceIdentifier keyIdent, - final SwitchFeatures data, final InstanceIdentifier nodeIdent) { - Preconditions.checkNotNull(keyIdent, "InstanceIdentifier can not be null!"); - Preconditions.checkNotNull(data, "SwitchFeatures data for {} can not be null!", keyIdent); - Preconditions.checkArgument(( ! keyIdent.isWildcarded()), "InstanceIdentifier is WildCarded!"); - - LOG.trace("STAT-MANAGER - connecting flow capable node {}", nodeIdent); - final List statCapabTypes = new ArrayList<>(); - Short maxCapTables = Short.valueOf("1"); - - final List> capabilities = data.getCapabilities() != null - ? data.getCapabilities() : Collections.> emptyList(); - for (final Class capability : capabilities) { - if (FlowFeatureCapabilityTableStats.class.equals(capability)) { - statCapabTypes.add(StatCapabTypes.TABLE_STATS); - } else if (FlowFeatureCapabilityFlowStats.class.equals(capability)) { - statCapabTypes.add(StatCapabTypes.FLOW_STATS); - } else if (FlowFeatureCapabilityGroupStats.class.equals(capability)) { - statCapabTypes.add(StatCapabTypes.GROUP_STATS); - } else if (FlowFeatureCapabilityPortStats.class.equals(capability)) { - statCapabTypes.add(StatCapabTypes.PORT_STATS); - } else if (FlowFeatureCapabilityQueueStats.class.equals(capability)) { - statCapabTypes.add(StatCapabTypes.QUEUE_STATS); - } - } - - statCapabTypes.add(StatCapabTypes.GROUP_FEATURE_STATS); - statCapabTypes.add(StatCapabTypes.METER_FEATURE_STATS); - - maxCapTables = data.getMaxTables(); - - final Optional maxTables = Optional. of(maxCapTables); - manager.connectedNodeRegistration(nodeIdent, Collections.unmodifiableList(statCapabTypes), maxTables.get()); - } - - @Override - public void disconnectFlowCapableNode(final InstanceIdentifier nodeIdent) { - Preconditions.checkArgument(nodeIdent != null, "InstanceIdentifier can not be NULL!"); - Preconditions.checkArgument(( ! nodeIdent.isWildcarded()), - "InstanceIdentifier {} is WildCarded!", nodeIdent); - LOG.trace("STAT-MANAGER - disconnect flow capable node {}", nodeIdent); - manager.disconnectedNodeUnregistration(nodeIdent); - } - - private boolean preConfigurationCheck(final NodeId nodeId) { - Preconditions.checkNotNull(nodeId, "Node Instance Identifier can not be null!"); - final Entity entity = getEntity(nodeId); - EntityOwnershipService ownershipService = manager.getOwnershipService(); - if(ownershipService == null) { - LOG.error("preConfigurationCheck: EntityOwnershipService is null"); - return false; - } - Optional entityOwnershipStateOptional = ownershipService.getOwnershipState(entity); - if(!entityOwnershipStateOptional.isPresent()) { //abset - assume this ofp is owning entity - LOG.warn("preConfigurationCheck: Entity state of {} is absent - acting as a non-owner",nodeId.getValue()); - return false; - } - final EntityOwnershipState entityOwnershipState = entityOwnershipStateOptional.get(); - if(!(entityOwnershipState.hasOwner() && entityOwnershipState.isOwner())) { - LOG.info("preConfigurationCheck: Controller is not the owner of {}",nodeId.getValue()); - return false; - } - return true; - } - - @Override - public void onNodeConnectorRemoved(final NodeConnectorRemoved notification) { - // NOOP - } - - @Override - public void onNodeConnectorUpdated(final NodeConnectorUpdated notification) { - // NOOP - } - - @Override - public void onNodeRemoved(final NodeRemoved notification) { - Preconditions.checkNotNull(notification); - final NodeRef nodeRef = notification.getNodeRef(); - final InstanceIdentifier nodeRefIdent = nodeRef.getValue(); - final InstanceIdentifier nodeIdent = - nodeRefIdent.firstIdentifierOf(Node.class); - if (nodeIdent != null) { - LOG.debug("Received onNodeRemoved for node:{} ", nodeIdent); - removeOwnership(InstanceIdentifier.keyOf(nodeIdent).getId()); - disconnectFlowCapableNode(nodeIdent); - } - } - - @Override - public void onNodeUpdated(final NodeUpdated notification) { - Preconditions.checkNotNull(notification); - final FlowCapableNodeUpdated newFlowNode = - notification.getAugmentation(FlowCapableNodeUpdated.class); - LOG.info("Received onNodeUpdated for node {} ", newFlowNode); - if (newFlowNode != null && newFlowNode.getSwitchFeatures() != null) { - final NodeRef nodeRef = notification.getNodeRef(); - final InstanceIdentifier nodeRefIdent = nodeRef.getValue(); - final InstanceIdentifier nodeIdent = - nodeRefIdent.firstIdentifierOf(Node.class); - - final InstanceIdentifier swichFeaturesIdent = - nodeIdent.augmentation(FlowCapableNode.class).child(SwitchFeatures.class); - final SwitchFeatures switchFeatures = newFlowNode.getSwitchFeatures(); - connectFlowCapableNode(swichFeaturesIdent, switchFeatures, nodeIdent); - - //Send group/meter request to get addition details not present in switch feature response. - NodeId nodeId = InstanceIdentifier.keyOf(nodeIdent).getId(); - boolean ownershipState = preConfigurationCheck(nodeId); - setNodeOwnership(nodeId, ownershipState); - LOG.info("onNodeUpdated: Send group/meter feature request to the device {}",nodeIdent); - manager.getRpcMsgManager().getGroupFeaturesStat(nodeRef); - manager.getRpcMsgManager().getMeterFeaturesStat(nodeRef); - } - } - - @Override - public boolean isFlowCapableNodeOwner(NodeId node) { - if(this.nodeOwnershipState.containsKey(node)){ - boolean state = this.nodeOwnershipState.get(node).booleanValue(); - LOG.debug("Is Node {} owned by this instance : {}",node, state); - return state; - } - return false; - } - - @Override - public void ownershipChanged(EntityOwnershipChange ownershipChange) { - - YangInstanceIdentifier yId = ownershipChange.getEntity().getId(); - NodeIdentifierWithPredicates niWPredicates = (NodeIdentifierWithPredicates)yId.getLastPathArgument(); - Map keyValMap = niWPredicates.getKeyValues(); - String nodeIdStr = (String)(keyValMap.get(ENTITY_NAME)); - NodeId nodeId = new NodeId(nodeIdStr); - setNodeOwnership(nodeId, ownershipChange.isOwner()); - } - - private void setNodeOwnership(NodeId node, boolean ownership) { - LOG.debug("Set {} ownership for Node {}",ownership?"Master":"Slave",node); - this.nodeOwnershipState.put(node,ownership); - } - - private void removeOwnership(NodeId node) { - this.nodeOwnershipState.remove(node); - } - - private Entity getEntity(NodeId nodeId) { - return new Entity("openflow", nodeId.getValue()); - } - -} diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatNotifyCommitPort.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatNotifyCommitPort.java deleted file mode 100644 index 77e00c9422..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatNotifyCommitPort.java +++ /dev/null @@ -1,165 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import java.util.ArrayList; -import java.util.List; - -import java.util.UUID; -import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatRpcMsgManager.TransactionCacheContainer; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager.StatDataStoreOperation; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager.StatDataStoreOperation.StatsManagerOperationType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionAware; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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.node.NodeConnectorBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsData; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsDataBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.NodeConnectorStatisticsUpdate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.OpendaylightPortStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.flow.capable.node.connector.statistics.FlowCapableNodeConnectorStatistics; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.flow.capable.node.connector.statistics.FlowCapableNodeConnectorStatisticsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMap; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Optional; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager.impl - * - * StatNotifyCommitPort - * Class is a NotifyListener for PortStatistics - * All expected (registered) portStatistics will be builded and - * commit to Operational/DataStore - * - * @author Vaclav Demcak - * - */ -public class StatNotifyCommitPort extends StatAbstractNotifyCommit - implements OpendaylightPortStatisticsListener { - - private static final Logger LOG = LoggerFactory.getLogger(StatNotifyCommitPort.class); - - public StatNotifyCommitPort(final StatisticsManager manager, - final NotificationProviderService nps, - final StatNodeRegistration nrm) { - super(manager, nps,nrm); - } - - @Override - protected OpendaylightPortStatisticsListener getStatNotificationListener() { - return this; - } - - @Override - public void onNodeConnectorStatisticsUpdate(final NodeConnectorStatisticsUpdate notification) { - final TransactionId transId = notification.getTransactionId(); - final NodeId nodeId = notification.getId(); - if ( ! isExpectedStatistics(transId, nodeId)) { - LOG.debug("STAT-MANAGER - NodeConnectorStatisticsUpdate: unregistred notification detect TransactionId {}", transId); - return; - } - manager.getRpcMsgManager().addNotification(notification, nodeId); - if (notification.isMoreReplies()) { - return; - } - final InstanceIdentifier nodeIdent = InstanceIdentifier.create(Nodes.class) - .child(Node.class, new NodeKey(nodeId)); - /* Don't block RPC Notification thread */ - manager.enqueue(new StatDataStoreOperation(StatsManagerOperationType.DATA_COMMIT_OPER_DS,nodeId) { - @Override - public void applyOperation(final ReadWriteTransaction trans) { - final Optional> txContainer = getTransactionCacheContainer(transId, nodeId); - if (( ! txContainer.isPresent()) || txContainer.get().getNotifications() == null) { - return; - } - - if(!nodeRegistrationManager.isFlowCapableNodeOwner(nodeId)) { return; } - - final List portStats = - new ArrayList(10); - final List cachedNotifs = txContainer.get().getNotifications(); - for (final TransactionAware notif : cachedNotifs) { - if (notif instanceof NodeConnectorStatisticsUpdate) { - final List notifStat = - ((NodeConnectorStatisticsUpdate) notif).getNodeConnectorStatisticsAndPortNumberMap(); - if (notifStat != null) { - portStats.addAll(notifStat); - } - } - } - /* write stat to trans */ - statPortCommit(portStats, nodeIdent, trans); - /* Notification for continue collecting statistics - Port statistics are still same size - * and they are small - don't need to wait for whole apply operation*/ - notifyToCollectNextStatistics(nodeIdent, transId); - } - - @Override - public UUID generatedUUIDForNode() { - return manager.getGeneratedUUIDForNode(getNodeIdentifier()); - } - }); - } - - private void statPortCommit(final List portStats, - final InstanceIdentifier nodeIdent, final ReadWriteTransaction tx) { - - /* check exist FlowCapableNode and write statistics probable with parent */ - Optional fNode = Optional.absent(); - try { - fNode = tx.read(LogicalDatastoreType.OPERATIONAL, nodeIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read Operational/DS for Node fail! {}", nodeIdent, e); - return; - } - if ( ! fNode.isPresent()) { - LOG.trace("Read Operational/DS for Node fail! Node {} doesn't exist.", nodeIdent); - return; - } - for (final NodeConnectorStatisticsAndPortNumberMap nConnectPort : portStats) { - final FlowCapableNodeConnectorStatistics stats = new FlowCapableNodeConnectorStatisticsBuilder(nConnectPort).build(); - final NodeConnectorKey key = new NodeConnectorKey(nConnectPort.getNodeConnectorId()); - final InstanceIdentifier nodeConnectorIdent = nodeIdent.child(NodeConnector.class, key); - final InstanceIdentifier nodeConnStatIdent = nodeConnectorIdent - .augmentation(FlowCapableNodeConnectorStatisticsData.class); - final InstanceIdentifier flowCapNodeConnStatIdent = - nodeConnStatIdent.child(FlowCapableNodeConnectorStatistics.class); - Optional fNodeConector; - try { - fNodeConector = tx.read(LogicalDatastoreType.OPERATIONAL, nodeConnectorIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read NodeConnector {} in Operational/DS fail!", nodeConnectorIdent, e); - fNodeConector = Optional.absent(); - } - if (fNodeConector.isPresent()) { - tx.merge(LogicalDatastoreType.OPERATIONAL, nodeConnectorIdent, new NodeConnectorBuilder().setId(key.getId()).build()); - tx.merge(LogicalDatastoreType.OPERATIONAL, nodeConnStatIdent, new FlowCapableNodeConnectorStatisticsDataBuilder().build()); - tx.put(LogicalDatastoreType.OPERATIONAL, flowCapNodeConnStatIdent, stats); - } - } - } -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatNotifyCommitTable.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatNotifyCommitTable.java deleted file mode 100644 index 0bfeaaa4b0..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatNotifyCommitTable.java +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import java.util.ArrayList; -import java.util.List; - -import java.util.UUID; -import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatRpcMsgManager.TransactionCacheContainer; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager.StatDataStoreOperation; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager.StatDataStoreOperation.StatsManagerOperationType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsData; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsDataBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsUpdate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.OpendaylightFlowTableStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.and.statistics.map.FlowTableAndStatisticsMap; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.statistics.FlowTableStatistics; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.statistics.FlowTableStatisticsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionAware; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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; - -import com.google.common.base.Optional; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager.impl - * - * StatNotifyCommitTable - * Class is a NotifyListener for TableStatistics - * All expected (registered) tableStatistics will be builded and - * commit to Operational/DataStore - * - * @author Vaclav Demcak - * - */ -public class StatNotifyCommitTable extends StatAbstractNotifyCommit - implements OpendaylightFlowTableStatisticsListener { - - private static final Logger LOG = LoggerFactory.getLogger(StatNotifyCommitTable.class); - - public StatNotifyCommitTable(final StatisticsManager manager, - final NotificationProviderService nps, - final StatNodeRegistration nrm) { - super(manager, nps, nrm); - } - - @Override - protected OpendaylightFlowTableStatisticsListener getStatNotificationListener() { - return this; - } - - @Override - public void onFlowTableStatisticsUpdate(final FlowTableStatisticsUpdate notification) { - final TransactionId transId = notification.getTransactionId(); - final NodeId nodeId = notification.getId(); - if ( ! isExpectedStatistics(transId, nodeId)) { - LOG.debug("STAT-MANAGER - FlowTableStatisticsUpdate: unregistred notification detect TransactionId {}", transId); - return; - } - manager.getRpcMsgManager().addNotification(notification, nodeId); - if (notification.isMoreReplies()) { - return; - } - /* Don't block RPC Notification thread */ - manager.enqueue(new StatDataStoreOperation(StatsManagerOperationType.DATA_COMMIT_OPER_DS,nodeId) { - @Override - public void applyOperation(final ReadWriteTransaction trans) { - final List tableStats = new ArrayList(10); - final Optional> txContainer = getTransactionCacheContainer(transId, nodeId); - final InstanceIdentifier nodeIdent = InstanceIdentifier.create(Nodes.class) - .child(Node.class, new NodeKey(nodeId)); - if (( ! txContainer.isPresent()) || txContainer.get().getNodeId() == null) { - return; - } - - if(!nodeRegistrationManager.isFlowCapableNodeOwner(nodeId)) { return; } - - final List cachedNotifs = txContainer.get().getNotifications(); - for (final TransactionAware notif : cachedNotifs) { - if (notif instanceof FlowTableStatisticsUpdate) { - final List statNotif = - ((FlowTableStatisticsUpdate) notif).getFlowTableAndStatisticsMap(); - if (statNotif != null) { - tableStats.addAll(statNotif); - } - } - } - /* write stat to trans */ - statTableCommit(tableStats, nodeIdent, trans); - /* Notification for continue collecting statistics - Tables statistics are still same size - * and they are small - don't need to wait to whole apply operation */ - notifyToCollectNextStatistics(nodeIdent, transId); - } - - @Override - public UUID generatedUUIDForNode() { - return manager.getGeneratedUUIDForNode(getNodeIdentifier()); - } - }); - } - - private void statTableCommit(final List tableStats, final InstanceIdentifier nodeIdent, - final ReadWriteTransaction trans) { - final InstanceIdentifier fNodeIdent = nodeIdent.augmentation(FlowCapableNode.class); - /* check flow Capable Node and write statistics */ - Optional fNode = Optional.absent(); - try { - fNode = trans.read(LogicalDatastoreType.OPERATIONAL, fNodeIdent).checkedGet(); - } - catch (final ReadFailedException e) { - LOG.debug("Read Operational/DS for FlowCapableNode fail! {}", fNodeIdent, e); - return; - } - if ( ! fNode.isPresent()) { - LOG.trace("Read Operational/DS for FlowCapableNode fail! Node {} doesn't exist.", fNodeIdent); - return; - } - for (final FlowTableAndStatisticsMap tableStat : tableStats) { - final InstanceIdentifier
tableIdent = fNodeIdent - .child(Table.class, new TableKey(tableStat.getTableId().getValue())); - final Table table = new TableBuilder().setId(tableStat.getTableId().getValue()).build(); - trans.merge(LogicalDatastoreType.OPERATIONAL, tableIdent, table); - final InstanceIdentifier tableStatIdent = tableIdent - .augmentation(FlowTableStatisticsData.class); - trans.merge(LogicalDatastoreType.OPERATIONAL, tableStatIdent, new FlowTableStatisticsDataBuilder().build()); - - final FlowTableStatistics stats = new FlowTableStatisticsBuilder(tableStat).build(); - final InstanceIdentifier tStatIdent = tableStatIdent.child(FlowTableStatistics.class); - trans.put(LogicalDatastoreType.OPERATIONAL, tStatIdent, stats); - } - } -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatPermCollectorImpl.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatPermCollectorImpl.java deleted file mode 100644 index 0bb4e0291e..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatPermCollectorImpl.java +++ /dev/null @@ -1,427 +0,0 @@ -/* - * 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.applications.statistics.manager.impl; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; - -import com.google.common.base.Optional; -import org.opendaylight.controller.md.sal.common.api.clustering.Entity; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatPermCollector; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Preconditions; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager.impl - * - * StatPermCollectorImpl - * Thread base statistic collector. Class holds internal map for all registered - * (means connected) nodes with List of Switch capabilities; - * Statistics collecting process get cross whole Network Device by device - * and statistic by statistic (follow Switch capabilities to prevent unnecessary - * ask) Next statistic start collecting by notification or by timeout. - * - * @author @author avishnoi@in.ibm.com Vaclav Demcak - * - */ -public class StatPermCollectorImpl implements StatPermCollector { - - private static final Logger LOG = LoggerFactory.getLogger(StatPermCollectorImpl.class); - - private static final long STAT_COLLECT_TIME_OUT = 3000L; - - /** - sleep 5 second before collecting all statistics cycles is important - for loading all Nodes to Operational/DS - */ - private static final long WAIT_BEFORE_COLLECTING_STATS = 5000; - private static final TransactionId FAKE_TX_ID = new TransactionId(new BigInteger("FFFFFFFFFFFFFFFF", 16)); - - private final ExecutorService statNetCollectorServ; - private final StatisticsManager manager; - - private final int maxNodeForCollector; - private final long minReqNetInterval; - private final String name; - - private final Object statCollectorLock = new Object(); - private final Object statNodeHolderLock = new Object(); - private final Object transNotifyLock = new Object(); - - private Map, StatNodeInfoHolder> statNodeHolder = - Collections., StatNodeInfoHolder> emptyMap(); - - private volatile boolean wakeMe = false; - private volatile boolean finishing = false; - private TransactionId actualTransactionId; - - public StatPermCollectorImpl(final StatisticsManager manager, final long minReqNetInterv, final int nr, - final int maxNodeForCollectors) { - this.manager = Preconditions.checkNotNull(manager, "StatisticsManager can not be null!"); - name = "odl-stat-collector-" + nr; - minReqNetInterval = minReqNetInterv; - final ThreadFactory threadFact = new ThreadFactoryBuilder() - .setNameFormat(name + "-thread-%d").build(); - statNetCollectorServ = Executors.newSingleThreadExecutor(threadFact); - maxNodeForCollector = maxNodeForCollectors; - LOG.trace("StatCollector {} start successful!", name); - } - - /** - * finish collecting statistics - */ - @Override - public void close() { - statNodeHolder = Collections., StatNodeInfoHolder> emptyMap(); - finishing = true; - collectNextStatistics(actualTransactionId); - statNetCollectorServ.shutdown(); - } - - @Override - public boolean hasActiveNodes() { - return ( ! statNodeHolder.isEmpty()); - } - - @Override - public boolean isProvidedFlowNodeActive( - final InstanceIdentifier flowNode) { - return statNodeHolder.containsKey(flowNode); - } - - @Override - public boolean connectedNodeRegistration(final InstanceIdentifier ident, - final List statTypes, final Short nrOfSwitchTables) { - if (isNodeIdentValidForUse(ident) && ! statNodeHolder.containsKey(ident)) { - synchronized (statNodeHolderLock) { - final boolean startStatCollecting = statNodeHolder.size() == 0; - if ( ! statNodeHolder.containsKey(ident)) { - if (statNodeHolder.size() >= maxNodeForCollector) { - return false; - } - final Map, StatNodeInfoHolder> statNode = - new HashMap<>(statNodeHolder); - final NodeRef nodeRef = new NodeRef(ident); - final StatNodeInfoHolder nodeInfoHolder = new StatNodeInfoHolder(nodeRef, - statTypes, nrOfSwitchTables); - statNode.put(ident, nodeInfoHolder); - statNodeHolder = Collections.unmodifiableMap(statNode); - } - if (startStatCollecting) { - finishing = false; - statNetCollectorServ.execute(this); - } - } - } - return true; - } - - @Override - public boolean disconnectedNodeUnregistration(final InstanceIdentifier ident) { - if (isNodeIdentValidForUse(ident) && statNodeHolder.containsKey(ident)) { - synchronized (statNodeHolderLock) { - if (statNodeHolder.containsKey(ident)) { - final Map, StatNodeInfoHolder> statNode = - new HashMap<>(statNodeHolder); - statNode.remove(ident); - statNodeHolder = Collections.unmodifiableMap(statNode); - } - if (statNodeHolder.isEmpty()) { - finishing = true; - collectNextStatistics(actualTransactionId); - statNetCollectorServ.shutdown(); - } - return true; - } - } - return false; - } - - @Override - public boolean registerAdditionalNodeFeature(final InstanceIdentifier ident, - final StatCapabTypes statCapab) { - if (isNodeIdentValidForUse(ident)) { - if ( ! statNodeHolder.containsKey(ident)) { - return false; - } - final StatNodeInfoHolder statNode = statNodeHolder.get(ident); - if ( ! statNode.getStatMarkers().contains(statCapab)) { - synchronized (statNodeHolderLock) { - if ( ! statNode.getStatMarkers().contains(statCapab)) { - final List statCapabForEdit = new ArrayList<>(statNode.getStatMarkers()); - statCapabForEdit.add(statCapab); - final StatNodeInfoHolder nodeInfoHolder = new StatNodeInfoHolder(statNode.getNodeRef(), - Collections.unmodifiableList(statCapabForEdit), statNode.getMaxTables()); - - final Map, StatNodeInfoHolder> statNodes = - new HashMap<>(statNodeHolder); - statNodes.put(ident, nodeInfoHolder); - statNodeHolder = Collections.unmodifiableMap(statNodes); - } - } - } - } - return true; - } - - @Override - public boolean unregisterNodeStats(final InstanceIdentifier ident, - final StatCapabTypes statCapab) { - if (isNodeIdentValidForUse(ident)) { - if ( ! statNodeHolder.containsKey(ident)) { - return false; - } - final StatNodeInfoHolder statNode = statNodeHolder.get(ident); - if ( statNode.getStatMarkers().contains(statCapab)) { - synchronized (statNodeHolderLock) { - if ( statNode.getStatMarkers().contains(statCapab)) { - final List statCapabForEdit = new ArrayList<>(statNode.getStatMarkers()); - statCapabForEdit.remove(statCapab); - final StatNodeInfoHolder nodeInfoHolder = new StatNodeInfoHolder(statNode.getNodeRef(), - Collections.unmodifiableList(statCapabForEdit), statNode.getMaxTables()); - - final Map, StatNodeInfoHolder> statNodes = - new HashMap<>(statNodeHolder); - statNodes.put(ident, nodeInfoHolder); - statNodeHolder = Collections.unmodifiableMap(statNodes); - } - } - } - } - return true; - } - - @Override - public void collectNextStatistics(final TransactionId xid) { - if (checkTransactionId(xid) && wakeMe) { - synchronized (statCollectorLock) { - if (wakeMe) { - LOG.trace("STAT-COLLECTOR is notified to conntinue"); - statCollectorLock.notify(); - } - } - } - } - - @Override - public void run() { - try { - Thread.sleep(WAIT_BEFORE_COLLECTING_STATS); - } - catch (final InterruptedException e1) { - // NOOP - } - LOG.debug("StatCollector {} Start collecting!", name); - /* Neverending cyle - wait for finishing */ - while ( ! finishing) { - boolean collecting = false; - final long startTime = System.currentTimeMillis(); - - if ( ! statNodeHolder.isEmpty()) { - collecting = true; - collectStatCrossNetwork(); - collecting = false; - } - - if ( ! collecting) { - final long statFinalTime = System.currentTimeMillis() - startTime; - LOG.debug("STAT-MANAGER {}: last all NET statistics collection cost {} ms", name, statFinalTime); - if (statFinalTime < minReqNetInterval) { - LOG.trace("statCollector is about to make a collecting sleep"); - synchronized (statCollectorLock) { - wakeMe = true; - try { - final long waitTime = minReqNetInterval - statFinalTime; - statCollectorLock.wait(waitTime); - LOG.trace("STAT-MANAGER : statCollector {} is waking up from a collecting sleep for {} ms", name, waitTime); - } catch (final InterruptedException e) { - LOG.warn("statCollector has been interrupted during collecting sleep", e); - } finally { - wakeMe = false; - } - } - } - } - } - } - - private void waitingForNotification() { - synchronized (statCollectorLock) { - wakeMe = true; - try { - statCollectorLock.wait(STAT_COLLECT_TIME_OUT); - LOG.trace("statCollector is waking up from a wait stat Response sleep"); - } catch (final InterruptedException e) { - LOG.warn("statCollector has been interrupted waiting stat Response sleep", e); - } finally { - setActualTransactionId(null); - wakeMe = false; - } - } - } - - - private void collectStatCrossNetwork() { - for (final Entry, StatNodeInfoHolder> nodeEntity : statNodeHolder.entrySet()) { - final NodeKey nodeKey = nodeEntity.getKey().firstKeyOf(Node.class); - if (!this.isThisInstanceNodeOwner(nodeKey.getId())) { - continue; - } - LOG.trace("collectStatCrossNetwork: Controller is owner of the " + - "node {}, so collecting the statistics.",nodeKey); - - final List listNeededStat = nodeEntity.getValue().getStatMarkers(); - final NodeRef actualNodeRef = nodeEntity.getValue().getNodeRef(); - final Short maxTables = nodeEntity.getValue().getMaxTables(); - for (final StatCapabTypes statMarker : listNeededStat) { - if ( ! isProvidedFlowNodeActive(nodeEntity.getKey())) { - break; - } - try { - switch (statMarker) { - case PORT_STATS: - LOG.trace("STAT-MANAGER-collecting PORT-STATS for NodeRef {}", actualNodeRef); - setActualTransactionId(manager.getRpcMsgManager().getAllPortsStat(actualNodeRef).get()); - waitingForNotification(); - break; - case QUEUE_STATS: - LOG.trace("STAT-MANAGER-collecting QUEUE-STATS for NodeRef {}", actualNodeRef); - setActualTransactionId(manager.getRpcMsgManager().getAllQueueStat(actualNodeRef).get()); - waitingForNotification(); - break; - case TABLE_STATS: - LOG.trace("STAT-MANAGER-collecting TABLE-STATS for NodeRef {}", actualNodeRef); - setActualTransactionId(manager.getRpcMsgManager().getAllTablesStat(actualNodeRef).get()); - waitingForNotification(); - break; - case GROUP_STATS: - LOG.trace("STAT-MANAGER-collecting GROUP-STATS for NodeRef {}", actualNodeRef); - setActualTransactionId(manager.getRpcMsgManager().getAllGroupsConfStats(actualNodeRef).get()); - waitingForNotification(); - setActualTransactionId(manager.getRpcMsgManager().getAllGroupsStat(actualNodeRef).get()); - waitingForNotification(); - break; - case METER_STATS: - LOG.trace("STAT-MANAGER-collecting METER-STATS for NodeRef {}", actualNodeRef); - setActualTransactionId(manager.getRpcMsgManager().getAllMeterConfigStat(actualNodeRef).get()); - waitingForNotification(); - setActualTransactionId(manager.getRpcMsgManager().getAllMetersStat(actualNodeRef).get()); - waitingForNotification(); - break; - case FLOW_STATS: - LOG.trace("STAT-MANAGER-collecting FLOW-STATS-ALL_FLOWS for NodeRef {}", actualNodeRef); - setActualTransactionId(manager.getRpcMsgManager().getAllFlowsStat(actualNodeRef).get()); - waitingForNotification(); - /*LOG.trace("STAT-MANAGER-collecting FLOW-AGGREGATE-STATS for NodeRef {}", actualNodeRef); - for (short i = 0; i < maxTables; i++) { - final TableId tableId = new TableId(i); - manager.getRpcMsgManager().getAggregateFlowStat(actualNodeRef, tableId); - }*/ - break; - case METER_FEATURE_STATS: - LOG.trace("STAT-MANAGER-collecting METER-FEATURE-STATS for NodeRef {}", actualNodeRef); - manager.getRpcMsgManager().getMeterFeaturesStat(actualNodeRef); - break; - case GROUP_FEATURE_STATS: - LOG.trace("STAT-MANAGER-collecting GROUP-FEATURE-STATS for NodeRef {}", actualNodeRef); - manager.getRpcMsgManager().getGroupFeaturesStat(actualNodeRef); - break; - default: - /* Exception for programmers in implementation cycle */ - throw new IllegalStateException("Not implemented ASK for " + statMarker); - } - } catch (InterruptedException | ExecutionException ex) { - LOG.warn("Unexpected RPC exception by call RPC Future!", ex); - continue; - } - } - } - } - - private boolean isThisInstanceNodeOwner(NodeId nodeId) { - return manager.getNodeRegistrator().isFlowCapableNodeOwner(nodeId); - } - - private class StatNodeInfoHolder { - private final NodeRef nodeRef; - private final List statMarkers; - private final Short maxTables; - - public StatNodeInfoHolder(final NodeRef nodeRef, - final List statMarkers, final Short maxTables) { - this.nodeRef = nodeRef; - this.maxTables = maxTables; - this.statMarkers = statMarkers; - } - - public final NodeRef getNodeRef() { - return nodeRef; - } - - public final List getStatMarkers() { - return statMarkers; - } - - public final Short getMaxTables() { - return maxTables; - } - } - - private boolean isNodeIdentValidForUse(final InstanceIdentifier ident) { - if (ident == null) { - LOG.warn("FlowCapableNode InstanceIdentifier {} can not be null!"); - return false; - } - if (ident.isWildcarded()) { - LOG.warn("FlowCapableNode InstanceIdentifier {} can not be wildcarded!", ident); - return false; - } - return true; - } - - private boolean checkTransactionId(final TransactionId xid) { - synchronized (transNotifyLock) { - return actualTransactionId != null - && (actualTransactionId.equals(xid) || actualTransactionId.equals(FAKE_TX_ID)); - } - } - - private void setActualTransactionId(final TransactionId transactionId) { - synchronized (transNotifyLock) { - actualTransactionId = transactionId; - } - } - - public static TransactionId getFakeTxId() { - return FAKE_TX_ID; - } -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatRPCFailedException.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatRPCFailedException.java deleted file mode 100644 index a16ffae5d4..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatRPCFailedException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import org.opendaylight.yangtools.yang.common.RpcError; - -import java.util.Collection; - -public final class StatRPCFailedException extends RuntimeException { - private static final long serialVersionUID = 1L; - private final Collection errors; - - public StatRPCFailedException(final String message, final Collection errors) { - super(message); - this.errors = errors; - } - - @Override - public String toString() { - return "RPCFailedException [errors=" + errors + ", message=" + getMessage() + ']'; - } -} diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatRpcMsgManagerImpl.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatRpcMsgManagerImpl.java deleted file mode 100644 index 0515ca1d1d..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatRpcMsgManagerImpl.java +++ /dev/null @@ -1,462 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException; -import org.opendaylight.controller.sal.binding.api.RpcConsumerRegistry; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatRpcMsgManager; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.OpendaylightFlowStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.GetFlowTablesStatisticsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.OpendaylightFlowTableStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionAware; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.OpendaylightGroupStatisticsService; -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.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterConfigStatisticsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.OpendaylightMeterStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.OpendaylightPortStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.OpendaylightQueueStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Joiner; -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.JdkFutureAdapters; -import com.google.common.util.concurrent.SettableFuture; - - -/** - * statistics-manager - * org.opendaylight.openflowplugin.applications.statistics.manager.impl - * - * StatRpcMsgManagerImpl - * Class register and provide all RPC Statistics Device Services and implement pre-defined - * wrapped methods for prepare easy access to RPC Statistics Device Services like getAllStatisticsFor... - * - * In next Class implement process for joining multipart messages. - * Class internally use two WeakHashMap and GuavaCache for holding values for joining multipart msg. - * One Weak map is used for holding all Multipart Messages and second is used for possible input - * Config/DS light-weight DataObject (DataObject contains only necessary identification fields as - * TableId, GroupId, MeterId or for flow Match, Priority, FlowCookie, TableId and FlowId ... - * - * @author avishnoi@in.ibm.com Vaclav Demcak - * - */ -public class StatRpcMsgManagerImpl implements StatRpcMsgManager { - - - private static final Logger LOG = LoggerFactory.getLogger(StatRpcMsgManagerImpl.class); - - private final Cache> txCache; - - /** - * Cache for futures to be returned by - * {@link #isExpectedStatistics(TransactionId, NodeId)}. - */ - private final Cache> txFutureCache; - - /** - * The number of seconds to wait for transaction container to be put into - * {@link #txCache}. - */ - private static final long TXCACHE_WAIT_TIMEOUT = 10L; - - private static final int MAX_CACHE_SIZE = 10000; - - private static final String MSG_TRANS_ID_NOT_NULL = "TransactionId can not be null!"; - private static final String MSG_NODE_ID_NOT_NULL = "NodeId can not be null!"; - private static final String MSG_NODE_REF_NOT_NULL = "NodeRef can not be null!"; - /** - * Number of possible statistic which are waiting for notification - * - check it in StatPermCollectorImpl method collectStatCrossNetwork() - */ - private static final long POSSIBLE_STAT_WAIT_FOR_NOTIFICATION = 7; - - private final OpendaylightGroupStatisticsService groupStatsService; - private final OpendaylightMeterStatisticsService meterStatsService; - private final OpendaylightFlowStatisticsService flowStatsService; - private final OpendaylightPortStatisticsService portStatsService; - private final OpendaylightFlowTableStatisticsService flowTableStatsService; - private final OpendaylightQueueStatisticsService queueStatsService; - - public StatRpcMsgManagerImpl (final StatisticsManager manager, - final RpcConsumerRegistry rpcRegistry, final long maxNodeForCollector) { - Preconditions.checkArgument(manager != null, "StatisticManager can not be null!"); - Preconditions.checkArgument(rpcRegistry != null, "RpcConsumerRegistry can not be null !"); - groupStatsService = Preconditions.checkNotNull( - rpcRegistry.getRpcService(OpendaylightGroupStatisticsService.class), - "OpendaylightGroupStatisticsService can not be null!"); - meterStatsService = Preconditions.checkNotNull( - rpcRegistry.getRpcService(OpendaylightMeterStatisticsService.class), - "OpendaylightMeterStatisticsService can not be null!"); - flowStatsService = Preconditions.checkNotNull( - rpcRegistry.getRpcService(OpendaylightFlowStatisticsService.class), - "OpendaylightFlowStatisticsService can not be null!"); - portStatsService = Preconditions.checkNotNull( - rpcRegistry.getRpcService(OpendaylightPortStatisticsService.class), - "OpendaylightPortStatisticsService can not be null!"); - flowTableStatsService = Preconditions.checkNotNull( - rpcRegistry.getRpcService(OpendaylightFlowTableStatisticsService.class), - "OpendaylightFlowTableStatisticsService can not be null!"); - queueStatsService = Preconditions.checkNotNull( - rpcRegistry.getRpcService(OpendaylightQueueStatisticsService.class), - "OpendaylightQueueStatisticsService can not be null!"); - - txCache = CacheBuilder.newBuilder().expireAfterWrite((maxNodeForCollector * POSSIBLE_STAT_WAIT_FOR_NOTIFICATION), TimeUnit.SECONDS) - .maximumSize(MAX_CACHE_SIZE).build(); - txFutureCache = CacheBuilder.newBuilder(). - expireAfterWrite(TXCACHE_WAIT_TIMEOUT, TimeUnit.SECONDS). - maximumSize(MAX_CACHE_SIZE).build(); - } - - @Override - public void registrationRpcFutureCallBack( - final Future> future, final D inputObj, final NodeRef nodeRef, - final SettableFuture resultTransId) { - - class FutureCallbackImpl implements FutureCallback> { - @Override - public void onSuccess(final RpcResult result) { - final TransactionId id = result.getResult().getTransactionId(); - final NodeKey nodeKey = nodeRef.getValue().firstKeyOf(Node.class, NodeKey.class); - if (id == null) { - String[] multipartRequestName = result.getResult().getClass().getSimpleName().split("(?=\\p{Upper})"); - LOG.warn("Node [{}] does not support statistics request type : {}", - nodeKey.getId(),Joiner.on(" ").join(Arrays.copyOfRange(multipartRequestName, 2, multipartRequestName.length-2))); - if (resultTransId != null) { - resultTransId.setException( - new UnsupportedOperationException()); - } - } else { - if (resultTransId != null) { - resultTransId.set(id); - } - final String cacheKey = buildCacheKey(id, nodeKey.getId()); - final TransactionCacheContainer container = - new TransactionCacheContainerImpl<>(id, inputObj, nodeKey.getId()); - putTransaction(cacheKey, container); - } - } - - @Override - public void onFailure(final Throwable t) { - LOG.warn("Response Registration for Statistics RPC call fail!", t); - if (resultTransId != null) { - if (t instanceof DOMRpcImplementationNotAvailableException) { - //If encountered with RPC not availabe exception, retry till - // stats manager remove the node from the stats collector pool - resultTransId.set(StatPermCollectorImpl.getFakeTxId()); - } else { - resultTransId.setException(t); - } - } - } - } - - Futures.addCallback(JdkFutureAdapters.listenInPoolThread(future),new FutureCallbackImpl()); - } - - private String buildCacheKey(final TransactionId id, final NodeId nodeId) { - return String.valueOf(id.getValue()) + "-" + nodeId.getValue(); - } - - /** - * Put the given statistics transaction container into the cache. - * - * @param key Key that specifies the given transaction container. - * @param container Transaction container. - */ - private synchronized void putTransaction( - String key, TransactionCacheContainer container) { - txCache.put(key, container); - - SettableFuture future = txFutureCache.asMap().remove(key); - if (future != null) { - // Wake up a thread waiting for this transaction container. - future.set(true); - } - } - - /** - * Check to see if the specified transaction container is cached in - * {@link #txCache}. - * - * @param key Key that specifies the transaction container. - * @return A future that will contain the result. - */ - private synchronized Future isExpectedStatistics(String key) { - Future future; - TransactionCacheContainer container = txCache.getIfPresent(key); - if (container == null) { - // Wait for the transaction container to be put into the cache. - SettableFuture f = SettableFuture.create(); - SettableFuture current = - txFutureCache.asMap().putIfAbsent(key, f); - future = (current == null) ? f : current; - } else { - future = Futures.immediateFuture(Boolean.TRUE); - } - - return future; - } - - @Override - public Future>> getTransactionCacheContainer( - final TransactionId id, final NodeId nodeId) { - Preconditions.checkArgument(id != null, MSG_TRANS_ID_NOT_NULL); - Preconditions.checkArgument(nodeId != null, MSG_NODE_ID_NOT_NULL); - - String key = buildCacheKey(id, nodeId); - Optional> resultContainer = - Optional.> fromNullable( - txCache.asMap().remove(key)); - if (!resultContainer.isPresent()) { - LOG.warn("Transaction cache not found: {}", key); - } - - return Futures.immediateFuture(resultContainer); - } - - @Override - public Future isExpectedStatistics(final TransactionId id, final NodeId nodeId) { - Preconditions.checkArgument(id != null, MSG_TRANS_ID_NOT_NULL); - Preconditions.checkArgument(nodeId != null, MSG_NODE_ID_NOT_NULL); - - String key = buildCacheKey(id, nodeId); - return isExpectedStatistics(key); - } - - @Override - public void addNotification(final TransactionAware notification, final NodeId nodeId) { - Preconditions.checkArgument(notification != null, "TransactionAware can not be null!"); - Preconditions.checkArgument(nodeId != null, MSG_NODE_ID_NOT_NULL); - - TransactionId txId = notification.getTransactionId(); - String key = buildCacheKey(txId, nodeId); - TransactionCacheContainer container = - txCache.getIfPresent(key); - if (container != null) { - container.addNotif(notification); - } else { - LOG.warn("Unable to add notification: {}, {}", key, - notification.getImplementedInterface()); - } - } - - @Override - public Future getAllGroupsStat(final NodeRef nodeRef) { - Preconditions.checkArgument(nodeRef != null, MSG_NODE_REF_NOT_NULL); - SettableFuture result = SettableFuture.create(); - GetAllGroupStatisticsInputBuilder builder = - new GetAllGroupStatisticsInputBuilder(); - builder.setNode(nodeRef); - registrationRpcFutureCallBack( - groupStatsService.getAllGroupStatistics(builder.build()), null, - nodeRef, result); - return result; - } - - @Override - public Future getAllMetersStat(final NodeRef nodeRef) { - Preconditions.checkArgument(nodeRef != null, MSG_NODE_REF_NOT_NULL); - SettableFuture result = SettableFuture.create(); - GetAllMeterStatisticsInputBuilder builder = - new GetAllMeterStatisticsInputBuilder(); - builder.setNode(nodeRef); - registrationRpcFutureCallBack( - meterStatsService.getAllMeterStatistics(builder.build()), null, - nodeRef, result); - return result; - } - - @Override - public Future getAllFlowsStat(final NodeRef nodeRef) { - Preconditions.checkArgument(nodeRef != null, MSG_NODE_REF_NOT_NULL); - SettableFuture result = SettableFuture.create(); - GetAllFlowsStatisticsFromAllFlowTablesInputBuilder builder = - new GetAllFlowsStatisticsFromAllFlowTablesInputBuilder(); - builder.setNode(nodeRef); - registrationRpcFutureCallBack( - flowStatsService.getAllFlowsStatisticsFromAllFlowTables(builder.build()), - null, nodeRef, result); - return result; - } - - @Override - public void getAggregateFlowStat(final NodeRef nodeRef, final TableId tableId) { - Preconditions.checkArgument(nodeRef != null, MSG_NODE_REF_NOT_NULL); - Preconditions.checkArgument(tableId != null, "TableId can not be null!"); - GetAggregateFlowStatisticsFromFlowTableForAllFlowsInputBuilder builder = - new GetAggregateFlowStatisticsFromFlowTableForAllFlowsInputBuilder(); - builder.setNode(nodeRef).setTableId(tableId); - - TableBuilder tbuilder = new TableBuilder(). - setId(tableId.getValue()). - setKey(new TableKey(tableId.getValue())); - registrationRpcFutureCallBack( - flowStatsService.getAggregateFlowStatisticsFromFlowTableForAllFlows(builder.build()), - tbuilder.build(), nodeRef, null); - } - - @Override - public Future getAllPortsStat(final NodeRef nodeRef) { - Preconditions.checkArgument(nodeRef != null, MSG_NODE_REF_NOT_NULL); - SettableFuture result = SettableFuture.create(); - GetAllNodeConnectorsStatisticsInputBuilder builder = - new GetAllNodeConnectorsStatisticsInputBuilder(); - builder.setNode(nodeRef); - Future> rpc = - portStatsService.getAllNodeConnectorsStatistics(builder.build()); - registrationRpcFutureCallBack(rpc, null, nodeRef, result); - return result; - } - - @Override - public Future getAllTablesStat(final NodeRef nodeRef) { - Preconditions.checkArgument(nodeRef != null, MSG_NODE_REF_NOT_NULL); - SettableFuture result = SettableFuture.create(); - GetFlowTablesStatisticsInputBuilder builder = - new GetFlowTablesStatisticsInputBuilder(); - builder.setNode(nodeRef); - registrationRpcFutureCallBack( - flowTableStatsService.getFlowTablesStatistics(builder.build()), - null, nodeRef, result); - return result; - } - - @Override - public Future getAllQueueStat(final NodeRef nodeRef) { - Preconditions.checkArgument(nodeRef != null, MSG_NODE_REF_NOT_NULL); - SettableFuture result = SettableFuture.create(); - GetAllQueuesStatisticsFromAllPortsInputBuilder builder = - new GetAllQueuesStatisticsFromAllPortsInputBuilder(); - builder.setNode(nodeRef); - registrationRpcFutureCallBack( - queueStatsService.getAllQueuesStatisticsFromAllPorts(builder.build()), - null, nodeRef, result); - return result; - } - - @Override - public Future getAllMeterConfigStat(final NodeRef nodeRef) { - Preconditions.checkArgument(nodeRef != null, MSG_NODE_REF_NOT_NULL); - SettableFuture result = SettableFuture.create(); - GetAllMeterConfigStatisticsInputBuilder builder = - new GetAllMeterConfigStatisticsInputBuilder(); - builder.setNode(nodeRef); - registrationRpcFutureCallBack( - meterStatsService.getAllMeterConfigStatistics(builder.build()), - null, nodeRef, result); - return result; - } - - @Override - public void getGroupFeaturesStat(final NodeRef nodeRef) { - Preconditions.checkArgument(nodeRef != null, MSG_NODE_REF_NOT_NULL); - GetGroupFeaturesInputBuilder input = new GetGroupFeaturesInputBuilder(). - setNode(nodeRef); - registrationRpcFutureCallBack( - groupStatsService.getGroupFeatures(input.build()), null, nodeRef, - null); - } - - @Override - public void getMeterFeaturesStat(final NodeRef nodeRef) { - Preconditions.checkArgument(nodeRef != null, MSG_NODE_REF_NOT_NULL); - GetMeterFeaturesInputBuilder input = new GetMeterFeaturesInputBuilder(). - setNode(nodeRef); - registrationRpcFutureCallBack( - meterStatsService.getMeterFeatures(input.build()), null, nodeRef, - null); - } - - @Override - public Future getAllGroupsConfStats(final NodeRef nodeRef) { - Preconditions.checkArgument(nodeRef != null, MSG_NODE_REF_NOT_NULL); - SettableFuture result = SettableFuture.create(); - GetGroupDescriptionInputBuilder builder = - new GetGroupDescriptionInputBuilder(); - builder.setNode(nodeRef); - registrationRpcFutureCallBack( - groupStatsService.getGroupDescription(builder.build()), null, - nodeRef, result); - return result; - } - - public class TransactionCacheContainerImpl implements TransactionCacheContainer { - - private final TransactionId id; - private final NodeId nId; - private final List notifications; - private final Optional confInput; - - public TransactionCacheContainerImpl (final TransactionId id, final D input, final NodeId nodeId) { - this.id = Preconditions.checkNotNull(id, MSG_TRANS_ID_NOT_NULL); - notifications = new CopyOnWriteArrayList(); - confInput = Optional.fromNullable(input); - nId = nodeId; - } - - @Override - public void addNotif(final T notif) { - notifications.add(notif); - } - - @Override - public TransactionId getId() { - return id; - } - - @Override - public NodeId getNodeId() { - return nId; - } - - @Override - public List getNotifications() { - return notifications; - } - - @Override - public Optional getConfInput() { - return confInput; - } - } -} diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatisticsManagerConfig.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatisticsManagerConfig.java deleted file mode 100644 index ab7cc0eda2..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatisticsManagerConfig.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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.applications.statistics.manager.impl; - -public final class StatisticsManagerConfig { - private final int maxNodesForCollector; - private final int minRequestNetMonitorInterval; - - private StatisticsManagerConfig(StatisticsManagerConfigBuilder builder) { - this.maxNodesForCollector = builder.getMaxNodesForCollector(); - this.minRequestNetMonitorInterval = builder.getMinRequestNetMonitorInterval(); - } - - public int getMaxNodesForCollector() { - return maxNodesForCollector; - } - - public int getMinRequestNetMonitorInterval() { - return minRequestNetMonitorInterval; - } - - public static StatisticsManagerConfigBuilder builder() { - return new StatisticsManagerConfigBuilder(); - } - - public static class StatisticsManagerConfigBuilder { - private int maxNodesForCollector; - private int minRequestNetMonitorInterval; - - public int getMaxNodesForCollector() { - return maxNodesForCollector; - } - - public void setMaxNodesForCollector(int maxNodesForCollector) { - this.maxNodesForCollector = maxNodesForCollector; - } - - public int getMinRequestNetMonitorInterval() { - return minRequestNetMonitorInterval; - } - - public void setMinRequestNetMonitorInterval(int minRequestNetMonitorInterval) { - this.minRequestNetMonitorInterval = minRequestNetMonitorInterval; - } - - public StatisticsManagerConfig build() { - return new StatisticsManagerConfig(this); - } - } -} diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatisticsManagerFactoryImpl.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatisticsManagerFactoryImpl.java deleted file mode 100644 index 11fe70d859..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatisticsManagerFactoryImpl.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcConsumerRegistry; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManagerFactory; -import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.app.statistics.manager.config.rev160509.StatisticsManagerAppConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Implementation of StatisticsManagerFactory. - * - * @author Thomas Pantelis - */ -public class StatisticsManagerFactoryImpl implements StatisticsManagerFactory { - private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerFactoryImpl.class); - - @Override - public StatisticsManager newInstance(StatisticsManagerAppConfig statsManagerAppConfig, DataBroker dataBroker, - NotificationProviderService notifService, RpcConsumerRegistry rpcRegistry, - EntityOwnershipService entityOwnershipService) { - LOG.info("StatisticsManager module initialization."); - - StatisticsManagerConfig.StatisticsManagerConfigBuilder configBuilder = StatisticsManagerConfig.builder(); - configBuilder.setMaxNodesForCollector(statsManagerAppConfig.getMaxNodesForCollector()); - configBuilder.setMinRequestNetMonitorInterval(statsManagerAppConfig.getMinRequestNetMonitorInterval()); - - StatisticsManager statisticsManager = new StatisticsManagerImpl(dataBroker, configBuilder.build()); - statisticsManager.setOwnershipService(entityOwnershipService); - statisticsManager.start(notifService, rpcRegistry); - - LOG.info("StatisticsManager started successfully."); - - return statisticsManager; - } -} diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatisticsManagerImpl.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatisticsManagerImpl.java deleted file mode 100644 index 3bd0cc2a65..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatisticsManagerImpl.java +++ /dev/null @@ -1,425 +0,0 @@ -/** - * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import com.google.common.base.Preconditions; -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingDeque; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService; -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.ReadWriteTransaction; -import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction; -import org.opendaylight.controller.md.sal.common.api.data.TransactionChain; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcConsumerRegistry; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatListeningCommiter; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNotifyCommiter; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatPermCollector; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatPermCollector.StatCapabTypes; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatRpcMsgManager; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.OpendaylightFlowStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.OpendaylightFlowTableStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.Queue; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.OpendaylightGroupStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.OpendaylightMeterStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.OpendaylightPortStatisticsListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.OpendaylightQueueStatisticsListener; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** -* statistics-manager -* org.opendaylight.openflowplugin.applications.statistics.manager.impl -* -* StatisticsManagerImpl -* It represent a central point for whole module. Implementation -* {@link StatisticsManager} registers all Operation/DS {@link StatNotifyCommiter} and -* Config/DS {@link StatListeningCommiter}, as well as {@link StatPermCollector} -* for statistic collecting and {@link StatRpcMsgManager} as Device RPCs provider. -* In next, StatisticsManager provides all DS contact Transaction services. -* -* @author avishnoi@in.ibm.com Vaclav Demcak -* -*/ -public class StatisticsManagerImpl implements StatisticsManager, Runnable { - - private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImpl.class); - - private static final int QUEUE_DEPTH = 5000; - private static final int MAX_BATCH = 100; - - private final BlockingQueue dataStoreOperQueue = new LinkedBlockingDeque<>(QUEUE_DEPTH); - private final Map, Pair> nodeCollectorMap = new ConcurrentHashMap<>(); - private AtomicInteger numNodesBeingCollected = new AtomicInteger(0); - - - private final DataBroker dataBroker; - private final ExecutorService statDataStoreOperationServ; - private EntityOwnershipService ownershipService; - private StatRpcMsgManager rpcMsgManager; - private List statCollectors; - private final Object statCollectorLock = new Object(); - private BindingTransactionChain txChain; - private volatile boolean finishing = false; - - private StatNodeRegistration nodeRegistrator; - private StatListeningCommiter flowListeningCommiter; - private StatListeningCommiter meterListeningCommiter; - private StatListeningCommiter groupListeningCommiter; - private StatListeningCommiter queueNotifyCommiter; - private StatNotifyCommiter tableNotifCommiter; - private StatNotifyCommiter portNotifyCommiter; - - private final StatisticsManagerConfig statManagerConfig; - - public StatisticsManagerImpl (final DataBroker dataBroker, final StatisticsManagerConfig statManagerconfig) { - statManagerConfig = Preconditions.checkNotNull(statManagerconfig); - this.dataBroker = Preconditions.checkNotNull(dataBroker, "DataBroker can not be null!"); - ThreadFactory threadFact; - threadFact = new ThreadFactoryBuilder().setNameFormat("odl-stat-rpc-oper-thread-%d").build(); - threadFact = new ThreadFactoryBuilder().setNameFormat("odl-stat-ds-oper-thread-%d").build(); - statDataStoreOperationServ = Executors.newSingleThreadExecutor(threadFact); - txChain = dataBroker.createTransactionChain(this); - } - - @Override - public void start(final NotificationProviderService notifService, - final RpcConsumerRegistry rpcRegistry) { - Preconditions.checkArgument(rpcRegistry != null, "RpcConsumerRegistry can not be null !"); - rpcMsgManager = new StatRpcMsgManagerImpl(this, rpcRegistry, statManagerConfig.getMaxNodesForCollector()); - statCollectors = Collections.emptyList(); - nodeRegistrator = new StatNodeRegistrationImpl(this, dataBroker, notifService); - flowListeningCommiter = new StatListenCommitFlow(this, dataBroker, notifService, nodeRegistrator); - meterListeningCommiter = new StatListenCommitMeter(this, dataBroker, notifService, nodeRegistrator); - groupListeningCommiter = new StatListenCommitGroup(this, dataBroker, notifService, nodeRegistrator); - tableNotifCommiter = new StatNotifyCommitTable(this, notifService, nodeRegistrator); - portNotifyCommiter = new StatNotifyCommitPort(this, notifService, nodeRegistrator); - queueNotifyCommiter = new StatListenCommitQueue(this, dataBroker, notifService, nodeRegistrator); - - statDataStoreOperationServ.execute(this); - LOG.info("Statistics Manager started successfully!"); - } - - private T close(final T closeable) throws Exception { - if (closeable != null) { - closeable.close(); - } - return null; - } - - @Override - public void close() throws Exception { - LOG.info("StatisticsManager close called"); - finishing = true; - nodeRegistrator = close(nodeRegistrator); - flowListeningCommiter = close(flowListeningCommiter); - meterListeningCommiter = close(meterListeningCommiter); - groupListeningCommiter = close(groupListeningCommiter); - tableNotifCommiter = close(tableNotifCommiter); - portNotifyCommiter = close(portNotifyCommiter); - queueNotifyCommiter = close(queueNotifyCommiter); - if (statCollectors != null) { - for (StatPermCollector collector : statCollectors) { - collector = close(collector); - } - statCollectors = null; - } - rpcMsgManager = null; - statDataStoreOperationServ.shutdown(); - txChain = close(txChain); - } - - @Override - public void enqueue(final StatDataStoreOperation op) { - // we don't need to block anything - next statistics come soon - final boolean success = dataStoreOperQueue.offer(op); - if ( ! success) { - LOG.debug("Stat DS/Operational submitter Queue is full!"); - } - } - - @Override - public void run() { - /* Neverending cyle - wait for finishing */ - while ( ! finishing) { - StatDataStoreOperation op = null; - try { - op = dataStoreOperQueue.take(); - final ReadWriteTransaction tx = txChain.newReadWriteTransaction(); - LOG.trace("New operations available, starting transaction {}", tx.getIdentifier()); - - int ops = 0; - do { - Pair statPermCollectorUUIDPair = nodeCollectorMap.get(op.getNodeIdentifier()); - if (statPermCollectorUUIDPair != null && statPermCollectorUUIDPair.getRight().equals(op.getNodeUUID())) { - // dont apply operations for nodes which have been disconnected or if there uuids do not match - // this can happen if operations are queued and node is removed. - // if the uuids dont match, it means that the stat operation are stale and belong to the same node - // which got disconnected and connected again. - op.applyOperation(tx); - ops++; - } else { - LOG.debug("{} not found or UUID mismatch for statistics datastore operation", op.getNodeIdentifier()); - } - - if (ops < MAX_BATCH) { - op = dataStoreOperQueue.poll(); - } else { - op = null; - } - } while (op != null); - - LOG.trace("Processed {} operations, submitting transaction {}", ops, tx.getIdentifier()); - - tx.submit().checkedGet(); - } catch (final InterruptedException e) { - LOG.warn("Stat Manager DS Operation thread interrupted, while " + - "waiting for StatDataStore Operation task!", e); - finishing = true; - } catch (final Exception e) { - LOG.warn("Unhandled exception during processing statistics for {}. " + - "Restarting transaction chain.",op != null?op.getNodeId().getValue():"",e); - txChain.close(); - txChain = dataBroker.createTransactionChain(StatisticsManagerImpl.this); - cleanDataStoreOperQueue(); - } - } - // Drain all events, making sure any blocked threads are unblocked - cleanDataStoreOperQueue(); - } - - private synchronized void cleanDataStoreOperQueue() { - // Drain all events, making sure any blocked threads are unblocked - while (! dataStoreOperQueue.isEmpty()) { - dataStoreOperQueue.poll(); - } - } - - @Override - public void onTransactionChainFailed(final TransactionChain chain, final AsyncTransaction transaction, - final Throwable cause) { - LOG.warn("Failed to export Flow Capable Statistics, Transaction {} failed.",transaction.getIdentifier(),cause); - } - - @Override - public void onTransactionChainSuccessful(final TransactionChain chain) { - // NOOP - } - - @Override - public boolean isProvidedFlowNodeActive(final InstanceIdentifier nodeIdent) { - for (final StatPermCollector collector : statCollectors) { - if (collector.isProvidedFlowNodeActive(nodeIdent)) { - return true; - } - } - return false; - } - - @Override - public void collectNextStatistics(final InstanceIdentifier nodeIdent, final TransactionId xid) { - for (final StatPermCollector collector : statCollectors) { - if (collector.isProvidedFlowNodeActive(nodeIdent)) { - collector.collectNextStatistics(xid); - } - } - } - - @Override - public void connectedNodeRegistration(final InstanceIdentifier nodeIdent, - final List statTypes, final Short nrOfSwitchTables) { - - - Pair collectorUUIDPair = nodeCollectorMap.get(nodeIdent); - if (collectorUUIDPair == null) { - // no collector contains this node, - // check if one of the collectors can accommodate it - // if no then add a new collector - - synchronized(statCollectorLock) { - for (int i = statCollectors.size() - 1; i >= 0; i--) { - // start from back of the list as most likely previous ones might be full - final StatPermCollector aCollector = statCollectors.get(i); - if (aCollector.connectedNodeRegistration(nodeIdent, statTypes, nrOfSwitchTables)) { - // if the collector returns true after adding node, then return - nodeCollectorMap.put(nodeIdent, new Pair(aCollector, UUID.randomUUID())); - LOG.debug("NodeAdded: Num Nodes Registered with StatisticsManager:{}", - numNodesBeingCollected.incrementAndGet()); - return; - } - } - // no collector was able to add this node - LOG.info("No existing collector found for new node. Creating a new collector for {}", nodeIdent); - final StatPermCollectorImpl newCollector = new StatPermCollectorImpl(this, - statManagerConfig.getMinRequestNetMonitorInterval(), statCollectors.size() + 1, - statManagerConfig.getMaxNodesForCollector()); - - final List statCollectorsNew = new ArrayList<>(statCollectors); - statCollectorsNew.add(newCollector); - statCollectors = Collections.unmodifiableList(statCollectorsNew); - nodeCollectorMap.put(nodeIdent, new Pair(newCollector, UUID.randomUUID())); - LOG.debug("NodeAdded: Num Nodes Registered with StatisticsManager:{}", numNodesBeingCollected.incrementAndGet()); - - newCollector.connectedNodeRegistration(nodeIdent, statTypes, nrOfSwitchTables); - } - - - } else { - // add to the collector, even if it rejects it. - collectorUUIDPair.getLeft().connectedNodeRegistration(nodeIdent, statTypes, nrOfSwitchTables); - } - } - - - @Override - public void disconnectedNodeUnregistration(final InstanceIdentifier nodeIdent) { - flowListeningCommiter.cleanForDisconnect(nodeIdent); - - Pair collectorUUIDPair = nodeCollectorMap.get(nodeIdent); - if (collectorUUIDPair != null) { - StatPermCollector collector = collectorUUIDPair.getLeft(); - if (collector != null) { - nodeCollectorMap.remove(nodeIdent); - LOG.debug("NodeRemoved: Num Nodes Registered with StatisticsManager:{}", numNodesBeingCollected.decrementAndGet()); - - if (collector.disconnectedNodeUnregistration(nodeIdent)) { - if (!collector.hasActiveNodes()) { - synchronized (statCollectorLock) { - if (collector.hasActiveNodes()) { - return; - } - final List newStatColl = new ArrayList<>(statCollectors); - newStatColl.remove(collector); - statCollectors = Collections.unmodifiableList(newStatColl); - } - } - LOG.info("Node:{} successfully removed by StatisticsManager ", nodeIdent); - } else { - LOG.error("Collector not disconnecting for node, no operations will be committed for this node:{}", nodeIdent); - } - } else { - LOG.error("Unexpected error, collector not found in collectorUUIDPair for node:{}, UUID:{}", nodeIdent, collectorUUIDPair.getRight()); - } - - } else { - LOG.error("Received node removed for {}, but unable to find it in nodeCollectorMap", nodeIdent); - } - } - - @Override - public void registerAdditionalNodeFeature(final InstanceIdentifier nodeIdent, - final StatCapabTypes statCapab) { - for (final StatPermCollector collector : statCollectors) { - if (collector.registerAdditionalNodeFeature(nodeIdent, statCapab)) { - return; - } - } - LOG.debug("Node {} has not been extended for feature {}!", nodeIdent, statCapab); - } - - @Override - public void unregisterNodeStats(final InstanceIdentifier nodeIdent, - final StatCapabTypes statCapab) { - for (final StatPermCollector collector : statCollectors) { - if (collector.unregisterNodeStats(nodeIdent, statCapab)) { - return; - } - } - LOG.debug("Stats type {} is not removed from the node {}!", statCapab,nodeIdent ); - } - - /* Getter internal Statistic Manager Job Classes */ - @Override - public StatRpcMsgManager getRpcMsgManager() { - return rpcMsgManager; - } - - @Override - public StatNodeRegistration getNodeRegistrator() { - return nodeRegistrator; - } - - @Override - public StatListeningCommiter getFlowListenComit() { - return flowListeningCommiter; - } - - @Override - public StatListeningCommiter getMeterListenCommit() { - return meterListeningCommiter; - } - - @Override - public StatListeningCommiter getGroupListenCommit() { - return groupListeningCommiter; - } - - @Override - public StatListeningCommiter getQueueNotifyCommit() { - return queueNotifyCommiter; - } - - - @Override - public StatNotifyCommiter getTableNotifCommit() { - return tableNotifCommiter; - } - - @Override - public StatNotifyCommiter getPortNotifyCommit() { - return portNotifyCommiter; - } - - @Override - public StatisticsManagerConfig getConfiguration() { - return statManagerConfig; - } - - @Override - public UUID getGeneratedUUIDForNode(InstanceIdentifier nodeInstanceIdentifier) { - Pair permCollectorUUIDPair = nodeCollectorMap.get(nodeInstanceIdentifier); - if (permCollectorUUIDPair != null) { - return permCollectorUUIDPair.getRight(); - } - // we dont want to mark operations with null uuid and get NPEs later. So mark them with invalid ones - return UUID.fromString("invalid-uuid"); - } - - @Override - public void setOwnershipService(EntityOwnershipService ownershipService) { - this.ownershipService = ownershipService; - } - - @Override - public EntityOwnershipService getOwnershipService() { - return this.ownershipService; - } - -} - diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/FlowComparator.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/FlowComparator.java deleted file mode 100644 index 4cfd1d0ebf..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/FlowComparator.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2013, 2015 IBM Corporation and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl.helper; - -import java.util.ArrayList; -import java.util.Collection; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.Flow; -/** - * Utility class for comparing flows. - */ -public final class FlowComparator { - - private FlowComparator() { - throw new UnsupportedOperationException("Utilities class should not be instantiated"); - } - - private static final Collection> FLOW_COMPARATORS = new ArrayList<>(); - static { - FLOW_COMPARATORS.add(FlowComparatorFactory.createPriority()); - FLOW_COMPARATORS.add(FlowComparatorFactory.createTableId()); - FLOW_COMPARATORS.add(FlowComparatorFactory.createContainerName()); - FLOW_COMPARATORS.add(FlowComparatorFactory.createCookie()); - FLOW_COMPARATORS.add(FlowComparatorFactory.createMatch()); - } - - public static boolean flowEquals(final Flow statsFlow, final Flow storedFlow) { - if (statsFlow == null || storedFlow == null) { - return false; - } - - for (SimpleComparator flowComp : FLOW_COMPARATORS) { - if (!flowComp.areObjectsEqual(statsFlow, storedFlow)) { - return false; - } - } - - return true; - } -} diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/FlowComparatorFactory.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/FlowComparatorFactory.java deleted file mode 100644 index eb8357a55a..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/FlowComparatorFactory.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (c) 2013, 2015 IBM Corporation and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl.helper; - -import java.util.ArrayList; -import java.util.Collection; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.Flow; - -public final class FlowComparatorFactory { - - private FlowComparatorFactory() { - // NOOP - } - - private static final Collection> MATCH_COMPARATORS = new ArrayList<>(); - static { - MATCH_COMPARATORS.add(MatchComparatorFactory.createEthernet()); - MATCH_COMPARATORS.add(MatchComparatorFactory.createIcmpv4()); - MATCH_COMPARATORS.add(MatchComparatorFactory.createInPhyPort()); - MATCH_COMPARATORS.add(MatchComparatorFactory.createInPort()); - MATCH_COMPARATORS.add(MatchComparatorFactory.createIp()); - MATCH_COMPARATORS.add(MatchComparatorFactory.createL3()); - MATCH_COMPARATORS.add(MatchComparatorFactory.createL4()); - MATCH_COMPARATORS.add(MatchComparatorFactory.createProtocolMatchFields()); - MATCH_COMPARATORS.add(MatchComparatorFactory.createMetadata()); - MATCH_COMPARATORS.add(MatchComparatorFactory.createNull()); - MATCH_COMPARATORS.add(MatchComparatorFactory.createTunnel()); - MATCH_COMPARATORS.add(MatchComparatorFactory.createVlan()); - } - - public static SimpleComparator createContainerName() { - return new SimpleComparator() { - /** - * Compares flows by container name - */ - @Override - public boolean areObjectsEqual(Flow statsFlow, Flow storedFlow) { - if (statsFlow.getContainerName() == null) { - if (storedFlow.getContainerName() != null) { - return false; - } - } else if (!statsFlow.getContainerName().equals(storedFlow.getContainerName())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createPriority() { - return new SimpleComparator() { - /** - * Compares flows by priority - */ - @Override - public boolean areObjectsEqual(final Flow statsFlow, final Flow storedFlow) { - if (storedFlow.getPriority() == null) { - if (statsFlow.getPriority() != null && statsFlow.getPriority() != 0x8000) { - return false; - } - } else if (!statsFlow.getPriority().equals(storedFlow.getPriority())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createTableId() { - return new SimpleComparator() { - /** - * Compares flows by table ID - */ - @Override - public boolean areObjectsEqual(final Flow statsFlow, final Flow storedFlow) { - if (statsFlow.getTableId() == null) { - if (storedFlow.getTableId() != null) { - return false; - } - } else if (!statsFlow.getTableId().equals(storedFlow.getTableId())) { - return false; - } - return true; - } - }; - } - - /* - * TODO:Cookie is used in flow comparison for the applications using match extensions - * in their flow body. As of now openflowplugin don't use match extensions - * in flow comparison, that can create a scenario where more then one stored flow - * can match to any stats flow, if stored flows differ only by match extension. - * Once match extensions are part of flow comparison, we should remove cookie - * from flow comparison. - */ - public static SimpleComparator createCookie() { - return new SimpleComparator() { - /** - * Compares flows by cookie value - */ - @Override - public boolean areObjectsEqual(final Flow statsFlow, final Flow storedFlow) { - /* - * Cookie is an optional field, so user might not set it, but if switch - * get flow without cookie value , it will use 0 as a default cookie value - * and return cookie=0 when openflowplugin fetch the flow stats from switch. - * In this scenario flow comparison will fail. Below check make sure that - * if user didn't set cookie value while flow installation, skip the comparison. - */ - if(storedFlow.getCookie() == null){ - return true; - } - if (statsFlow.getCookie() == null) { - if (storedFlow.getCookie() != null) { - return false; - } - } else if (!statsFlow.getCookie().equals(storedFlow.getCookie())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createMatch() { - return new SimpleComparator() { - /** - * Compares flows by whole match - */ - @Override - public boolean areObjectsEqual(final Flow statsFlow, final Flow storedFlow) { - if (statsFlow.getMatch() == null) { - if (storedFlow.getMatch() != null) { - return false; - } - } else if (!compareMatches(statsFlow.getMatch(), storedFlow.getMatch())) { - return false; - } - return true; - } - }; - } - - - /** - * Explicit equals method to compare the 'match' for flows stored in the data-stores and flow fetched from the switch. - * Flow installation process has three steps - * 1) Store flow in config data store - * 2) and send it to plugin for installation - * 3) Flow gets installed in switch - * - * The flow user wants to install and what finally gets installed in switch can be slightly different. - * E.g, If user installs flow with src/dst ip=10.0.0.1/24, when it get installed in the switch - * src/dst ip will be changes to 10.0.0.0/24 because of netmask of 24. When statistics manager fetch - * stats it gets 10.0.0.0/24 rather then 10.0.0.1/24. Custom match takes care of by using masked ip - * while comparing two ip addresses. - * - * Sometimes when user don't provide few values that is required by flow installation request, like - * priority,hard timeout, idle timeout, cookies etc, plugin usages default values before sending - * request to the switch. So when statistics manager gets flow statistics, it gets the default value. - * But the flow stored in config data store don't have those defaults value. I included those checks - * in the customer flow/match equal function. - * - * - * @param statsMatch - * @param storedMatch - * @return - */ - private static boolean compareMatches(final Match statsMatch, final Match storedMatch) { - if (statsMatch == storedMatch) { - return true; - } - - for (SimpleComparator matchComp : MATCH_COMPARATORS) { - if (!matchComp.areObjectsEqual(statsMatch, storedMatch)) { - return false; - } - } - return true; - } -} diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/IntegerIpAddress.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/IntegerIpAddress.java deleted file mode 100644 index 86de07838d..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/IntegerIpAddress.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 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.applications.statistics.manager.impl.helper; - -/** - * 4B base + 4B mask wrapper - */ -public class IntegerIpAddress { - - int ip; - int mask; - - public IntegerIpAddress(final int ip, final int mask) { - this.ip = ip; - this.mask = mask; - } - - public int getIp() { - return ip; - } - - public int getMask() { - return mask; - } -} diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/MatchComparatorFactory.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/MatchComparatorFactory.java deleted file mode 100644 index 52c9c77e4f..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/MatchComparatorFactory.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (c) 2013, 2015 IBM Corporation and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.applications.statistics.manager.impl.helper; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match; -/** - * Provides comparator for comparing according to various {@link Match} attributes - * - */ -public final class MatchComparatorFactory { - - private MatchComparatorFactory() { - // NOOP - } - - public static SimpleComparator createNull() { - return new SimpleComparator() { - /** - * Comparation by whole object - */ - @Override - public boolean areObjectsEqual(Match statsMatch, Match storedMatch) { - return (statsMatch == null) == (storedMatch == null); - } - }; - } - - public static SimpleComparator createVlan() { - return new SimpleComparator() { - /** - * Comparation by VLAN - */ - @Override - public boolean areObjectsEqual(Match statsMatch, Match storedMatch) { - if (storedMatch == null) return false; - if (storedMatch.getVlanMatch() == null) { - if (statsMatch.getVlanMatch() != null) { - return false; - } - } else if (!storedMatch.getVlanMatch().equals(statsMatch.getVlanMatch())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createTunnel() { - return new SimpleComparator() { - /** - * Comparation by tunnel - */ - @Override - public boolean areObjectsEqual(Match statsMatch, Match storedMatch) { - if (storedMatch == null) return false; - if (storedMatch.getTunnel() == null) { - if (statsMatch.getTunnel() != null) { - return false; - } - } else if (!storedMatch.getTunnel().equals(statsMatch.getTunnel())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createProtocolMatchFields() { - return new SimpleComparator() { - /** - * Comparation by protocol fields - */ - @Override - public boolean areObjectsEqual(Match statsMatch, Match storedMatch) { - if (storedMatch == null) return false; - if (storedMatch.getProtocolMatchFields() == null) { - if (statsMatch.getProtocolMatchFields() != null) { - return false; - } - } else if (!storedMatch.getProtocolMatchFields().equals(statsMatch.getProtocolMatchFields())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createMetadata() { - return new SimpleComparator() { - /** - * Comparation by metadata - */ - @Override - public boolean areObjectsEqual(Match statsMatch, Match storedMatch) { - if (storedMatch == null) return false; - if (storedMatch.getMetadata() == null) { - if (statsMatch.getMetadata() != null) { - return false; - } - } else if (!storedMatch.getMetadata().equals(statsMatch.getMetadata())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createL4() { - return new SimpleComparator() { - /** - * Comparation by layer4 - */ - @Override - public boolean areObjectsEqual(Match statsMatch, Match storedMatch) { - if (storedMatch == null) return false; - if (storedMatch.getLayer4Match() == null) { - if (statsMatch.getLayer4Match() != null) { - return false; - } - } else if (!storedMatch.getLayer4Match().equals(statsMatch.getLayer4Match())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createL3() { - return new SimpleComparator() { - /** - * Comparation by layer3 - */ - @Override - public boolean areObjectsEqual(Match statsMatch, Match storedMatch) { - if (storedMatch == null) return false; - if (storedMatch.getLayer3Match() == null) { - if (statsMatch.getLayer3Match() != null) { - return false; - } - } else if (!MatchComparatorHelper.layer3MatchEquals(statsMatch.getLayer3Match(), storedMatch.getLayer3Match())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createIp() { - return new SimpleComparator() { - /** - * Comparation by Ip - */ - @Override - public boolean areObjectsEqual(Match statsMatch, Match storedMatch) { - if (storedMatch == null) return false; - if (storedMatch.getIpMatch() == null) { - if (statsMatch.getIpMatch() != null) { - return false; - } - } else if (!storedMatch.getIpMatch().equals(statsMatch.getIpMatch())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createInPort() { - return new SimpleComparator() { - /** - * Comparation by InPort - */ - @Override - public boolean areObjectsEqual(Match statsMatch, Match storedMatch) { - if (storedMatch == null) return false; - if (storedMatch.getInPort() == null) { - if (statsMatch.getInPort() != null) { - return false; - } - } else if (!storedMatch.getInPort().equals(statsMatch.getInPort())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createInPhyPort() { - return new SimpleComparator() { - /** - * Comparation by InPhyPort - */ - @Override - public boolean areObjectsEqual(Match statsMatch, Match storedMatch) { - if (storedMatch == null) return false; - if (storedMatch.getInPhyPort() == null) { - if (statsMatch.getInPhyPort() != null) { - return false; - } - } else if (!storedMatch.getInPhyPort().equals(statsMatch.getInPhyPort())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createEthernet() { - return new SimpleComparator() { - /** - * Comparation by Ethernet - */ - @Override - public boolean areObjectsEqual(Match statsMatch, Match storedMatch) { - if (storedMatch == null) return false; - if (storedMatch.getEthernetMatch() == null) { - if (statsMatch.getEthernetMatch() != null) { - return false; - } - } else if (!MatchComparatorHelper.ethernetMatchEquals(statsMatch.getEthernetMatch(), storedMatch.getEthernetMatch())) { - return false; - } - return true; - } - }; - } - - public static SimpleComparator createIcmpv4() { - return new SimpleComparator() { - /** - * Comparation by Icmpv4 - */ - @Override - public boolean areObjectsEqual(Match statsMatch, Match storedMatch) { - if (storedMatch == null) return false; - if (storedMatch.getIcmpv4Match() == null) { - if (statsMatch.getIcmpv4Match() != null) { - return false; - } - } else if (!storedMatch.getIcmpv4Match().equals(statsMatch.getIcmpv4Match())) { - return false; - } - return true; - } - }; - } - -} diff --git a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/MatchComparatorHelper.java b/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/MatchComparatorHelper.java deleted file mode 100644 index 20e5640c92..0000000000 --- a/applications/statistics-manager/src/main/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/MatchComparatorHelper.java +++ /dev/null @@ -1,648 +0,0 @@ -/** - * 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.applications.statistics.manager.impl.helper; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.net.InetAddresses; -import com.google.common.primitives.UnsignedBytes; -import java.math.BigInteger; -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Arrays; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Prefix; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DottedQuad; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.MacAddressFilter; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpSourceHardwareAddress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpTargetHardwareAddress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpTargetHardwareAddressBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatch; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Layer3Match; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatch; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv4Match; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv4MatchArbitraryBitMask; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv6Match; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv6MatchArbitraryBitMask; -import org.opendaylight.yang.gen.v1.urn.opendaylight.opendaylight.ipv6.arbitrary.bitmask.fields.rev160224.Ipv6ArbitraryMask; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author joe - * @author sai.marapareddy@gmail.com - * - */ -public class MatchComparatorHelper { - - private static final Logger LOG = LoggerFactory.getLogger(MatchComparatorHelper.class); - private static final int DEFAULT_SUBNET = 32; - private static final int IPV4_MASK_LENGTH = 32; - private static final int SHIFT_OCTET_1 = 24; - private static final int SHIFT_OCTET_2 = 16; - private static final int SHIFT_OCTET_3 = 8; - private static final int SHIFT_OCTET_4 = 0; - private static final int POSITION_OCTET_1 = 0; - private static final int POSITION_OCTET_2 = 1; - private static final int POSITION_OCTET_3 = 2; - private static final int POSITION_OCTET_4 = 3; - private static final String DEFAULT_ARBITRARY_BIT_MASK = "255.255.255.255"; - private static final String DEFAULT_IPV6_ARBITRARY_BIT_MASK = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"; - private static final String PREFIX_SEPARATOR = "/"; - private static final int IPV4_ADDRESS_LENGTH = 32; - private static final int IPV6_ADDRESS_LENGTH = 128; - private static final int BYTE_SIZE = 8; - - /* - * Custom EthernetMatch is required because mac address string provided by user in EthernetMatch can be in any case - * (upper or lower or mix). Ethernet Match which controller receives from switch is always an upper case string. - * Default EthernetMatch equals doesn't use equalsIgnoreCase() and hence it fails. E.g User provided mac address - * string in flow match is aa:bb:cc:dd:ee:ff and when controller fetch statistic data, openflow driver library - * returns AA:BB:CC:DD:EE:FF and default eqauls fails here. - */ - @VisibleForTesting - static boolean ethernetMatchEquals(final EthernetMatch statsEthernetMatch, final EthernetMatch storedEthernetMatch) { - boolean verdict = true; - final Boolean checkNullValues = checkNullValues(statsEthernetMatch, storedEthernetMatch); - if (checkNullValues != null) { - verdict = checkNullValues; - } else { - verdict = ethernetMatchFieldsEquals(statsEthernetMatch.getEthernetSource(), - storedEthernetMatch.getEthernetSource()); - if (verdict) { - verdict = ethernetMatchFieldsEquals(statsEthernetMatch.getEthernetDestination(), - storedEthernetMatch.getEthernetDestination()); - } - if (verdict) { - if (statsEthernetMatch.getEthernetType() == null) { - if (storedEthernetMatch.getEthernetType() != null) { - verdict = false; - } - } else { - verdict = statsEthernetMatch.getEthernetType().equals(storedEthernetMatch.getEthernetType()); - } - } - } - return verdict; - } - - static boolean ethernetMatchFieldsEquals(final MacAddressFilter statsEthernetMatchFields, - final MacAddressFilter storedEthernetMatchFields) { - boolean verdict = true; - final Boolean checkNullValues = checkNullValues(statsEthernetMatchFields, storedEthernetMatchFields); - if (checkNullValues != null) { - verdict = checkNullValues; - } else { - verdict = macAddressEquals(statsEthernetMatchFields.getAddress(), storedEthernetMatchFields.getAddress()); - if (verdict) { - verdict = macAddressEquals(statsEthernetMatchFields.getMask(), storedEthernetMatchFields.getMask()); - } - } - return verdict; - } - - static boolean macAddressEquals(final MacAddress statsMacAddress, final MacAddress storedMacAddress) { - boolean verdict = true; - final Boolean checkNullValues = checkNullValues(statsMacAddress, storedMacAddress); - if (checkNullValues != null) { - verdict = checkNullValues; - } else { - verdict = statsMacAddress.getValue().equalsIgnoreCase(storedMacAddress.getValue()); - } - return verdict; - } - - @VisibleForTesting - static boolean layer3MatchEquals(final Layer3Match statsLayer3Match, final Layer3Match storedLayer3Match) { - boolean verdict = true; - if (statsLayer3Match instanceof Ipv4Match && storedLayer3Match instanceof Ipv4Match) { - final Ipv4Match statsIpv4Match = (Ipv4Match) statsLayer3Match; - final Ipv4Match storedIpv4Match = (Ipv4Match) storedLayer3Match; - verdict = MatchComparatorHelper.compareIpv4PrefixNullSafe(storedIpv4Match.getIpv4Destination(), - statsIpv4Match.getIpv4Destination()); - if (verdict) { - verdict = MatchComparatorHelper.compareIpv4PrefixNullSafe(statsIpv4Match.getIpv4Source(), - storedIpv4Match.getIpv4Source()); - } - } else if (statsLayer3Match instanceof Ipv6Match && storedLayer3Match instanceof Ipv6Match) { - final Ipv6Match statsIpv6Match = (Ipv6Match) statsLayer3Match; - final Ipv6Match storedIpv6Match = (Ipv6Match) storedLayer3Match; - verdict = MatchComparatorHelper.compareIpv6PrefixNullSafe(storedIpv6Match.getIpv6Destination(), - statsIpv6Match.getIpv6Destination()); - if (verdict) { - verdict = MatchComparatorHelper.compareIpv6PrefixNullSafe(statsIpv6Match.getIpv6Source(), - storedIpv6Match.getIpv6Source()); - } - } else if (statsLayer3Match instanceof Ipv4MatchArbitraryBitMask && storedLayer3Match instanceof Ipv4MatchArbitraryBitMask) { - // At this moment storedIpv4MatchArbitraryBitMask & statsIpv4MatchArbitraryBitMask will always have non null arbitrary masks. - // In case of no / null arbitrary mask, statsLayer3Match will be an instance of Ipv4Match. - // Eg:- stats -> 1.0.1.0/255.0.255.0 stored -> 1.1.1.0/255.0.255.0 - final Ipv4MatchArbitraryBitMask statsIpv4MatchArbitraryBitMask= (Ipv4MatchArbitraryBitMask) statsLayer3Match; - final Ipv4MatchArbitraryBitMask storedIpv4MatchArbitraryBitMask = (Ipv4MatchArbitraryBitMask) storedLayer3Match; - if ((storedIpv4MatchArbitraryBitMask.getIpv4DestinationAddressNoMask() != null | - storedIpv4MatchArbitraryBitMask.getIpv4SourceAddressNoMask() != null)) { - if (storedIpv4MatchArbitraryBitMask.getIpv4DestinationAddressNoMask() != null) { - String storedDstIpAddress = normalizeIpv4Address(storedIpv4MatchArbitraryBitMask.getIpv4DestinationAddressNoMask(), - storedIpv4MatchArbitraryBitMask.getIpv4DestinationArbitraryBitmask()); - String statsDstIpAddress = normalizeIpv4Address(statsIpv4MatchArbitraryBitMask.getIpv4DestinationAddressNoMask(), - statsIpv4MatchArbitraryBitMask.getIpv4DestinationArbitraryBitmask()); - if (MatchComparatorHelper.compareStringNullSafe(storedIpv4MatchArbitraryBitMask.getIpv4DestinationArbitraryBitmask().getValue(), - statsIpv4MatchArbitraryBitMask.getIpv4DestinationArbitraryBitmask().getValue())) { - verdict = MatchComparatorHelper.compareStringNullSafe(storedDstIpAddress, - statsDstIpAddress); - } else { - verdict = false; - return verdict; - } - } - if (storedIpv4MatchArbitraryBitMask.getIpv4SourceAddressNoMask() != null) { - String storedSrcIpAddress = normalizeIpv4Address(storedIpv4MatchArbitraryBitMask.getIpv4SourceAddressNoMask() - ,storedIpv4MatchArbitraryBitMask.getIpv4SourceArbitraryBitmask()); - String statsSrcIpAddress = normalizeIpv4Address(statsIpv4MatchArbitraryBitMask.getIpv4SourceAddressNoMask() - ,statsIpv4MatchArbitraryBitMask.getIpv4SourceArbitraryBitmask()); - if (MatchComparatorHelper.compareStringNullSafe(storedIpv4MatchArbitraryBitMask.getIpv4SourceArbitraryBitmask().getValue(), - statsIpv4MatchArbitraryBitMask.getIpv4SourceArbitraryBitmask().getValue())) { - verdict = MatchComparatorHelper.compareStringNullSafe(storedSrcIpAddress, - statsSrcIpAddress); - } else { - verdict = false; - } - } - } else { - final Boolean nullCheckOut = checkNullValues(storedLayer3Match, statsLayer3Match); - if (nullCheckOut != null) { - verdict = nullCheckOut; - } else { - verdict = storedLayer3Match.equals(statsLayer3Match); - } - } - } else if (statsLayer3Match instanceof Ipv4Match && storedLayer3Match instanceof Ipv4MatchArbitraryBitMask) { - // Here stored netmask is an instance of Ipv4MatchArbitraryBitMask, when it is pushed in to switch - // it automatically converts it in to cidr format in case of certain subnet masks ( consecutive ones or zeroes) - // Eg:- stats src/dest -> 1.1.1.0/24 stored src/dest -> 1.1.1.0/255.255.255.0 - final Ipv4Match statsIpv4Match = (Ipv4Match) statsLayer3Match; - final Ipv4MatchArbitraryBitMask storedIpv4MatchArbitraryBitMask = (Ipv4MatchArbitraryBitMask) storedLayer3Match; - if (storedIpv4MatchArbitraryBitMask.getIpv4DestinationAddressNoMask() != null) { - Ipv4Prefix ipv4PrefixDestination; - if (storedIpv4MatchArbitraryBitMask.getIpv4DestinationArbitraryBitmask() != null) { - byte[] destByteMask = convertArbitraryMaskToByteArray(storedIpv4MatchArbitraryBitMask.getIpv4DestinationArbitraryBitmask()); - ipv4PrefixDestination = createPrefix(storedIpv4MatchArbitraryBitMask.getIpv4DestinationAddressNoMask(), destByteMask); - } else { - ipv4PrefixDestination = createPrefix(storedIpv4MatchArbitraryBitMask.getIpv4DestinationAddressNoMask()); - } - verdict = MatchComparatorHelper.compareIpv4PrefixNullSafe(ipv4PrefixDestination, statsIpv4Match.getIpv4Destination()); - if (verdict == false) { - return verdict; - } - } - if (storedIpv4MatchArbitraryBitMask.getIpv4SourceAddressNoMask() != null) { - Ipv4Prefix ipv4PrefixSource; - if (storedIpv4MatchArbitraryBitMask.getIpv4SourceArbitraryBitmask() != null) { - byte[] srcByteMask = convertArbitraryMaskToByteArray(storedIpv4MatchArbitraryBitMask.getIpv4SourceArbitraryBitmask()); - ipv4PrefixSource = createPrefix(storedIpv4MatchArbitraryBitMask.getIpv4SourceAddressNoMask(), srcByteMask); - } else { - ipv4PrefixSource = createPrefix(storedIpv4MatchArbitraryBitMask.getIpv4SourceAddressNoMask()); - } - verdict = MatchComparatorHelper.compareIpv4PrefixNullSafe(ipv4PrefixSource, statsIpv4Match.getIpv4Source()); - } - } else if (statsLayer3Match instanceof Ipv6MatchArbitraryBitMask && storedLayer3Match instanceof Ipv6MatchArbitraryBitMask) { - // At this moment storedIpv6MatchArbitraryBitMask & statsIpv6MatchArbitraryBitMask will always have non null arbitrary masks. - // In case of no / null arbitrary mask, statsLayer3Match will be an instance of Ipv6Match. - // Eg:- stats src/dest -> 2001:2001:2001:2001:2001:2001:2001:2001/FFFF:FFFF:FFFF:FFFF:0000:FFFF:FFFF:FFF0 - // stored src/dest -> 2001:2001:2001:2001:2001:2001:2001:2001/FFFF:FFFF:FFFF:FFFF:0000:FFFF:FFFF:FFF0 - final Ipv6MatchArbitraryBitMask statsIpv6MatchArbitraryBitMask= (Ipv6MatchArbitraryBitMask) statsLayer3Match; - final Ipv6MatchArbitraryBitMask storedIpv6MatchArbitraryBitMask = (Ipv6MatchArbitraryBitMask) storedLayer3Match; - if ((storedIpv6MatchArbitraryBitMask.getIpv6DestinationAddressNoMask() != null | - storedIpv6MatchArbitraryBitMask.getIpv6SourceAddressNoMask() != null)) { - if (storedIpv6MatchArbitraryBitMask.getIpv6DestinationAddressNoMask() != null) { - String storedDstIpAddress = normalizeIpv6Address(storedIpv6MatchArbitraryBitMask.getIpv6DestinationAddressNoMask(), - storedIpv6MatchArbitraryBitMask.getIpv6DestinationArbitraryBitmask()); - String statsDstIpAddress = normalizeIpv6Address(statsIpv6MatchArbitraryBitMask.getIpv6DestinationAddressNoMask(), - statsIpv6MatchArbitraryBitMask.getIpv6DestinationArbitraryBitmask()); - String storedDstMask = extractIpv6CanonicalForm(storedIpv6MatchArbitraryBitMask. - getIpv6DestinationArbitraryBitmask().getValue()).getHostAddress(); - String statsDstMask = extractIpv6CanonicalForm(statsIpv6MatchArbitraryBitMask. - getIpv6DestinationArbitraryBitmask().getValue()).getHostAddress(); - if (MatchComparatorHelper.compareStringNullSafe(storedDstMask,statsDstMask)) { - verdict = MatchComparatorHelper.compareStringNullSafe(storedDstIpAddress, - statsDstIpAddress); - } else { - verdict = false; - return verdict; - } - } - if (storedIpv6MatchArbitraryBitMask.getIpv6SourceAddressNoMask() != null) { - String storedSrcIpAddress = normalizeIpv6Address(storedIpv6MatchArbitraryBitMask.getIpv6SourceAddressNoMask() - ,storedIpv6MatchArbitraryBitMask.getIpv6SourceArbitraryBitmask()); - String statsSrcIpAddress = normalizeIpv6Address(statsIpv6MatchArbitraryBitMask.getIpv6SourceAddressNoMask() - ,statsIpv6MatchArbitraryBitMask.getIpv6SourceArbitraryBitmask()); - String storedSrcMask = extractIpv6CanonicalForm(storedIpv6MatchArbitraryBitMask. - getIpv6SourceArbitraryBitmask().getValue()).getHostAddress(); - String statsSrcMask = extractIpv6CanonicalForm(statsIpv6MatchArbitraryBitMask. - getIpv6SourceArbitraryBitmask().getValue()).getHostAddress(); - if (MatchComparatorHelper.compareStringNullSafe(storedSrcMask, statsSrcMask)) { - verdict = MatchComparatorHelper.compareStringNullSafe(storedSrcIpAddress, - statsSrcIpAddress); - } else { - verdict = false; - } - } - } else { - final Boolean nullCheckOut = checkNullValues(storedLayer3Match, statsLayer3Match); - if (nullCheckOut != null) { - verdict = nullCheckOut; - } else { - verdict = storedLayer3Match.equals(statsLayer3Match); - } - } - } else if (statsLayer3Match instanceof Ipv6Match && storedLayer3Match instanceof Ipv6MatchArbitraryBitMask) { - // Here stored netmask is an instance of Ipv6MatchArbitraryBitMask, when it is pushed in to switch - // it automatically converts it in to cidr format in case of certain subnet masks ( consecutive ones or zeroes) - // Eg:- stats src/dest -> 2001:2001:2001:2001:2001:2001:2001:2001/124 - // stored src/dest -> 2001:2001:2001:2001:2001:2001:2001:2001/FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFF0 - final Ipv6Match statsIpv6Match = (Ipv6Match) statsLayer3Match; - final Ipv6MatchArbitraryBitMask storedIpv6MatchArbitraryBitMask = (Ipv6MatchArbitraryBitMask) storedLayer3Match; - if (storedIpv6MatchArbitraryBitMask.getIpv6DestinationAddressNoMask() != null) { - Ipv6Prefix ipv6PrefixDestination; - if (storedIpv6MatchArbitraryBitMask.getIpv6DestinationArbitraryBitmask() != null) { - byte[] destByteMask = convertIpv6ArbitraryMaskToByteArray(storedIpv6MatchArbitraryBitMask.getIpv6DestinationArbitraryBitmask()); - ipv6PrefixDestination = createPrefix(storedIpv6MatchArbitraryBitMask.getIpv6DestinationAddressNoMask(), destByteMask); - } else { - ipv6PrefixDestination = createPrefix(storedIpv6MatchArbitraryBitMask.getIpv6DestinationAddressNoMask()); - } - verdict = MatchComparatorHelper.compareIpv6PrefixNullSafe(ipv6PrefixDestination, statsIpv6Match.getIpv6Destination()); - if (verdict == false) { - return verdict; - } - } - if (storedIpv6MatchArbitraryBitMask.getIpv6SourceAddressNoMask() != null) { - Ipv6Prefix ipv6PrefixSource; - if (storedIpv6MatchArbitraryBitMask.getIpv6SourceArbitraryBitmask() != null) { - byte[] srcByteMask = convertIpv6ArbitraryMaskToByteArray(storedIpv6MatchArbitraryBitMask.getIpv6SourceArbitraryBitmask()); - ipv6PrefixSource = createPrefix(storedIpv6MatchArbitraryBitMask.getIpv6SourceAddressNoMask(), srcByteMask); - } else { - ipv6PrefixSource = createPrefix(storedIpv6MatchArbitraryBitMask.getIpv6SourceAddressNoMask()); - } - verdict = MatchComparatorHelper.compareIpv6PrefixNullSafe(ipv6PrefixSource, statsIpv6Match.getIpv6Source()); - } - } else if (statsLayer3Match instanceof ArpMatch && storedLayer3Match instanceof ArpMatch) { - verdict = arpMatchEquals((ArpMatch)statsLayer3Match, (ArpMatch)storedLayer3Match); - } else { - final Boolean nullCheckOut = checkNullValues(storedLayer3Match, statsLayer3Match); - if (nullCheckOut != null) { - verdict = nullCheckOut; - } else { - verdict = storedLayer3Match.equals(statsLayer3Match); - } - } - return verdict; - } - - static boolean arpMatchEquals(final ArpMatch statsArpMatch, final ArpMatch storedArpMatch) { - - Integer statsOp = statsArpMatch.getArpOp(); - Integer storedOp = storedArpMatch.getArpOp(); - - Boolean nullCheck = checkNullValues(statsOp, storedOp); - if (nullCheck != null) { - if (nullCheck == false) { - return false; - } - } else if (!statsOp.equals(storedOp)) { - return false; - } - - Ipv4Prefix statsIp = statsArpMatch.getArpSourceTransportAddress(); - Ipv4Prefix storedIp = storedArpMatch.getArpSourceTransportAddress(); - if (!compareIpv4PrefixNullSafe(statsIp, storedIp)) { - return false; - } - - statsIp = statsArpMatch.getArpTargetTransportAddress(); - storedIp = storedArpMatch.getArpTargetTransportAddress(); - if (!compareIpv4PrefixNullSafe(statsIp, storedIp)) { - return false; - } - - MacAddressFilter statsMac = statsArpMatch.getArpSourceHardwareAddress(); - MacAddressFilter storedMac = storedArpMatch.getArpSourceHardwareAddress(); - if (!ethernetMatchFieldsEquals(statsMac, storedMac)) { - return false; - } - - statsMac = statsArpMatch.getArpTargetHardwareAddress(); - storedMac = storedArpMatch.getArpTargetHardwareAddress(); - if (!ethernetMatchFieldsEquals(statsMac, storedMac)) { - return false; - } - - return true; - } - - - /** - * TODO: why don't we use the default Ipv4Prefix.equals()? - * - * @param statsIpAddress - * @param storedIpAddress - * @return true if IPv4prefixes equals - */ - static boolean IpAddressEquals(final Ipv4Prefix statsIpAddress, final Ipv4Prefix storedIpAddress) { - final IntegerIpAddress statsIpAddressInt = MatchComparatorHelper.strIpToIntIp(statsIpAddress.getValue()); - final IntegerIpAddress storedIpAddressInt = MatchComparatorHelper.strIpToIntIp(storedIpAddress.getValue()); - - if (ipAndMaskBasedMatch(statsIpAddressInt, storedIpAddressInt)) { - return true; - } - if (ipBasedMatch(statsIpAddressInt, storedIpAddressInt)) { - return true; - } - return false; - } - - static boolean ipAndMaskBasedMatch(final IntegerIpAddress statsIpAddressInt, - final IntegerIpAddress storedIpAddressInt) { - return ((statsIpAddressInt.getIp() & statsIpAddressInt.getMask()) == (storedIpAddressInt.getIp() & storedIpAddressInt - .getMask())); - } - - static boolean ipBasedMatch(final IntegerIpAddress statsIpAddressInt, final IntegerIpAddress storedIpAddressInt) { - return (statsIpAddressInt.getIp() == storedIpAddressInt.getIp()); - } - - - private static boolean IpAddressEquals(Ipv6Prefix statsIpv6, Ipv6Prefix storedIpv6) { - final String[] statsIpMask = statsIpv6.getValue().split("/"); - final String[] storedIpMask = storedIpv6.getValue().split("/"); - if (! (statsIpMask.length > 1 && storedIpMask.length > 1 && statsIpMask[1].equals(storedIpMask[1]))){ - return false; - } - - final int prefix = Integer.parseInt(statsIpMask[1]); - final int byteIndex = prefix/BYTE_SIZE; - final int lastByteBits = BYTE_SIZE - (prefix % BYTE_SIZE); - final InetAddress statsIp = InetAddresses.forString(statsIpMask[0]); - final InetAddress storedIp = InetAddresses.forString(storedIpMask[0]); - byte[] statsIpArr = Arrays.copyOfRange(statsIp.getAddress(),0,byteIndex+1); - byte[] storedIpArr = Arrays.copyOfRange(storedIp.getAddress(),0,byteIndex+1); - statsIpArr[byteIndex] = (byte) (statsIpArr[byteIndex] & (0XFF << lastByteBits)); - storedIpArr[byteIndex] = (byte) (storedIpArr[byteIndex] & (0XFF << lastByteBits)); - if(Arrays.equals(statsIpArr,storedIpArr)) { - return true; - } - return false; - } - - static Boolean checkNullValues(final Object v1, final Object v2) { - Boolean verdict = null; - if (v1 == null && v2 != null) { - verdict = Boolean.FALSE; - } else if (v1 != null && v2 == null) { - verdict = Boolean.FALSE; - } else if (v1 == null && v2 == null) { - verdict = Boolean.TRUE; - } - return verdict; - } - - static boolean compareIpv4PrefixNullSafe(final Ipv4Prefix statsIpv4, final Ipv4Prefix storedIpv4) { - boolean verdict = true; - final Boolean checkDestNullValuesOut = checkNullValues(storedIpv4, statsIpv4); - if (checkDestNullValuesOut != null) { - verdict = checkDestNullValuesOut; - } else if (!IpAddressEquals(statsIpv4, storedIpv4)) { - verdict = false; - } - return verdict; - } - - static boolean compareStringNullSafe(final String stringA, final String stringB) { - boolean verdict = true; - final Boolean checkDestNullValuesOut = checkNullValues(stringA,stringB); - if (checkDestNullValuesOut != null) { - verdict = checkDestNullValuesOut; - } else if (!stringA.equals(stringB)) { - verdict = false; - } - return verdict; - } - - private static boolean compareIpv6PrefixNullSafe(Ipv6Prefix statsIpv6, Ipv6Prefix storedIpv6) { - boolean verdict = true; - final Boolean checkDestNullValuesOut = checkNullValues(statsIpv6, storedIpv6); - if (checkDestNullValuesOut != null) { - verdict = checkDestNullValuesOut; - } else if (!IpAddressEquals(statsIpv6, storedIpv6)) { - verdict = false; - } - return verdict; - } - - /** - * Method return integer version of ip address. Converted int will be mask if mask specified - */ - static IntegerIpAddress strIpToIntIp(final String ipAddresss) { - - final String[] parts = ipAddresss.split("/"); - final String ip = parts[0]; - int prefix; - - if (parts.length < 2) { - prefix = DEFAULT_SUBNET; - } else { - prefix = Integer.parseInt(parts[1]); - if (prefix < 0 || prefix > IPV4_MASK_LENGTH) { - final StringBuilder stringBuilder = new StringBuilder( - "Valid values for mask are from range 0 - 32. Value "); - stringBuilder.append(prefix); - stringBuilder.append(" is invalid."); - throw new IllegalStateException(stringBuilder.toString()); - } - } - - IntegerIpAddress integerIpAddress = null; - - final Inet4Address addr = ((Inet4Address) InetAddresses.forString(ip)); - final byte[] addrBytes = addr.getAddress(); - // FIXME: what is meaning of anding with 0xFF? Probably could be removed. - final int ipInt = ((addrBytes[POSITION_OCTET_1] & 0xFF) << SHIFT_OCTET_1) - | ((addrBytes[POSITION_OCTET_2] & 0xFF) << SHIFT_OCTET_2) - | ((addrBytes[POSITION_OCTET_3] & 0xFF) << SHIFT_OCTET_3) - | ((addrBytes[POSITION_OCTET_4] & 0xFF) << SHIFT_OCTET_4); - - // FIXME: Is this valid? - final int mask = 0xffffffff << DEFAULT_SUBNET - prefix; - - integerIpAddress = new IntegerIpAddress(ipInt, mask); - - return integerIpAddress; - } - - static boolean isArbitraryBitMask(byte[] byteMask) { - if (byteMask == null) { - return false; - } else { - ArrayList integerMaskArrayList = new ArrayList(); - String maskInBits; - // converting byte array to bits - maskInBits = new BigInteger(1, byteMask).toString(2); - ArrayList stringMaskArrayList = new ArrayList(Arrays.asList(maskInBits.split("(?!^)"))); - for(String string:stringMaskArrayList){ - integerMaskArrayList.add(Integer.parseInt(string)); - } - return checkArbitraryBitMask(integerMaskArrayList); - } - } - - static boolean checkArbitraryBitMask(ArrayList arrayList) { - if (arrayList.size()>0 && arrayList.size()< IPV4_MASK_LENGTH ) { - // checks 0*1* case - Leading zeros in arrayList are truncated - return true; - } else { - //checks 1*0*1 case - for(int i=0; i { - - boolean areObjectsEqual(T obj1, T obj2); - -} \ No newline at end of file diff --git a/applications/statistics-manager/src/main/resources/org/opendaylight/blueprint/statistics-manager.xml b/applications/statistics-manager/src/main/resources/org/opendaylight/blueprint/statistics-manager.xml deleted file mode 100644 index 3155c1f912..0000000000 --- a/applications/statistics-manager/src/main/resources/org/opendaylight/blueprint/statistics-manager.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/applications/statistics-manager/src/main/yang/statistics-manager-app-config.yang b/applications/statistics-manager/src/main/yang/statistics-manager-app-config.yang deleted file mode 100644 index d8243269a4..0000000000 --- a/applications/statistics-manager/src/main/yang/statistics-manager-app-config.yang +++ /dev/null @@ -1,25 +0,0 @@ -module statistics-manager-app-config { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:openflowplugin:app:statistics-manager:config"; - prefix "statistics-manager-app-config"; - - description - "Configuration for Statistics Manager application."; - - revision "2016-05-09" { - description - "Initial revision"; - } - - container statistics-manager-app-config { - leaf min-request-net-monitor-interval { - type int32; - default 3000; - } - - leaf max-nodes-for-collector { - type int32; - default 16; - } - } -} \ No newline at end of file diff --git a/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatAbstractListenCommitTest.java b/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatAbstractListenCommitTest.java deleted file mode 100644 index 2eaac49f54..0000000000 --- a/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatAbstractListenCommitTest.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.applications.statistics.manager.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import com.google.common.base.Optional; -import com.google.common.util.concurrent.CheckedFuture; -import com.google.common.util.concurrent.Futures; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction; - -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.binding.NotificationListener; - -import java.util.ArrayList; -import java.util.Collection; - - -/** - * Unit tests for StatAbstractListenCommit. - * - * @author Thomas Pantelis - */ -public class StatAbstractListenCommitTest { - - @Mock - private NotificationProviderService mockNotificationProviderService; - - @Mock - private StatisticsManager mockStatisticsManager; - - @Mock - private DataBroker mockDataBroker; - - @Mock - private NotificationListener mockNotificationListener; - - @Mock - private StatNodeRegistration statsNodeRegistration; - - - @SuppressWarnings("rawtypes") - private StatAbstractListenCommit statCommit; - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - statCommit = new StatAbstractListenCommit(mockStatisticsManager, mockDataBroker, - mockNotificationProviderService, DataObject.class, statsNodeRegistration) { - @Override - protected InstanceIdentifier getWildCardedRegistrationPath() { - return InstanceIdentifier.create(DataObject.class); - } - - @Override - protected void processDataChange(Collection changes) { - - } - - @Override - protected NotificationListener getStatNotificationListener() { - return mockNotificationListener; - } - }; - } - - - @SuppressWarnings("unchecked") - @Test - public void testReadLatestConfiguration() { - - InstanceIdentifier path = InstanceIdentifier.create(DataObject.class); - - ReadOnlyTransaction mockReadTx = mock(ReadOnlyTransaction.class); - doReturn(mockReadTx).when(mockDataBroker).newReadOnlyTransaction(); - - Optional expected = Optional.of(mock(DataObject.class)); - doReturn(Futures.immediateCheckedFuture(expected)).when(mockReadTx).read( - LogicalDatastoreType.CONFIGURATION, path); - - Optional actual = statCommit.readLatestConfiguration(path); - - assertSame("Optional instance", expected, actual); - - actual = statCommit.readLatestConfiguration(path); - - assertSame("Optional instance", expected, actual); - - verify(mockReadTx, never()).close(); - verify(mockDataBroker).newReadOnlyTransaction(); - } - - @SuppressWarnings("unchecked") - @Test - public void testReadLatestConfigurationWithReadFailure() { - - InstanceIdentifier path = InstanceIdentifier.create(DataObject.class); - - ReadOnlyTransaction mockReadTx1 = mock(ReadOnlyTransaction.class); - ReadOnlyTransaction mockReadTx2 = mock(ReadOnlyTransaction.class); - ReadOnlyTransaction mockReadTx3 = mock(ReadOnlyTransaction.class); - doReturn(mockReadTx1).doReturn(mockReadTx2).doReturn(mockReadTx3).when(mockDataBroker).newReadOnlyTransaction(); - - doReturn(Futures.immediateFailedCheckedFuture(new ReadFailedException("mock"))).when(mockReadTx1).read( - LogicalDatastoreType.CONFIGURATION, path); - - doReturn(Futures.immediateFailedCheckedFuture(new ReadFailedException("mock"))).when(mockReadTx2).read( - LogicalDatastoreType.CONFIGURATION, path); - - Optional expected = Optional.of(mock(DataObject.class)); - doReturn(Futures.immediateCheckedFuture(expected)).when(mockReadTx3).read( - LogicalDatastoreType.CONFIGURATION, path); - - Optional actual = statCommit.readLatestConfiguration(path); - - assertEquals("Optional isPresent", false, actual.isPresent()); - - actual = statCommit.readLatestConfiguration(path); - - assertSame("Optional instance", expected, actual); - } - - @SuppressWarnings("unchecked") - @Test - public void testReadLatestConfigurationWithInterveningOnDataTreeChanged() { - - InstanceIdentifier path = InstanceIdentifier.create(DataObject.class); - - ReadOnlyTransaction mockReadTx1 = mock(ReadOnlyTransaction.class); - ReadOnlyTransaction mockReadTx2 = mock(ReadOnlyTransaction.class); - doReturn(mockReadTx1).doReturn(mockReadTx2).when(mockDataBroker).newReadOnlyTransaction(); - - final Optional expected1 = Optional.of(mock(DataObject.class)); - Answer, ReadFailedException>> answer = - new Answer, ReadFailedException>>() { - @Override - public CheckedFuture, ReadFailedException> answer( - InvocationOnMock unused) { - statCommit.onDataTreeChanged(new ArrayList<>()); - return Futures.immediateCheckedFuture(expected1); - } - }; - - doAnswer(answer).when(mockReadTx1).read(LogicalDatastoreType.CONFIGURATION, path); - - Optional expected2 = Optional.of(mock(DataObject.class)); - doReturn(Futures.immediateCheckedFuture(expected2)).when(mockReadTx2).read( - LogicalDatastoreType.CONFIGURATION, path); - - Optional actual = statCommit.readLatestConfiguration(path); - - assertSame("Optional instance", expected1, actual); - - actual = statCommit.readLatestConfiguration(path); - - assertSame("Optional instance", expected2, actual); - - actual = statCommit.readLatestConfiguration(path); - - assertSame("Optional instance", expected2, actual); - - verify(mockReadTx1).close(); - verify(mockReadTx2, never()).close(); - verify(mockDataBroker, times(2)).newReadOnlyTransaction(); - } -} diff --git a/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitFlowTest.java b/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitFlowTest.java deleted file mode 100644 index bf7917d0be..0000000000 --- a/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/StatListenCommitFlowTest.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright (c) 2015 Tata Consultancy services and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.statistics.manager.impl; - -import static org.junit.Assert.fail; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction; -import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatNodeRegistration; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowHashIdMapping; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowHashIdMappingBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.nodes.node.table.FlowHashIdMap; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.nodes.node.table.FlowHashIdMapBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.nodes.node.table.FlowHashIdMapKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowsStatisticsUpdate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowsStatisticsUpdateBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.flow.and.statistics.map.list.FlowAndStatisticsMapList; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.flow.and.statistics.map.list.FlowAndStatisticsMapListBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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.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 com.google.common.base.Optional; -import com.google.common.util.concurrent.Futures; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Unit tests for StatListenCommitFlow. - * - * @author Monika Verma - */ -public class StatListenCommitFlowTest { - - private static final Logger LOG = LoggerFactory.getLogger(StatListenCommitFlowTest.class); - - @Mock - private NotificationProviderService mockNotificationProviderService; - - @Mock - private StatisticsManager mockStatisticsManager; - - @Mock - private DataBroker mockDataBroker; - - @Mock - private StatNodeRegistration statsNodeRegistration; - - private StatListenCommitFlow statCommitFlow; - private TableKey tableKey = new TableKey((short) 12); - - @Before - public void init() { - MockitoAnnotations.initMocks(this); - statCommitFlow = new StatListenCommitFlow(mockStatisticsManager, mockDataBroker, - mockNotificationProviderService, statsNodeRegistration); - } - - @Test - public void testStatsFlowCommitAllWithAlienSystemFlowId() throws InvocationTargetException { - Class[] argClasses = { List.class, InstanceIdentifier.class, ReadWriteTransaction.class }; - - List flowStats = new ArrayList(); - flowStats.add(createFlowAndStatisticsMapList()); - - FlowCapableNode flowCapableNode = createFlowCapableNode("#UF$TABLE*F1"); - - FlowsStatisticsUpdate flowsStatisticsUpdate = createFlowsStatisticsUpdate(); - - InstanceIdentifier nodeIdent = InstanceIdentifier.create(Nodes.class).child(Node.class, - new NodeKey(flowsStatisticsUpdate.getId())); - - final InstanceIdentifier fNodeIdent = nodeIdent.augmentation(FlowCapableNode.class); - - InstanceIdentifier
path = InstanceIdentifier.create(Nodes.class) - .child(Node.class, new NodeKey(flowsStatisticsUpdate.getId())).augmentation(FlowCapableNode.class) - .child(Table.class, tableKey); - - ReadWriteTransaction mockReadWriteTx = mock(ReadWriteTransaction.class); - doReturn(mockReadWriteTx).when(mockDataBroker).newReadWriteTransaction(); - Optional expected = Optional.of(flowCapableNode); - doReturn(Futures.immediateCheckedFuture(expected)).when(mockReadWriteTx).read(LogicalDatastoreType.OPERATIONAL, - fNodeIdent); - - ReadOnlyTransaction mockReadTx = mock(ReadOnlyTransaction.class); - doReturn(mockReadTx).when(mockDataBroker).newReadOnlyTransaction(); - Optional
expected1 = Optional.of(flowCapableNode.getTable().get(0)); - doReturn(Futures.immediateCheckedFuture(expected1)).when(mockReadTx).read(LogicalDatastoreType.CONFIGURATION, - path); - - Object[] argObjects = { flowStats, nodeIdent, mockReadWriteTx }; - - Method method; - try { - method = StatListenCommitFlow.class.getDeclaredMethod("statsFlowCommitAll", argClasses); - method.setAccessible(true); - method.invoke(statCommitFlow, argObjects); - } catch (Exception e) { - LOG.error("Exception occurred: {} ", e.getMessage(), e); - fail(e.getCause().toString()); - } - } - - private FlowsStatisticsUpdate createFlowsStatisticsUpdate() { - return new FlowsStatisticsUpdateBuilder().setId(new NodeId("S1")) - .setTransactionId(new TransactionId(new java.math.BigInteger("18446744073709551615"))) - .setMoreReplies(false).build(); - } - - private FlowAndStatisticsMapList createFlowAndStatisticsMapList() { - return new FlowAndStatisticsMapListBuilder().setFlowName("testFlow").setFlowId(new FlowId("F1")) - .setTableId(tableKey.getId()).setMatch(new MatchBuilder().build()).setPriority(2) - .setCookie(new FlowCookie(new java.math.BigInteger("18446744073709551615"))).build(); - } - - private FlowCapableNode createFlowCapableNode(String flowId) { - - List
tableList = new ArrayList
(); - List flowList = new ArrayList(); - flowList.add(new FlowBuilder().setFlowName("testFlow") - .setId(new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId("F1")).build()); - List flowHashIdMapList = new ArrayList(); - flowHashIdMapList.add(new FlowHashIdMapBuilder() - .setFlowId(new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId(flowId)) - .setHash("TestFlow").setKey(new FlowHashIdMapKey("FM1")).build()); - tableList.add(new TableBuilder() - .setFlow(flowList) - .setId((short) 12) - .setKey(tableKey) - .addAugmentation(FlowHashIdMapping.class, - new FlowHashIdMappingBuilder().setFlowHashIdMap(flowHashIdMapList).build()).build()); - - return new FlowCapableNodeBuilder().setDescription("test").setTable(tableList).build(); - } - - @Test - public void testStatsFlowCommitAll() throws InvocationTargetException { - Class[] argClasses = { List.class, InstanceIdentifier.class, ReadWriteTransaction.class }; - - List flowStats = new ArrayList(); - flowStats.add(createFlowAndStatisticsMapList()); - - FlowCapableNode flowCapableNode = createFlowCapableNode("F1"); - - FlowsStatisticsUpdate flowsStatisticsUpdate = createFlowsStatisticsUpdate(); - - InstanceIdentifier nodeIdent = InstanceIdentifier.create(Nodes.class).child(Node.class, - new NodeKey(flowsStatisticsUpdate.getId())); - - final InstanceIdentifier fNodeIdent = nodeIdent.augmentation(FlowCapableNode.class); - - InstanceIdentifier
path = InstanceIdentifier.create(Nodes.class) - .child(Node.class, new NodeKey(flowsStatisticsUpdate.getId())).augmentation(FlowCapableNode.class) - .child(Table.class, tableKey); - - ReadWriteTransaction mockReadWriteTx = mock(ReadWriteTransaction.class); - doReturn(mockReadWriteTx).when(mockDataBroker).newReadWriteTransaction(); - Optional expected = Optional.of(flowCapableNode); - doReturn(Futures.immediateCheckedFuture(expected)).when(mockReadWriteTx).read(LogicalDatastoreType.OPERATIONAL, - fNodeIdent); - - ReadOnlyTransaction mockReadTx = mock(ReadOnlyTransaction.class); - doReturn(mockReadTx).when(mockDataBroker).newReadOnlyTransaction(); - Optional
expected1 = Optional.of(flowCapableNode.getTable().get(0)); - doReturn(Futures.immediateCheckedFuture(expected1)).when(mockReadTx).read(LogicalDatastoreType.CONFIGURATION, - path); - - Object[] argObjects = { flowStats, nodeIdent, mockReadWriteTx }; - - Method method; - try { - method = StatListenCommitFlow.class.getDeclaredMethod("statsFlowCommitAll", argClasses); - method.setAccessible(true); - method.invoke(statCommitFlow, argObjects); - } catch (Exception e) { - LOG.error("Exception occurred: {} ", e.getMessage(), e); - fail(e.getCause().toString()); - } - } - - @Test - public void testStatsFlowCommitAllWithDefaultAlienSystemFlowId() throws InvocationTargetException { - Class[] argClasses = { List.class, InstanceIdentifier.class, ReadWriteTransaction.class }; - - List flowStats = new ArrayList(); - flowStats.add(createFlowAndStatisticsMapList()); - - FlowCapableNode flowCapableNode = createFlowCapableNode("#UF$TABLE*12-1"); - - FlowsStatisticsUpdate flowsStatisticsUpdate = createFlowsStatisticsUpdate(); - - InstanceIdentifier nodeIdent = InstanceIdentifier.create(Nodes.class).child(Node.class, - new NodeKey(flowsStatisticsUpdate.getId())); - - final InstanceIdentifier fNodeIdent = nodeIdent.augmentation(FlowCapableNode.class); - - InstanceIdentifier
path = InstanceIdentifier.create(Nodes.class) - .child(Node.class, new NodeKey(flowsStatisticsUpdate.getId())).augmentation(FlowCapableNode.class) - .child(Table.class, tableKey); - - ReadWriteTransaction mockReadWriteTx = mock(ReadWriteTransaction.class); - doReturn(mockReadWriteTx).when(mockDataBroker).newReadWriteTransaction(); - Optional expected = Optional.of(flowCapableNode); - doReturn(Futures.immediateCheckedFuture(expected)).when(mockReadWriteTx).read(LogicalDatastoreType.OPERATIONAL, - fNodeIdent); - - ReadOnlyTransaction mockReadTx = mock(ReadOnlyTransaction.class); - doReturn(mockReadTx).when(mockDataBroker).newReadOnlyTransaction(); - Optional
expected1 = Optional.of(flowCapableNode.getTable().get(0)); - doReturn(Futures.immediateCheckedFuture(expected1)).when(mockReadTx).read(LogicalDatastoreType.CONFIGURATION, - path); - - Object[] argObjects = { flowStats, nodeIdent, mockReadWriteTx }; - - Method method; - try { - method = StatListenCommitFlow.class.getDeclaredMethod("statsFlowCommitAll", argClasses); - method.setAccessible(true); - method.invoke(statCommitFlow, argObjects); - } catch (Exception e) { - LOG.error("Exception occurred: {} ", e.getMessage(), e); - fail(e.getCause().toString()); - } - } -} diff --git a/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/FlowComparatorFactoryTest.java b/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/FlowComparatorFactoryTest.java deleted file mode 100644 index cc656822fd..0000000000 --- a/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/FlowComparatorFactoryTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2013 IBM Corporation. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.applications.statistics.manager.impl.helper; - -import static org.junit.Assert.assertEquals; - -import java.math.BigInteger; -import org.junit.BeforeClass; -import org.junit.Test; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.Flow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.TunnelBuilder; - -public final class FlowComparatorFactoryTest { - - private static Flow statsFlow; - private static Flow storedFlow; - private static Flow nullFlow; - private static Flow copyStatsFlow; - - @BeforeClass - public static void initialization() { - statsFlow = prepareFlow("statsFlow", (short) 1, 1, 1); - copyStatsFlow = prepareFlow("statsFlow", (short) 1, 1, 1); - storedFlow = prepareFlow("storedFlow", (short) 2, 2, 2); - nullFlow = new FlowBuilder().build(); - } - - private static Flow prepareFlow(String containerName, short tableId, int priority, int tunnelId) { - final FlowBuilder flowBuilder = new FlowBuilder(); - flowBuilder.setContainerName(containerName); - flowBuilder.setTableId(tableId); - flowBuilder.setPriority(priority); - flowBuilder.setMatch(new MatchBuilder().setTunnel( - new TunnelBuilder().setTunnelId(BigInteger.valueOf(tunnelId)).build()).build()); - return flowBuilder.build(); - } - - @Test - public void containerNameComparationTest() { - final SimpleComparator simpleComparator = FlowComparatorFactory.createContainerName(); - compareViaComparator(simpleComparator); - assertEquals(false, simpleComparator.areObjectsEqual(nullFlow, storedFlow)); - } - - - @Test - public void tableIdComparationTest() { - final SimpleComparator simpleComparator = FlowComparatorFactory.createTableId(); - compareViaComparator(simpleComparator); - assertEquals(false, simpleComparator.areObjectsEqual(nullFlow, storedFlow)); - } - - @Test - public void priorityComparationTest() { - final SimpleComparator simpleComparator = FlowComparatorFactory.createPriority(); - compareViaComparator(simpleComparator); - assertEquals(false, simpleComparator.areObjectsEqual(storedFlow, nullFlow)); - } - - @Test - public void matchComparationTest() { - final SimpleComparator simpleComparator = FlowComparatorFactory.createMatch(); - compareViaComparator(simpleComparator); - assertEquals(false, simpleComparator.areObjectsEqual(nullFlow, storedFlow)); - assertEquals(true, simpleComparator.areObjectsEqual(statsFlow, copyStatsFlow)); - assertEquals(false,simpleComparator.areObjectsEqual(statsFlow,nullFlow)); - } - - private void compareViaComparator(SimpleComparator simpleComparator) { - assertEquals(true, simpleComparator.areObjectsEqual(nullFlow, nullFlow)); - assertEquals(false, simpleComparator.areObjectsEqual(statsFlow, storedFlow)); - assertEquals(true, simpleComparator.areObjectsEqual(statsFlow, statsFlow)); - } -} diff --git a/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/MatchComparatorFactoryTest.java b/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/MatchComparatorFactoryTest.java deleted file mode 100644 index e0af55b899..0000000000 --- a/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/MatchComparatorFactoryTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * 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.applications.statistics.manager.impl.helper; - -import static org.junit.Assert.assertEquals; -import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetTypeBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv4MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.IpMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.SctpMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.MetadataBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.ProtocolMatchFieldsBuilder; -import java.math.BigInteger; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.TunnelBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.VlanMatchBuilder; -import org.junit.Test; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder; -import org.junit.BeforeClass; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.vlan.match.fields.VlanIdBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId; - -public class MatchComparatorFactoryTest { - - private static Match nullMatch; - private static Match storedMatch; - private static Match statsMatch; - - @BeforeClass - public static void initialization() { - statsMatch = prepareMatch(1, (long) 1, (short) 1, (long) 1, 1, 1, (short) 1, "1", (short) 1, (long)1); - // copyStatsMatch = prepareMatch(1); - storedMatch = prepareMatch(2, (long) 2, (short) 2, (long) 2, 2, 2, (short) 2, "2", (short) 2, (long)2); - nullMatch = new MatchBuilder().build(); - } - - private static Match prepareMatch(int vlanId, long tunelId, short mplsBos, long metadata, int portNumber, - int arpOp, short ipEcn, String nodeConnector, short icpmV4Code, long etherType) { - final MatchBuilder matchBuilder = new MatchBuilder(); - matchBuilder.setVlanMatch(new VlanMatchBuilder().setVlanId( - new VlanIdBuilder().setVlanId(new VlanId(vlanId)).build()).build()); - matchBuilder.setTunnel(new TunnelBuilder().setTunnelId(BigInteger.valueOf(tunelId)).build()); - matchBuilder.setProtocolMatchFields(new ProtocolMatchFieldsBuilder().setMplsBos(mplsBos).build()); - matchBuilder.setMetadata(new MetadataBuilder().setMetadata(BigInteger.valueOf(metadata)).build()); - matchBuilder.setLayer4Match(new SctpMatchBuilder().setSctpSourcePort(new PortNumber(portNumber)).build()); - matchBuilder.setLayer3Match(new ArpMatchBuilder().setArpOp(arpOp).build()); - matchBuilder.setIpMatch(new IpMatchBuilder().setIpEcn(ipEcn).build()); - matchBuilder.setInPort(new NodeConnectorId(nodeConnector)); - matchBuilder.setInPhyPort(new NodeConnectorId(nodeConnector)); - matchBuilder.setIcmpv4Match(new Icmpv4MatchBuilder().setIcmpv4Code(icpmV4Code).build()); - matchBuilder.setEthernetMatch(new EthernetMatchBuilder().setEthernetType( - new EthernetTypeBuilder().setType(new EtherType(etherType)).build()).build()); - return matchBuilder.build(); - } - - @Test - public void ethernetComparationTest() { - final SimpleComparator simpleComparator = MatchComparatorFactory.createEthernet(); - compareViaComparator(simpleComparator); - } - - @Test - public void nullComparationTest() { - final SimpleComparator simpleComparator = MatchComparatorFactory.createNull(); - assertEquals(true, simpleComparator.areObjectsEqual(null, null)); - assertEquals(false, simpleComparator.areObjectsEqual(null, storedMatch)); - assertEquals(false, simpleComparator.areObjectsEqual(statsMatch, null)); - } - - @Test - public void icmpv4ComparationTest() { - final SimpleComparator simpleComparator = MatchComparatorFactory.createIcmpv4(); - compareViaComparator(simpleComparator); - } - - @Test - public void inPhyPortComparationTest() { - final SimpleComparator simpleComparator = MatchComparatorFactory.createInPhyPort(); - compareViaComparator(simpleComparator); - } - - @Test - public void inPortComparationTest() { - final SimpleComparator simpleComparator = MatchComparatorFactory.createInPort(); - compareViaComparator(simpleComparator); - } - - @Test - public void ipComparationTest() { - final SimpleComparator simpleComparator = MatchComparatorFactory.createIp(); - compareViaComparator(simpleComparator); - } - - @Test - public void l3ComparationTest() { - final SimpleComparator simpleComparator = MatchComparatorFactory.createL3(); - compareViaComparator(simpleComparator); - } - - @Test - public void l4ComparationTest() { - final SimpleComparator simpleComparator = MatchComparatorFactory.createL4(); - compareViaComparator(simpleComparator); - } - - @Test - public void metadataComparationTest() { - final SimpleComparator simpleComparator = MatchComparatorFactory.createMetadata(); - compareViaComparator(simpleComparator); - } - - @Test - public void protocolMatchFieldsComparationTest() { - final SimpleComparator simpleComparator = MatchComparatorFactory.createProtocolMatchFields(); - compareViaComparator(simpleComparator); - } - - @Test - public void tunnelComparationTest() { - final SimpleComparator simpleComparator = MatchComparatorFactory.createTunnel(); - compareViaComparator(simpleComparator); - } - - @Test - public void vlanComparationTest() { - final SimpleComparator simpleComparator = MatchComparatorFactory.createVlan(); - compareViaComparator(simpleComparator); - } - - private void compareViaComparator(SimpleComparator simpleComparator) { - assertEquals(true, simpleComparator.areObjectsEqual(nullMatch, nullMatch)); - assertEquals(false, simpleComparator.areObjectsEqual(statsMatch, nullMatch)); - assertEquals(false, simpleComparator.areObjectsEqual(statsMatch, storedMatch)); - assertEquals(true, simpleComparator.areObjectsEqual(statsMatch, statsMatch)); - } - -} diff --git a/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/MatchComparatorHelperTest.java b/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/MatchComparatorHelperTest.java deleted file mode 100644 index 96a94dae9c..0000000000 --- a/applications/statistics-manager/src/test/java/org/opendaylight/openflowplugin/applications/statistics/manager/impl/helper/MatchComparatorHelperTest.java +++ /dev/null @@ -1,413 +0,0 @@ -/* - * Copyright (c) 2014, 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.statistics.manager.impl.helper; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Prefix; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DottedQuad; -import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetDestinationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetSourceBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetTypeBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv4MatchArbitraryBitMaskBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv4MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv6MatchArbitraryBitMaskBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv6MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.opendaylight.ipv6.arbitrary.bitmask.fields.rev160224.Ipv6ArbitraryMask; - -/** - * @author sai.marapareddy@gmail.com (arbitrary masks) - */ - -/** - * test of {@link MatchComparatorHelper} - */ -public class MatchComparatorHelperTest { - - /** - * mask for /32 - */ - private static final int DEFAULT_IPV4_MASK = 0xffffffff; - - /** - * mask for /30 - */ - private static final int IPV4_30_MASK = 0xfffffffc; - private static final int IP_ADDRESS = 0xC0A80101; - - /** - * The test of conversion valid IP addres without mask to binary form. - */ - @Test - public void validIpWithoutMaskTest() { - IntegerIpAddress intIp = MatchComparatorHelper.strIpToIntIp("192.168.1.1"); - assertEquals(IP_ADDRESS, intIp.getIp()); - assertEquals(DEFAULT_IPV4_MASK, intIp.getMask()); - } - - /** - * The test of conversion of valid IP address with valid mask to binary form. - */ - @Test - public void validIpWithValidMaskTest() { - IntegerIpAddress intIp = MatchComparatorHelper.strIpToIntIp("192.168.1.1/30"); - assertEquals(IP_ADDRESS, intIp.getIp()); - assertEquals(IPV4_30_MASK, intIp.getMask()); - } - - /** - * The test of conversion of valid IP address invalid mask to binary form. - */ - @Test - public void validIpWithInvalidMaskTest() { - try { - MatchComparatorHelper.strIpToIntIp("192.168.1.1/40"); - } catch (IllegalStateException e) { - assertEquals("Valid values for mask are from range 0 - 32. Value 40 is invalid.", e.getMessage()); - return; - } - fail("IllegalStateException was awaited (40 subnet is invalid)"); - } - - /** - * The test of conversion invalid IP address with valid mask to binary form. - */ - @Test - public void invalidIpWithValidMaskTest() { - try { - MatchComparatorHelper.strIpToIntIp("257.168.1.1/25"); - } catch (IllegalArgumentException e) { - assertEquals("'257.168.1.1' is not an IP string literal.", e.getMessage()); - } - } - - @Test - public void ethernetMatchEqualsTest() { - final EthernetMatchBuilder statsEthernetBuilder = new EthernetMatchBuilder(); - final EthernetMatchBuilder storedEthernetBuilder = new EthernetMatchBuilder(); - - assertEquals(true, MatchComparatorHelper.ethernetMatchEquals(null, null)); - - statsEthernetBuilder.setEthernetSource(new EthernetSourceBuilder().setAddress( - new MacAddress("11:22:33:44:55:66")).build()); - storedEthernetBuilder.setEthernetSource(new EthernetSourceBuilder().setAddress( - new MacAddress("11:22:33:44:55:77")).build()); - assertEquals(false, - MatchComparatorHelper.ethernetMatchEquals(statsEthernetBuilder.build(), storedEthernetBuilder.build())); - - storedEthernetBuilder.setEthernetSource(new EthernetSourceBuilder().setAddress( - new MacAddress("11:22:33:44:55:66")).build()); - statsEthernetBuilder.setEthernetDestination(new EthernetDestinationBuilder().setAddress( - new MacAddress("66:55:44:33:22:11")).build()); - storedEthernetBuilder.setEthernetDestination(new EthernetDestinationBuilder().setAddress( - new MacAddress("77:55:44:33:22:11")).build()); - assertEquals(false, - MatchComparatorHelper.ethernetMatchEquals(statsEthernetBuilder.build(), storedEthernetBuilder.build())); - - storedEthernetBuilder.setEthernetDestination(new EthernetDestinationBuilder().setAddress( - new MacAddress("66:55:44:33:22:11")).build()); - statsEthernetBuilder.setEthernetType(new EthernetTypeBuilder().setType(new EtherType((long) 1)).build()); - storedEthernetBuilder.setEthernetType(new EthernetTypeBuilder().setType(new EtherType((long) 1)).build()); - assertEquals(true, - MatchComparatorHelper.ethernetMatchEquals(statsEthernetBuilder.build(), storedEthernetBuilder.build())); - - statsEthernetBuilder.setEthernetType(null).build(); - assertEquals(false, - MatchComparatorHelper.ethernetMatchEquals(statsEthernetBuilder.build(), storedEthernetBuilder.build())); - - storedEthernetBuilder.setEthernetType(null).build(); - assertEquals(true, - MatchComparatorHelper.ethernetMatchEquals(statsEthernetBuilder.build(), storedEthernetBuilder.build())); - - } - - @Test - public void ethernetMatchFieldsEqualsTest() { - final EthernetSourceBuilder statsBuilder = new EthernetSourceBuilder(); - final EthernetSourceBuilder storedBuilder = new EthernetSourceBuilder(); - - assertEquals(true, MatchComparatorHelper.ethernetMatchFieldsEquals(null, null)); - - statsBuilder.setAddress(new MacAddress("11:22:33:44:55:66")); - storedBuilder.setAddress(new MacAddress("11:22:33:44:55:77")); - assertEquals(false, - MatchComparatorHelper.ethernetMatchFieldsEquals(statsBuilder.build(), storedBuilder.build())); - - storedBuilder.setAddress(new MacAddress("11:22:33:44:55:66")); - assertEquals(true, MatchComparatorHelper.ethernetMatchFieldsEquals(statsBuilder.build(), storedBuilder.build())); - } - - @Test - public void macAddressEqualsTest() { - assertEquals(true, MatchComparatorHelper.macAddressEquals(null, null)); - assertEquals(true, MatchComparatorHelper.macAddressEquals(new MacAddress("11:22:33:44:55:66"), new MacAddress( - "11:22:33:44:55:66"))); - assertEquals(false, MatchComparatorHelper.macAddressEquals(new MacAddress("11:22:33:44:55:66"), new MacAddress( - "11:22:33:44:55:77"))); - } - - @Test - public void checkNullValuesTest() { - assertEquals(false, MatchComparatorHelper.checkNullValues(null, "")); - assertEquals(false, MatchComparatorHelper.checkNullValues("", null)); - assertEquals(true, MatchComparatorHelper.checkNullValues(null, null)); - assertTrue(MatchComparatorHelper.checkNullValues("", "") == null); - } - - @Test - public void compareIpv4PrefixNullSafeTest() { - assertEquals(true, MatchComparatorHelper.compareIpv4PrefixNullSafe(null, null)); - assertEquals(true, MatchComparatorHelper.compareIpv4PrefixNullSafe(new Ipv4Prefix("192.168.1.1/31"), - new Ipv4Prefix("192.168.1.1/31"))); - - assertEquals(false, MatchComparatorHelper.compareIpv4PrefixNullSafe(new Ipv4Prefix("192.168.1.1/31"), - new Ipv4Prefix("191.168.1.1/31"))); - } - - @Test - public void compareStringNullSafeTest() { - assertEquals(true, MatchComparatorHelper.compareStringNullSafe(null,null)); - assertEquals(true, MatchComparatorHelper.compareStringNullSafe("Hello", "Hello")); - assertEquals(false, MatchComparatorHelper.compareStringNullSafe("Hello", "hello")); - } - - private static final int ip_192_168_1_1 = 0xC0A80101; - private static final int ip_192_168_1_4 = 0xC0A80104; - - @Test - public void ipBasedMatchTest() { - // are equals because only IP address is compared - assertEquals(true, MatchComparatorHelper.ipBasedMatch(new IntegerIpAddress(ip_192_168_1_1, 32), - new IntegerIpAddress(ip_192_168_1_1, 16))); - } - - @Test - public void ipAndMaskBasedMatchTest() { - // true because both cases are network 192.168.1.0 - assertEquals(true, MatchComparatorHelper.ipBasedMatch(new IntegerIpAddress(ip_192_168_1_1, 31), - new IntegerIpAddress(ip_192_168_1_1, 30))); - - // false because first is network 192.168.1.0 and second is 192.168.1.4 - assertEquals(false, MatchComparatorHelper.ipBasedMatch(new IntegerIpAddress(ip_192_168_1_1, 31), - new IntegerIpAddress(ip_192_168_1_4, 30))); - } - - @Test - public void layer3MatchEqualsTest() { - final Ipv4MatchBuilder statsBuilder = new Ipv4MatchBuilder(); - final Ipv4MatchBuilder storedBuilder = new Ipv4MatchBuilder(); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(), storedBuilder.build())); - statsBuilder.setIpv4Destination(new Ipv4Prefix("192.168.1.1/30")); - storedBuilder.setIpv4Destination(new Ipv4Prefix("191.168.1.1/30")); - assertEquals(false, MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(), storedBuilder.build())); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(null, null)); - assertEquals(true, - MatchComparatorHelper.layer3MatchEquals(new ArpMatchBuilder().build(), new ArpMatchBuilder().build())); - } - - @Test - public void layer3MatchEqualsIpv6Test() { - final Ipv6MatchBuilder statsBuilder = new Ipv6MatchBuilder(); - final Ipv6MatchBuilder storedBuilder = new Ipv6MatchBuilder(); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(), storedBuilder.build())); - - statsBuilder.setIpv6Destination(new Ipv6Prefix("AABB:1234:2ACF:000D:0000:0000:0000:5D99/64")); - storedBuilder.setIpv6Destination(new Ipv6Prefix("AABB:1234:2ACF:000D:0000:0000:0000:4D99/64")); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(), storedBuilder.build())); - - statsBuilder.setIpv6Destination(new Ipv6Prefix("aabb:1234:2acf:000d:0000:0000:0000:5d99/64")); - storedBuilder.setIpv6Destination(new Ipv6Prefix("AABB:1234:2ACF:000D:0000:0000:0000:4D99/64")); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(), storedBuilder.build())); - - statsBuilder.setIpv6Destination(new Ipv6Prefix("AABB:1234:2ACF:000C:0000:0000:0000:5D99/64")); - storedBuilder.setIpv6Destination(new Ipv6Prefix("AABB:1234:2ACF:000D:0000:0000:0000:4D99/64")); - assertEquals(false, MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(), storedBuilder.build())); - - statsBuilder.setIpv6Destination(new Ipv6Prefix("AABB:1234:2ACF:000C:0000:0000:0000:5D99/63")); - storedBuilder.setIpv6Destination(new Ipv6Prefix("AABB:1234:2ACF:000D:0000:0000:0000:4D99/63")); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(), storedBuilder.build())); - - statsBuilder.setIpv6Destination(new Ipv6Prefix("AABB:1234:2ACF:000D:0000:0000:0000:5D99/63")); - storedBuilder.setIpv6Destination(new Ipv6Prefix("AABB:1234:2ACF:000E:0000:0000:0000:4D99/63")); - assertEquals(false, MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(), storedBuilder.build())); - } - - @Test - public void layer3MatchEqualsIpv4ArbitraryMaskTest(){ - final Ipv4MatchBuilder statsBuilder = new Ipv4MatchBuilder(); - final Ipv4MatchArbitraryBitMaskBuilder storedBuilder = new Ipv4MatchArbitraryBitMaskBuilder(); - assertEquals(true,MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(),storedBuilder.build())); - statsBuilder.setIpv4Destination(new Ipv4Prefix("192.168.1.1/24")); - storedBuilder.setIpv4DestinationAddressNoMask(new Ipv4Address("192.168.1.1")); - storedBuilder.setIpv4DestinationArbitraryBitmask(new DottedQuad("255.255.255.0")); - statsBuilder.setIpv4Source(new Ipv4Prefix("192.168.1.1/24")); - storedBuilder.setIpv4SourceAddressNoMask(new Ipv4Address("192.168.1.1")); - storedBuilder.setIpv4SourceArbitraryBitmask(new DottedQuad("255.255.255.0")); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(), storedBuilder.build())); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(null, null)); - - } - - @Test - public void layer3MatchEqualsIpv4ArbitraryMaskRandomTest() { - final Ipv4MatchArbitraryBitMaskBuilder statsBuilder = new Ipv4MatchArbitraryBitMaskBuilder(); - final Ipv4MatchArbitraryBitMaskBuilder storedBuilder = new Ipv4MatchArbitraryBitMaskBuilder(); - assertEquals(true,MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(),storedBuilder.build())); - statsBuilder.setIpv4DestinationAddressNoMask(new Ipv4Address("192.168.0.1")); - statsBuilder.setIpv4DestinationArbitraryBitmask(new DottedQuad("255.255.0.255")); - storedBuilder.setIpv4DestinationAddressNoMask(new Ipv4Address("192.168.1.1")); - storedBuilder.setIpv4DestinationArbitraryBitmask(new DottedQuad("255.255.0.255")); - statsBuilder.setIpv4SourceAddressNoMask(new Ipv4Address("192.0.0.1")); - statsBuilder.setIpv4SourceArbitraryBitmask(new DottedQuad("255.0.0.255")); - storedBuilder.setIpv4SourceAddressNoMask(new Ipv4Address("192.7.1.1")); - storedBuilder.setIpv4SourceArbitraryBitmask(new DottedQuad("255.0.0.255")); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(), storedBuilder.build())); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(null, null)); - } - - @Test - public void layer3MatchEqualsIpv4ArbitraryMaskEqualsNullTest() { - final Ipv4MatchBuilder statsBuilder = new Ipv4MatchBuilder(); - final Ipv4MatchArbitraryBitMaskBuilder storedBuilder = new Ipv4MatchArbitraryBitMaskBuilder(); - assertEquals(true,MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(),storedBuilder.build())); - statsBuilder.setIpv4Source(new Ipv4Prefix("192.168.0.1/32")); - storedBuilder.setIpv4DestinationAddressNoMask(new Ipv4Address("192.168.0.1")); - statsBuilder.setIpv4Destination(new Ipv4Prefix("192.1.0.0/32")); - storedBuilder.setIpv4SourceAddressNoMask(new Ipv4Address("192.1.0.0")); - assertEquals(false, MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(), storedBuilder.build())); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(null, null)); - } - - @Test - public void layer3MatchEqualsIpv4ArbitraryEmptyBitMaskTest(){ - final Ipv4MatchBuilder statsBuilder = new Ipv4MatchBuilder(); - final Ipv4MatchArbitraryBitMaskBuilder storedBuilder = new Ipv4MatchArbitraryBitMaskBuilder(); - assertEquals(true,MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(),storedBuilder.build())); - statsBuilder.setIpv4Destination(new Ipv4Prefix("192.168.1.1/32")); - storedBuilder.setIpv4DestinationAddressNoMask(new Ipv4Address("192.168.1.1")); - statsBuilder.setIpv4Source(new Ipv4Prefix("192.168.1.1/32")); - storedBuilder.setIpv4SourceAddressNoMask(new Ipv4Address("192.168.1.1")); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(statsBuilder.build(), storedBuilder.build())); - assertEquals(true, MatchComparatorHelper.layer3MatchEquals(null, null)); - } - - @Test - public void extractIpv4AddressTest() { - Ipv4Address ipAddress = new Ipv4Address("1.1.1.1"); - DottedQuad netMask = new DottedQuad("255.255.255.0"); - String extractedIpAddress; - extractedIpAddress = MatchComparatorHelper.normalizeIpv4Address(ipAddress,netMask); - assertEquals(extractedIpAddress,"1.1.1.0"); - } - - @Test - public void convertArbitraryMaskToByteArrayTest() { - int value = 0xffffffff; - byte[] bytes = new byte[]{ - (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff) }; - byte[] maskBytes; - maskBytes = MatchComparatorHelper.convertArbitraryMaskToByteArray(new DottedQuad("255.255.255.255")); - for (int i=0; i nodeII = InstanceIdentifier.create(Nodes.class).child(Node.class, s1Key); - - assertTrue(statisticsManager.isProvidedFlowNodeActive(nodeII)); - } - - @Test - public void nodeUnregistrationTest() throws ExecutionException, InterruptedException { - StatisticsManager statisticsManager = setupStatisticsManager(); - - addFlowCapableNode(s1Key); - Thread.sleep(2000); - final InstanceIdentifier nodeII = InstanceIdentifier.create(Nodes.class).child(Node.class, s1Key); - - assertTrue(statisticsManager.isProvidedFlowNodeActive(nodeII)); - - removeNode(s1Key); - Thread.sleep(2000); - assertFalse(statisticsManager.isProvidedFlowNodeActive(nodeII)); - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/StatCollectorTest.java b/applications/statistics-manager/src/test/java/test/mock/StatCollectorTest.java deleted file mode 100644 index b5808da1db..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/StatCollectorTest.java +++ /dev/null @@ -1,304 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.common.base.Optional; - -import java.util.Collection; -import java.util.concurrent.ExecutionException; -import org.junit.Test; -import org.opendaylight.controller.md.sal.binding.api.*; -import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnectorBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityFlowStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityGroupStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityPortStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityQueueStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowFeatureCapabilityTableStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowStatisticsData; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsData; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.Queue; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.QueueBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupDescStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupStatistics; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.group.features.GroupFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterConfigStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterStatistics; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.nodes.node.MeterFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsData; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.FlowCapableNodeConnectorQueueStatisticsData; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import test.mock.util.StatisticsManagerTest; - -public class StatCollectorTest extends StatisticsManagerTest { - private final Object waitObject = new Object(); - - @Test(timeout = 200000) - public void getAllFlowStatsTest() throws ExecutionException, InterruptedException, ReadFailedException { - setupStatisticsManager(); - - addFlowCapableNodeWithFeatures(s1Key, false, FlowFeatureCapabilityFlowStats.class); - - final Flow flow = getFlow(); - - final InstanceIdentifier
tableII = InstanceIdentifier.create(Nodes.class).child(Node.class, s1Key) - .augmentation(FlowCapableNode.class).child(Table.class, new TableKey(flow.getTableId())); - - getDataBroker().registerDataTreeChangeListener( new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, - tableII.child(Flow.class)), new ChangeListener()); - - synchronized (waitObject) { - waitObject.wait(); - } - - final ReadOnlyTransaction readTx = getDataBroker().newReadOnlyTransaction(); - final Optional
tableOptional = readTx.read(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class) - .child(Node.class, s1Key).augmentation(FlowCapableNode.class) - .child(Table.class, new TableKey(flow.getTableId()))).checkedGet(); - assertTrue(tableOptional.isPresent()); - final FlowStatisticsData flowStats = tableOptional.get().getFlow().get(0).getAugmentation(FlowStatisticsData.class); - assertTrue(flowStats != null); - assertEquals(COUNTER_64_TEST_VALUE, flowStats.getFlowStatistics().getByteCount()); - } - - @Test(timeout = 200000) - public void getAllGroupStatsFeatureNotAdvertisedTest() throws ExecutionException, InterruptedException { - setupStatisticsManager(); - - addFlowCapableNodeWithFeatures(s1Key, true); - - final InstanceIdentifier groupII = InstanceIdentifier.create(Nodes.class).child(Node.class, s1Key) - .augmentation(FlowCapableNode.class).child(Group.class, getGroup().getKey()); - getDataBroker().registerDataTreeChangeListener( new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, - groupII.augmentation(NodeGroupStatistics.class)), new ChangeListener()); - - synchronized (waitObject) { - waitObject.wait(); - } - - ReadOnlyTransaction readTx = getDataBroker().newReadOnlyTransaction(); - final Optional optionalGroup = readTx.read(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class) - .child(Node.class, s1Key).augmentation(FlowCapableNode.class) - .child(Group.class, getGroup().getKey())).get(); - - assertTrue(optionalGroup.isPresent()); - assertTrue(optionalGroup.get().getAugmentation(NodeGroupDescStats.class) != null); - final NodeGroupStatistics groupStats = optionalGroup.get().getAugmentation(NodeGroupStatistics.class); - assertTrue(groupStats != null); - assertEquals(COUNTER_64_TEST_VALUE, groupStats.getGroupStatistics().getByteCount()); - - readTx = getDataBroker().newReadOnlyTransaction(); - final Optional optionalGroupFeatures = readTx.read(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class) - .child(Node.class, s1Key).augmentation(NodeGroupFeatures.class).child(GroupFeatures.class)).get(); - assertTrue(optionalGroupFeatures.isPresent()); - assertEquals(1, optionalGroupFeatures.get().getMaxGroups().size()); - assertEquals(MAX_GROUPS_TEST_VALUE, optionalGroupFeatures.get().getMaxGroups().get(0)); - } - - @Test(timeout = 200000) - public void getAllGroupStatsFeatureAdvertisedTest() throws ExecutionException, InterruptedException { - setupStatisticsManager(); - - addFlowCapableNodeWithFeatures(s1Key, false, FlowFeatureCapabilityGroupStats.class); - - final InstanceIdentifier groupII = InstanceIdentifier.create(Nodes.class).child(Node.class, s1Key) - .augmentation(FlowCapableNode.class).child(Group.class, getGroup().getKey()); - getDataBroker().registerDataTreeChangeListener( new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, - groupII.augmentation(NodeGroupStatistics.class)), new ChangeListener()); - - synchronized (waitObject) { - waitObject.wait(); - } - - ReadOnlyTransaction readTx = getDataBroker().newReadOnlyTransaction(); - final Optional optionalGroup = readTx.read(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class) - .child(Node.class, s1Key).augmentation(FlowCapableNode.class) - .child(Group.class, getGroup().getKey())).get(); - - assertTrue(optionalGroup.isPresent()); - assertTrue(optionalGroup.get().getAugmentation(NodeGroupDescStats.class) != null); - final NodeGroupStatistics groupStats = optionalGroup.get().getAugmentation(NodeGroupStatistics.class); - assertTrue(groupStats != null); - assertEquals(COUNTER_64_TEST_VALUE, groupStats.getGroupStatistics().getByteCount()); - - readTx = getDataBroker().newReadOnlyTransaction(); - final Optional optionalGroupFeatures = readTx.read(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class) - .child(Node.class, s1Key).augmentation(NodeGroupFeatures.class).child(GroupFeatures.class)).get(); - assertTrue(optionalGroupFeatures.isPresent()); - assertEquals(1, optionalGroupFeatures.get().getMaxGroups().size()); - assertEquals(MAX_GROUPS_TEST_VALUE, optionalGroupFeatures.get().getMaxGroups().get(0)); - } - - @Test(timeout = 200000) - public void getAllMeterStatsTest() throws ExecutionException, InterruptedException { - setupStatisticsManager(); - - addFlowCapableNodeWithFeatures(s1Key, true); - - final InstanceIdentifier meterII = InstanceIdentifier.create(Nodes.class).child(Node.class, s1Key) - .augmentation(FlowCapableNode.class).child(Meter.class, getMeter().getKey()); - getDataBroker().registerDataTreeChangeListener( new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, - meterII.augmentation(NodeMeterStatistics.class)), new ChangeListener()); - - synchronized (waitObject) { - waitObject.wait(); - } - - ReadOnlyTransaction readTx = getDataBroker().newReadOnlyTransaction(); - final Optional optionalMeter = readTx.read(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class) - .child(Node.class, s1Key).augmentation(FlowCapableNode.class) - .child(Meter.class, getMeter().getKey())).get(); - - assertTrue(optionalMeter.isPresent()); - assertTrue(optionalMeter.get().getAugmentation(NodeMeterConfigStats.class) != null); - final NodeMeterStatistics meterStats = optionalMeter.get().getAugmentation(NodeMeterStatistics.class); - assertTrue(meterStats != null); - assertEquals(COUNTER_64_TEST_VALUE, meterStats.getMeterStatistics().getByteInCount()); - assertEquals(COUNTER_64_TEST_VALUE, meterStats.getMeterStatistics().getPacketInCount()); - - readTx = getDataBroker().newReadOnlyTransaction(); - final Optional optionalMeterFeautures = readTx.read(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class) - .child(Node.class, s1Key).augmentation(NodeMeterFeatures.class).child(MeterFeatures.class)).get(); - assertTrue(optionalMeterFeautures.isPresent()); - assertEquals(COUNTER_32_TEST_VALUE, optionalMeterFeautures.get().getMaxMeter()); - } - - @Test(timeout = 200000) - public void getAllQueueStatsTest() throws ExecutionException, InterruptedException, ReadFailedException { - setupStatisticsManager(); - - addFlowCapableNodeWithFeatures(s1Key, false, FlowFeatureCapabilityQueueStats.class); - - final NodeConnectorBuilder ncBuilder = new NodeConnectorBuilder(); - final FlowCapableNodeConnectorBuilder fcncBuilder = new FlowCapableNodeConnectorBuilder(); - ncBuilder.setKey(new NodeConnectorKey(getNodeConnectorId())); - ncBuilder.addAugmentation(FlowCapableNodeConnector.class, fcncBuilder.build()); - - final InstanceIdentifier nodeConnectorII = InstanceIdentifier.create(Nodes.class) - .child(Node.class, s1Key) - .child(NodeConnector.class, ncBuilder.getKey()); - - final WriteTransaction writeTx = getDataBroker().newWriteOnlyTransaction(); - writeTx.put(LogicalDatastoreType.OPERATIONAL, nodeConnectorII, ncBuilder.build()); - final InstanceIdentifier queueII = nodeConnectorII.augmentation(FlowCapableNodeConnector.class) - .child(Queue.class, getQueue().getKey()); - final QueueBuilder qBuilder = new QueueBuilder(getQueue()); - writeTx.put(LogicalDatastoreType.OPERATIONAL, queueII, qBuilder.build()); - assertCommit(writeTx.submit()); - - getDataBroker().registerDataTreeChangeListener( new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, - queueII.augmentation(FlowCapableNodeConnectorQueueStatisticsData.class)), new ChangeListener()); - - synchronized (waitObject) { - waitObject.wait(); - } - - final ReadOnlyTransaction readTx = getDataBroker().newReadOnlyTransaction(); - final Optional queueOptional = readTx.read(LogicalDatastoreType.OPERATIONAL, queueII).checkedGet(); - assertTrue(queueOptional.isPresent()); - final FlowCapableNodeConnectorQueueStatisticsData queueStats = - queueOptional.get().getAugmentation(FlowCapableNodeConnectorQueueStatisticsData.class); - assertTrue(queueStats != null); - assertEquals(COUNTER_64_TEST_VALUE, - queueStats.getFlowCapableNodeConnectorQueueStatistics().getTransmittedBytes()); - } - - @Test(timeout = 200000) - public void getAllPortStatsTest() throws ExecutionException, InterruptedException, ReadFailedException { - setupStatisticsManager(); - - addFlowCapableNodeWithFeatures(s1Key, false, FlowFeatureCapabilityPortStats.class); - - final InstanceIdentifier nodeConnectorII = InstanceIdentifier.create(Nodes.class) - .child(Node.class, s1Key).child(NodeConnector.class, new NodeConnectorKey(getNodeConnectorId())); - - NodeConnectorBuilder ncBuilder = new NodeConnectorBuilder(); - ncBuilder.setKey(new NodeConnectorKey(getNodeConnectorId())); - WriteTransaction writeTx = getDataBroker().newWriteOnlyTransaction(); - writeTx.put(LogicalDatastoreType.OPERATIONAL, nodeConnectorII, ncBuilder.build()); - assertCommit(writeTx.submit()); - - getDataBroker().registerDataTreeChangeListener(new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, - nodeConnectorII.augmentation(FlowCapableNodeConnectorStatisticsData.class)), new ChangeListener()); - - synchronized (waitObject) { - waitObject.wait(); - } - - final ReadOnlyTransaction readTx = getDataBroker().newReadOnlyTransaction(); - final Optional flowCapableNodeConnectorStatisticsDataOptional = - readTx.read(LogicalDatastoreType.OPERATIONAL, - nodeConnectorII.augmentation(FlowCapableNodeConnectorStatisticsData.class)).checkedGet(); - assertTrue(flowCapableNodeConnectorStatisticsDataOptional.isPresent()); - assertEquals(BIG_INTEGER_TEST_VALUE, - flowCapableNodeConnectorStatisticsDataOptional.get().getFlowCapableNodeConnectorStatistics() - .getReceiveDrops()); - assertEquals(BIG_INTEGER_TEST_VALUE, - flowCapableNodeConnectorStatisticsDataOptional.get().getFlowCapableNodeConnectorStatistics() - .getCollisionCount()); - } - - @Test(timeout = 200000) - public void getAllTableStatsTest() throws ExecutionException, InterruptedException, ReadFailedException { - setupStatisticsManager(); - - addFlowCapableNodeWithFeatures(s1Key, false, FlowFeatureCapabilityTableStats.class); - - final TableId tableId = getTableId(); - final InstanceIdentifier
tableII = InstanceIdentifier.create(Nodes.class).child(Node.class, s1Key) - .augmentation(FlowCapableNode.class).child(Table.class, new TableKey(tableId.getValue())); - - getDataBroker().registerDataTreeChangeListener( new DataTreeIdentifier<>(LogicalDatastoreType.OPERATIONAL, - tableII.augmentation(FlowTableStatisticsData.class)), new ChangeListener()); - - synchronized (waitObject) { - waitObject.wait(); - } - - final ReadOnlyTransaction readTx = getDataBroker().newReadOnlyTransaction(); - final Optional flowTableStatisticsDataOptional = readTx.read( - LogicalDatastoreType.OPERATIONAL, tableII.augmentation(FlowTableStatisticsData.class)).checkedGet(); - assertTrue(flowTableStatisticsDataOptional.isPresent()); - assertEquals(COUNTER_32_TEST_VALUE, - flowTableStatisticsDataOptional.get().getFlowTableStatistics().getActiveFlows()); - assertEquals(COUNTER_64_TEST_VALUE, - flowTableStatisticsDataOptional.get().getFlowTableStatistics().getPacketsLookedUp()); - } - - public class ChangeListener implements DataTreeChangeListener { - - @Override - public void onDataTreeChanged(final Collection> changes){ - synchronized (waitObject) { - waitObject.notify(); - } - } - - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/BundleContextMock.java b/applications/statistics-manager/src/test/java/test/mock/util/BundleContextMock.java deleted file mode 100644 index 431b5da94f..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/BundleContextMock.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; -import org.osgi.framework.BundleListener; -import org.osgi.framework.Filter; -import org.osgi.framework.FrameworkListener; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.framework.ServiceListener; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.ServiceRegistration; - -import java.io.File; -import java.io.InputStream; -import java.util.Collection; -import java.util.Dictionary; - -public class BundleContextMock implements BundleContext { - @Override - public String getProperty(String s) { - return null; - } - - @Override - public Bundle getBundle() { - return null; - } - - @Override - public Bundle installBundle(String s, InputStream inputStream) throws BundleException { - return null; - } - - @Override - public Bundle installBundle(String s) throws BundleException { - return null; - } - - @Override - public Bundle getBundle(long l) { - return null; - } - - @Override - public Bundle[] getBundles() { - return new Bundle[0]; - } - - @Override - public void addServiceListener(ServiceListener serviceListener, String s) throws InvalidSyntaxException { - - } - - @Override - public void addServiceListener(ServiceListener serviceListener) { - - } - - @Override - public void removeServiceListener(ServiceListener serviceListener) { - - } - - @Override - public void addBundleListener(BundleListener bundleListener) { - - } - - @Override - public void removeBundleListener(BundleListener bundleListener) { - - } - - @Override - public void addFrameworkListener(FrameworkListener frameworkListener) { - - } - - @Override - public void removeFrameworkListener(FrameworkListener frameworkListener) { - - } - - @Override - public ServiceRegistration registerService(String[] strings, Object o, Dictionary stringDictionary) { - return null; - } - - @Override - public ServiceRegistration registerService(String s, Object o, Dictionary stringDictionary) { - return null; - } - - @Override - public ServiceRegistration registerService(Class sClass, S s, Dictionary stringDictionary) { - return null; - } - - @Override - public ServiceReference[] getServiceReferences(String s, String s2) throws InvalidSyntaxException { - return new ServiceReference[0]; - } - - @Override - public ServiceReference[] getAllServiceReferences(String s, String s2) throws InvalidSyntaxException { - return new ServiceReference[0]; - } - - @Override - public ServiceReference getServiceReference(String s) { - return null; - } - - @Override - public ServiceReference getServiceReference(Class sClass) { - return null; - } - - @Override - public Collection> getServiceReferences(Class sClass, String s) throws InvalidSyntaxException { - return null; - } - - @Override - public S getService(ServiceReference sServiceReference) { - return null; - } - - @Override - public boolean ungetService(ServiceReference serviceReference) { - return false; - } - - @Override - public File getDataFile(String s) { - return null; - } - - @Override - public Filter createFilter(String s) throws InvalidSyntaxException { - return null; - } - - @Override - public Bundle getBundle(String s) { - return null; - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/EntityOwnershipServiceMock.java b/applications/statistics-manager/src/test/java/test/mock/util/EntityOwnershipServiceMock.java deleted file mode 100644 index 7dac2fb762..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/EntityOwnershipServiceMock.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import com.google.common.base.Optional; -import org.opendaylight.controller.md.sal.common.api.clustering.*; - -import javax.annotation.Nonnull; - -/** - * Created by vishnoianil on 1/13/16. - */ -public class EntityOwnershipServiceMock implements EntityOwnershipService { - @Override - public EntityOwnershipCandidateRegistration registerCandidate(@Nonnull Entity entity) throws CandidateAlreadyRegisteredException { - return null; - } - - @Override - public EntityOwnershipListenerRegistration registerListener(@Nonnull String entityType, @Nonnull EntityOwnershipListener listener) { - return null; - } - - @Override - public Optional getOwnershipState(@Nonnull Entity forEntity) { - return Optional.of(new EntityOwnershipState(true,true)); - } - - @Override - public boolean isCandidateRegistered(@Nonnull Entity entity) { - return true; - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/FlowMockGenerator.java b/applications/statistics-manager/src/test/java/test/mock/util/FlowMockGenerator.java deleted file mode 100644 index 01a1738d09..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/FlowMockGenerator.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie; - -import java.math.BigInteger; -import java.util.Random; - -public class FlowMockGenerator { - private static final Random rnd = new Random(); - private static final FlowBuilder flowBuilder = new FlowBuilder(); - - public static Flow getRandomFlow() { - flowBuilder.setKey(new FlowKey(new FlowId("flow." + rnd.nextInt(1000)))); - flowBuilder.setOutGroup(TestUtils.nextLong(0, 4294967296L)); - flowBuilder.setTableId((short) rnd.nextInt(256)); - flowBuilder.setOutPort(BigInteger.valueOf(TestUtils.nextLong(0, Long.MAX_VALUE))); - flowBuilder.setStrict(rnd.nextBoolean()); - flowBuilder.setContainerName("container." + rnd.nextInt(1000)); - flowBuilder.setBarrier(rnd.nextBoolean()); - flowBuilder.setMatch(MatchMockGenerator.getRandomMatch()); - flowBuilder.setPriority(rnd.nextInt(65535)); - flowBuilder.setCookie(new FlowCookie(BigInteger.valueOf(TestUtils.nextLong(0, Long.MAX_VALUE)))); - flowBuilder.setCookieMask(flowBuilder.getCookie()); - return flowBuilder.build(); - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/GroupMockGenerator.java b/applications/statistics-manager/src/test/java/test/mock/util/GroupMockGenerator.java deleted file mode 100644 index 661675b166..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/GroupMockGenerator.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey; - -import java.util.Random; - -public class GroupMockGenerator { - private static final Random rnd = new Random(); - private static final GroupBuilder groupBuilder = new GroupBuilder(); - - public static Group getRandomGroup() { - groupBuilder.setKey(new GroupKey(new GroupId(TestUtils.nextLong(0, 4294967295L)))); - groupBuilder.setContainerName("container." + rnd.nextInt(1000)); - groupBuilder.setBarrier(rnd.nextBoolean()); - groupBuilder.setGroupName("group." + rnd.nextInt(1000)); - groupBuilder.setGroupType(GroupTypes.forValue(rnd.nextInt(4))); - return groupBuilder.build(); - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/MatchMockGenerator.java b/applications/statistics-manager/src/test/java/test/mock/util/MatchMockGenerator.java deleted file mode 100644 index bdbeb2a1df..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/MatchMockGenerator.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Dscp; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.IpMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.MetadataBuilder; - -import java.math.BigInteger; -import java.util.Random; - -public class MatchMockGenerator { - private static final Random rnd = new Random(); - private static final MatchBuilder matchBuilder = new MatchBuilder(); - private static final IpMatchBuilder ipMatchBuilder = new IpMatchBuilder(); - private static final MetadataBuilder metadataBuilder = new MetadataBuilder(); - - public static Match getRandomMatch() { - matchBuilder.setInPort(new NodeConnectorId("port." + rnd.nextInt(500))); - ipMatchBuilder.setIpDscp(new Dscp((short) rnd.nextInt(64))).build(); - ipMatchBuilder.setIpEcn((short) rnd.nextInt(256)); - ipMatchBuilder.setIpProtocol((short) rnd.nextInt(256)); - matchBuilder.setIpMatch(ipMatchBuilder.build()); - metadataBuilder.setMetadata(BigInteger.valueOf(TestUtils.nextLong(0, Long.MAX_VALUE))); - metadataBuilder.setMetadataMask(BigInteger.valueOf(TestUtils.nextLong(0, Long.MAX_VALUE))); - matchBuilder.setMetadata(metadataBuilder.build()); - return matchBuilder.build(); - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/MeterMockGenerator.java b/applications/statistics-manager/src/test/java/test/mock/util/MeterMockGenerator.java deleted file mode 100644 index dbec4c7dda..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/MeterMockGenerator.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.BandId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.MeterBandHeadersBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.meter.band.headers.MeterBandHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.meter.band.headers.MeterBandHeaderBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.meter.band.headers.MeterBandHeaderKey; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -public class MeterMockGenerator { - private static final Random rnd = new Random(); - private static final MeterBuilder meterBuilder = new MeterBuilder(); - private static final MeterBandHeaderBuilder meterBandHeaderBuilder = new MeterBandHeaderBuilder(); - private static final MeterBandHeadersBuilder meterBandHeadersBuilder = new MeterBandHeadersBuilder(); - - public static Meter getRandomMeter() { - meterBandHeaderBuilder.setKey(new MeterBandHeaderKey(new BandId(TestUtils.nextLong(0, 4294967295L)))); - meterBandHeaderBuilder.setBandBurstSize(TestUtils.nextLong(0, 4294967295L)); - meterBandHeaderBuilder.setBandRate(TestUtils.nextLong(0, 4294967295L)); - List meterBandHeaders = new ArrayList<>(); - meterBuilder.setKey(new MeterKey(new MeterId(TestUtils.nextLong(0, 4294967295L)))); - meterBuilder.setBarrier(rnd.nextBoolean()); - meterBuilder.setContainerName("container." + rnd.nextInt(1000)); - meterBuilder.setMeterName("meter." + rnd.nextInt(1000)); - meterBuilder.setMeterBandHeaders(meterBandHeadersBuilder.setMeterBandHeader(meterBandHeaders).build()); - return meterBuilder.build(); - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/NotificationProviderServiceHelper.java b/applications/statistics-manager/src/test/java/test/mock/util/NotificationProviderServiceHelper.java deleted file mode 100644 index cfc8babc4b..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/NotificationProviderServiceHelper.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import com.google.common.collect.LinkedHashMultimap; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Set; -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.ExecutorService; -import org.opendaylight.controller.sal.binding.api.NotificationListener; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.binding.Notification; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NotificationProviderServiceHelper { - - private static final Logger LOG = LoggerFactory.getLogger(NotificationProviderServiceHelper.class); - - private NotificationProviderService notifBroker = new NotificationProviderServiceDummyImpl(); - - public NotificationProviderService getNotifBroker() { - return notifBroker; - } - - public void pushDelayedNotification(final Notification notification, int delay) { - new Timer().schedule(new TimerTask() { - @Override - public void run() { - notifBroker.publish(notification); - } - }, delay); - } - - public void pushNotification(final Notification notification) { - notifBroker.publish(notification); - } - - private static class NotificationListenerExecTuple { - Method m; - org.opendaylight.yangtools.yang.binding.NotificationListener listenerInst; - - void propagateNotification(Notification notification) { - try { - m.invoke(listenerInst, notification); - } catch (IllegalAccessException | InvocationTargetException e) { - LOG.error("Exception occurred: {} ", e.getMessage(), e); - } - } - - @Override - public int hashCode() { - return listenerInst.hashCode(); - } - - @Override - public boolean equals(Object obj) { - return listenerInst.equals(obj); - } - - } - - private static class NotificationProviderServiceDummyImpl implements NotificationProviderService { - private LinkedHashMultimap listenerRegistry = LinkedHashMultimap.create(); - - @Override - - public void publish(Notification notification) { - Set execPack = listenerRegistry.get(notification.getImplementedInterface()); - for (NotificationListenerExecTuple notificationListenerExecTuple : execPack) { - notificationListenerExecTuple.propagateNotification(notification); - } - } - - @Override - public void publish(Notification notification, ExecutorService executorService) { - throw new IllegalAccessError("publish with executorService not supported"); - } - - @Override - public ListenerRegistration registerInterestListener(NotificationInterestListener notificationInterestListener) { - throw new IllegalAccessError("registering of interest listener not supported"); - } - - @Override - public ListenerRegistration> registerNotificationListener(Class aClass, NotificationListener notificationListener) { - throw new IllegalAccessError("registering with class not supported"); - } - - @Override - public ListenerRegistration registerNotificationListener(org.opendaylight.yangtools.yang.binding.NotificationListener notificationListener) { - for (Method m : notificationListener.getClass().getMethods()) { - if (m.getName().startsWith("on") && m.getParameterTypes().length == 1) { - Class key = m.getParameterTypes()[0]; - Set listeners = listenerRegistry.get(key); - NotificationListenerExecTuple execPack = new NotificationListenerExecTuple(); - execPack.listenerInst = notificationListener; - execPack.m = m; - listeners.add(execPack); - } - } - return null; - } - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightFlowStatisticsServiceMock.java b/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightFlowStatisticsServiceMock.java deleted file mode 100644 index 7c626e508c..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightFlowStatisticsServiceMock.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Future; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.AggregateFlowStatisticsUpdateBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowsStatisticsUpdateBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.OpendaylightFlowStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.flow.and.statistics.map.list.FlowAndStatisticsMapList; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.flow.and.statistics.map.list.FlowAndStatisticsMapListBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; - -import com.google.common.util.concurrent.Futures; - -public class OpendaylightFlowStatisticsServiceMock implements OpendaylightFlowStatisticsService { - NotificationProviderServiceHelper notifService; - - public OpendaylightFlowStatisticsServiceMock(NotificationProviderServiceHelper notifService) { - this.notifService = notifService; - } - - @Override - public Future> getAggregateFlowStatisticsFromFlowTableForAllFlows(GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput input) { - GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder builder = new GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getAggregateFlowStatisticsFromFlowTableForGivenMatch(GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput input) { - GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder builder = new GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - AggregateFlowStatisticsUpdateBuilder afsuBuilder = new AggregateFlowStatisticsUpdateBuilder(); - afsuBuilder.setMoreReplies(false); - afsuBuilder.setTransactionId(transId); - afsuBuilder.setByteCount(StatisticsManagerTest.COUNTER_64_TEST_VALUE); - afsuBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - notifService.pushDelayedNotification(afsuBuilder.build(), 100); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getAllFlowStatisticsFromFlowTable(GetAllFlowStatisticsFromFlowTableInput input) { - GetAllFlowStatisticsFromFlowTableOutputBuilder builder = new GetAllFlowStatisticsFromFlowTableOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getAllFlowsStatisticsFromAllFlowTables(GetAllFlowsStatisticsFromAllFlowTablesInput input) { - GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder builder = new GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - List flowAndStatisticsMapLists = new ArrayList<>(); - FlowsStatisticsUpdateBuilder flowsStatisticsUpdateBuilder = new FlowsStatisticsUpdateBuilder(); - flowsStatisticsUpdateBuilder.setTransactionId(transId); - flowsStatisticsUpdateBuilder.setMoreReplies(false); - flowsStatisticsUpdateBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - FlowAndStatisticsMapListBuilder flowAndStatisticsMapListBuilder = new FlowAndStatisticsMapListBuilder(StatisticsManagerTest.getFlow()); - flowAndStatisticsMapListBuilder.setTableId(StatisticsManagerTest.getFlow().getTableId()); - flowAndStatisticsMapListBuilder.setContainerName(StatisticsManagerTest.getFlow().getContainerName()); - flowAndStatisticsMapListBuilder.setBarrier(StatisticsManagerTest.getFlow().isBarrier()); - flowAndStatisticsMapListBuilder.setByteCount(StatisticsManagerTest.COUNTER_64_TEST_VALUE); - flowAndStatisticsMapLists.add(flowAndStatisticsMapListBuilder.build()); - flowsStatisticsUpdateBuilder.setFlowAndStatisticsMapList(flowAndStatisticsMapLists); - notifService.pushDelayedNotification(flowsStatisticsUpdateBuilder.build(), 100); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getFlowStatisticsFromFlowTable(GetFlowStatisticsFromFlowTableInput input) { - GetFlowStatisticsFromFlowTableOutputBuilder builder = new GetFlowStatisticsFromFlowTableOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - List flowAndStatisticsMapLists = new ArrayList<>(); - FlowsStatisticsUpdateBuilder flowsStatisticsUpdateBuilder = new FlowsStatisticsUpdateBuilder(); - flowsStatisticsUpdateBuilder.setTransactionId(transId); - flowsStatisticsUpdateBuilder.setMoreReplies(false); - flowsStatisticsUpdateBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - FlowAndStatisticsMapListBuilder flowAndStatisticsMapListBuilder = new FlowAndStatisticsMapListBuilder(input); - flowAndStatisticsMapListBuilder.setTableId(input.getTableId()); - flowAndStatisticsMapListBuilder.setContainerName(input.getContainerName()); - flowAndStatisticsMapListBuilder.setBarrier(input.isBarrier()); - flowAndStatisticsMapListBuilder.setByteCount(StatisticsManagerTest.COUNTER_64_TEST_VALUE); - flowAndStatisticsMapLists.add(flowAndStatisticsMapListBuilder.build()); - flowsStatisticsUpdateBuilder.setFlowAndStatisticsMapList(flowAndStatisticsMapLists); - notifService.pushDelayedNotification(flowsStatisticsUpdateBuilder.build(), 100); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightFlowTableStatisticsServiceMock.java b/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightFlowTableStatisticsServiceMock.java deleted file mode 100644 index ff617c3524..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightFlowTableStatisticsServiceMock.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Future; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsUpdateBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.GetFlowTablesStatisticsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.GetFlowTablesStatisticsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.GetFlowTablesStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.OpendaylightFlowTableStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.and.statistics.map.FlowTableAndStatisticsMap; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.and.statistics.map.FlowTableAndStatisticsMapBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.flow.table.and.statistics.map.FlowTableAndStatisticsMapKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; - -import com.google.common.util.concurrent.Futures; - -public class OpendaylightFlowTableStatisticsServiceMock implements OpendaylightFlowTableStatisticsService { - NotificationProviderServiceHelper notifService; - - public OpendaylightFlowTableStatisticsServiceMock(NotificationProviderServiceHelper notifService) { - this.notifService = notifService; - } - - @Override - public Future> getFlowTablesStatistics(GetFlowTablesStatisticsInput input) { - GetFlowTablesStatisticsOutputBuilder builder = new GetFlowTablesStatisticsOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - FlowTableStatisticsUpdateBuilder ftsBuilder = new FlowTableStatisticsUpdateBuilder(); - FlowTableAndStatisticsMapBuilder ftasmBuilder = new FlowTableAndStatisticsMapBuilder(); - List tableAndStatisticsMaps = new ArrayList<>(); - ftasmBuilder.setKey(new FlowTableAndStatisticsMapKey(StatisticsManagerTest.getTableId())); - ftasmBuilder.setActiveFlows(StatisticsManagerTest.COUNTER_32_TEST_VALUE); - tableAndStatisticsMaps.add(ftasmBuilder.build()); - ftsBuilder.setTransactionId(transId); - ftsBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - ftsBuilder.setFlowTableAndStatisticsMap(tableAndStatisticsMaps); - ftsBuilder.setMoreReplies(true); - notifService.pushDelayedNotification(ftsBuilder.build(), 0); // 1st notification - ftsBuilder.setMoreReplies(false); - ftasmBuilder.setPacketsLookedUp(StatisticsManagerTest.COUNTER_64_TEST_VALUE); - tableAndStatisticsMaps.clear(); - tableAndStatisticsMaps.add(ftasmBuilder.build()); - ftsBuilder.setFlowTableAndStatisticsMap(tableAndStatisticsMaps); - notifService.pushDelayedNotification(ftsBuilder.build(), 0); // 2nd notification - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightGroupStatisticsServiceMock.java b/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightGroupStatisticsServiceMock.java deleted file mode 100644 index 0683335077..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightGroupStatisticsServiceMock.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Future; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupDescStatsUpdatedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupFeaturesUpdatedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupStatisticsUpdatedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.OpendaylightGroupStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.desc.stats.reply.GroupDescStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.desc.stats.reply.GroupDescStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.desc.stats.reply.GroupDescStatsKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.statistics.reply.GroupStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.statistics.reply.GroupStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.statistics.reply.GroupStatsKey; -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.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; - -import com.google.common.util.concurrent.Futures; - -public class OpendaylightGroupStatisticsServiceMock implements OpendaylightGroupStatisticsService { - NotificationProviderServiceHelper notifService; - - public OpendaylightGroupStatisticsServiceMock(NotificationProviderServiceHelper notifService) { - this.notifService = notifService; - } - - @Override - public Future> getAllGroupStatistics(GetAllGroupStatisticsInput input) { - GetAllGroupStatisticsOutputBuilder builder = new GetAllGroupStatisticsOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - List groupStats = new ArrayList<>(); - GroupStatsBuilder gsBuilder = new GroupStatsBuilder(); - GroupStatisticsUpdatedBuilder gsuBuilder = new GroupStatisticsUpdatedBuilder(); - gsBuilder.setKey(new GroupStatsKey(StatisticsManagerTest.getGroup().getGroupId())); - gsBuilder.setByteCount(StatisticsManagerTest.COUNTER_64_TEST_VALUE); - groupStats.add(gsBuilder.build()); - builder.setGroupStats(groupStats); - gsuBuilder.setTransactionId(transId); - gsuBuilder.setMoreReplies(false); - gsuBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - gsuBuilder.setGroupStats(groupStats); - notifService.pushDelayedNotification(gsuBuilder.build(), 500); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getGroupDescription(GetGroupDescriptionInput input) { - GetGroupDescriptionOutputBuilder builder = new GetGroupDescriptionOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - List groupDescStats = new ArrayList<>(); - GroupDescStatsUpdatedBuilder gdsuBuilder = new GroupDescStatsUpdatedBuilder(); - GroupDescStatsBuilder gdsBuilder = new GroupDescStatsBuilder(); - gdsBuilder.setKey(new GroupDescStatsKey(StatisticsManagerTest.getGroup().getGroupId())); - gdsBuilder.setBuckets(StatisticsManagerTest.getGroup().getBuckets()); - gdsBuilder.setContainerName(StatisticsManagerTest.getGroup().getContainerName()); - gdsBuilder.setGroupName(StatisticsManagerTest.getGroup().getGroupName()); - gdsBuilder.setGroupType(StatisticsManagerTest.getGroup().getGroupType()); - groupDescStats.add(gdsBuilder.build()); - builder.setGroupDescStats(groupDescStats); - gdsuBuilder.setTransactionId(transId); - gdsuBuilder.setMoreReplies(false); - gdsuBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - gdsuBuilder.setGroupDescStats(groupDescStats); - notifService.pushDelayedNotification(gdsuBuilder.build(), 100); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getGroupFeatures(GetGroupFeaturesInput input) { - GetGroupFeaturesOutputBuilder builder = new GetGroupFeaturesOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - GroupFeaturesUpdatedBuilder gfuBuilder = new GroupFeaturesUpdatedBuilder(); - gfuBuilder.setTransactionId(transId); - gfuBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - gfuBuilder.setMoreReplies(false); - List maxGroups = new ArrayList<>(); - maxGroups.add(StatisticsManagerTest.MAX_GROUPS_TEST_VALUE); - gfuBuilder.setMaxGroups(maxGroups); - notifService.pushDelayedNotification(gfuBuilder.build(), 100); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getGroupStatistics(GetGroupStatisticsInput input) { - GetGroupStatisticsOutputBuilder builder = new GetGroupStatisticsOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - GroupStatsBuilder gsBuilder = new GroupStatsBuilder(); - List groupStats = new ArrayList<>(); - gsBuilder.setKey(new GroupStatsKey(input.getGroupId())); - gsBuilder.setByteCount(StatisticsManagerTest.COUNTER_64_TEST_VALUE); - groupStats.add(gsBuilder.build()); - GroupStatisticsUpdatedBuilder gsuBuilder = new GroupStatisticsUpdatedBuilder(); - gsuBuilder.setTransactionId(transId); - gsuBuilder.setMoreReplies(false); - gsuBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - gsuBuilder.setGroupStats(groupStats); - notifService.pushDelayedNotification(gsuBuilder.build(), 100); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightMeterStatisticsServiceMock.java b/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightMeterStatisticsServiceMock.java deleted file mode 100644 index 181b0c5001..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightMeterStatisticsServiceMock.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Future; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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.meter.statistics.rev131111.GetAllMeterConfigStatisticsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterConfigStatisticsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterConfigStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterConfigStatsUpdatedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterFeaturesUpdatedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterStatisticsUpdatedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.OpendaylightMeterStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.config.stats.reply.MeterConfigStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.config.stats.reply.MeterConfigStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.statistics.reply.MeterStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.statistics.reply.MeterStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.statistics.reply.MeterStatsKey; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; - -import com.google.common.util.concurrent.Futures; - -public class OpendaylightMeterStatisticsServiceMock implements OpendaylightMeterStatisticsService { - NotificationProviderServiceHelper notifService; - - public OpendaylightMeterStatisticsServiceMock(NotificationProviderServiceHelper notifService) { - this.notifService = notifService; - } - - @Override - public Future> getAllMeterConfigStatistics(GetAllMeterConfigStatisticsInput input) { - GetAllMeterConfigStatisticsOutputBuilder builder = new GetAllMeterConfigStatisticsOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - List meterConfigStats = new ArrayList<>(); - MeterConfigStatsBuilder mcsBuilder = new MeterConfigStatsBuilder(); - mcsBuilder.setMeterId(StatisticsManagerTest.getMeter().getMeterId()); - mcsBuilder.setMeterName(StatisticsManagerTest.getMeter().getMeterName()); - mcsBuilder.setContainerName(StatisticsManagerTest.getMeter().getContainerName()); - meterConfigStats.add(mcsBuilder.build()); - builder.setMeterConfigStats(meterConfigStats); - MeterConfigStatsUpdatedBuilder mscuBuilder = new MeterConfigStatsUpdatedBuilder(); - mscuBuilder.setTransactionId(transId); - mscuBuilder.setMoreReplies(false); - mscuBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - mscuBuilder.setMeterConfigStats(meterConfigStats); - notifService.pushDelayedNotification(mscuBuilder.build(), 100); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getAllMeterStatistics(GetAllMeterStatisticsInput input) { - GetAllMeterStatisticsOutputBuilder builder = new GetAllMeterStatisticsOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - MeterStatsBuilder msBuilder = new MeterStatsBuilder(); - msBuilder.setByteInCount(StatisticsManagerTest.COUNTER_64_TEST_VALUE); - msBuilder.setPacketInCount(StatisticsManagerTest.COUNTER_64_TEST_VALUE); - msBuilder.setKey(new MeterStatsKey(StatisticsManagerTest.getMeter().getMeterId())); - List meterStats = new ArrayList<>(); - meterStats.add(msBuilder.build()); - MeterStatisticsUpdatedBuilder msuBuilder = new MeterStatisticsUpdatedBuilder(); - msuBuilder.setTransactionId(transId); - msuBuilder.setMoreReplies(false); - msuBuilder.setMeterStats(meterStats); - msuBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - notifService.pushDelayedNotification(msuBuilder.build(), 100); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getMeterFeatures(GetMeterFeaturesInput input) { - GetMeterFeaturesOutputBuilder builder = new GetMeterFeaturesOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - MeterFeaturesUpdatedBuilder mfuBuilder = new MeterFeaturesUpdatedBuilder(); - mfuBuilder.setTransactionId(transId); - mfuBuilder.setMoreReplies(false); - mfuBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - mfuBuilder.setMaxMeter(StatisticsManagerTest.COUNTER_32_TEST_VALUE); - notifService.pushDelayedNotification(mfuBuilder.build(), 100); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getMeterStatistics(GetMeterStatisticsInput input) { - GetMeterStatisticsOutputBuilder builder = new GetMeterStatisticsOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - MeterStatsBuilder msBuilder = new MeterStatsBuilder(); - msBuilder.setKey(new MeterStatsKey(input.getMeterId())); - msBuilder.setByteInCount(StatisticsManagerTest.COUNTER_64_TEST_VALUE); - msBuilder.setPacketInCount(StatisticsManagerTest.COUNTER_64_TEST_VALUE); - List meterStats = new ArrayList<>(); - meterStats.add(msBuilder.build()); - MeterStatisticsUpdatedBuilder msuBuilder = new MeterStatisticsUpdatedBuilder(); - msuBuilder.setTransactionId(transId); - msuBuilder.setMoreReplies(false); - msuBuilder.setMeterStats(meterStats); - msuBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - notifService.pushDelayedNotification(msuBuilder.build(), 100); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightPortStatisticsServiceMock.java b/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightPortStatisticsServiceMock.java deleted file mode 100644 index 879cb02a96..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightPortStatisticsServiceMock.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Future; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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.port.statistics.rev131214.GetAllNodeConnectorsStatisticsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.NodeConnectorStatisticsUpdateBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.OpendaylightPortStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMap; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMapBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMapKey; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; - -import com.google.common.util.concurrent.Futures; - -public class OpendaylightPortStatisticsServiceMock implements OpendaylightPortStatisticsService { - NotificationProviderServiceHelper notifService; - - public OpendaylightPortStatisticsServiceMock(NotificationProviderServiceHelper notifService) { - this.notifService = notifService; - } - - @Override - public Future> getAllNodeConnectorsStatistics(GetAllNodeConnectorsStatisticsInput input) { - GetAllNodeConnectorsStatisticsOutputBuilder builder = new GetAllNodeConnectorsStatisticsOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - NodeConnectorStatisticsUpdateBuilder ncsuBuilder = new NodeConnectorStatisticsUpdateBuilder(); - NodeConnectorStatisticsAndPortNumberMapBuilder ncsapnmBuilder = new NodeConnectorStatisticsAndPortNumberMapBuilder(); - List nodeConnectorStatisticsAndPortNumberMaps = new ArrayList<>(); - ncsapnmBuilder.setKey(new NodeConnectorStatisticsAndPortNumberMapKey(StatisticsManagerTest.getNodeConnectorId())); - ncsapnmBuilder.setReceiveDrops(StatisticsManagerTest.BIG_INTEGER_TEST_VALUE); - nodeConnectorStatisticsAndPortNumberMaps.add(ncsapnmBuilder.build()); - ncsuBuilder.setTransactionId(transId); - ncsuBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - ncsuBuilder.setNodeConnectorStatisticsAndPortNumberMap(nodeConnectorStatisticsAndPortNumberMaps); - ncsuBuilder.setMoreReplies(true); - notifService.pushDelayedNotification(ncsuBuilder.build(), 0); // 1st notification - ncsuBuilder.setMoreReplies(false); - ncsapnmBuilder.setCollisionCount(StatisticsManagerTest.BIG_INTEGER_TEST_VALUE); - nodeConnectorStatisticsAndPortNumberMaps.clear(); - nodeConnectorStatisticsAndPortNumberMaps.add(ncsapnmBuilder.build()); - ncsuBuilder.setNodeConnectorStatisticsAndPortNumberMap(nodeConnectorStatisticsAndPortNumberMaps); - notifService.pushDelayedNotification(ncsuBuilder.build(), 10); // 2nd notification - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getNodeConnectorStatistics(GetNodeConnectorStatisticsInput input) { - GetNodeConnectorStatisticsOutputBuilder builder = new GetNodeConnectorStatisticsOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightQueueStatisticsServiceMock.java b/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightQueueStatisticsServiceMock.java deleted file mode 100644 index ddb660883a..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/OpendaylightQueueStatisticsServiceMock.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicLong; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetQueueStatisticsFromGivenPortInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetQueueStatisticsFromGivenPortOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetQueueStatisticsFromGivenPortOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.OpendaylightQueueStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.QueueStatisticsUpdateBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.queue.id.and.statistics.map.QueueIdAndStatisticsMap; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.queue.id.and.statistics.map.QueueIdAndStatisticsMapBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.queue.id.and.statistics.map.QueueIdAndStatisticsMapKey; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; - -import com.google.common.util.concurrent.Futures; - -public class OpendaylightQueueStatisticsServiceMock implements OpendaylightQueueStatisticsService { - NotificationProviderServiceHelper notifService; - AtomicLong transNum = new AtomicLong(); - - public OpendaylightQueueStatisticsServiceMock(NotificationProviderServiceHelper notifService) { - this.notifService = notifService; - } - - @Override - public Future> getAllQueuesStatisticsFromAllPorts(GetAllQueuesStatisticsFromAllPortsInput input) { - GetAllQueuesStatisticsFromAllPortsOutputBuilder builder = new GetAllQueuesStatisticsFromAllPortsOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - QueueStatisticsUpdateBuilder qsuBuilder = new QueueStatisticsUpdateBuilder(); - QueueIdAndStatisticsMapBuilder qiasmBuilder = new QueueIdAndStatisticsMapBuilder(); - List queueIdAndStatisticsMaps = new ArrayList<>(); - qsuBuilder.setMoreReplies(false); - qsuBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - qsuBuilder.setTransactionId(transId); - qiasmBuilder.setTransmittedBytes(StatisticsManagerTest.COUNTER_64_TEST_VALUE); - qiasmBuilder.setKey(new QueueIdAndStatisticsMapKey(StatisticsManagerTest.getNodeConnectorId(), StatisticsManagerTest.getQueue().getQueueId())); - queueIdAndStatisticsMaps.add(qiasmBuilder.build()); - qsuBuilder.setQueueIdAndStatisticsMap(queueIdAndStatisticsMaps); - notifService.pushDelayedNotification(qsuBuilder.build(), 100); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getAllQueuesStatisticsFromGivenPort(GetAllQueuesStatisticsFromGivenPortInput input) { - GetAllQueuesStatisticsFromGivenPortOutputBuilder builder = new GetAllQueuesStatisticsFromGivenPortOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } - - @Override - public Future> getQueueStatisticsFromGivenPort(GetQueueStatisticsFromGivenPortInput input) { - GetQueueStatisticsFromGivenPortOutputBuilder builder = new GetQueueStatisticsFromGivenPortOutputBuilder(); - TransactionId transId = new TransactionId(BigInteger.valueOf(TestUtils.getNewTransactionId())); - builder.setTransactionId(transId); - QueueIdAndStatisticsMapBuilder qiasmBuilder = new QueueIdAndStatisticsMapBuilder(); - List queueIdAndStatisticsMaps = new ArrayList<>(); - qiasmBuilder.setKey(new QueueIdAndStatisticsMapKey(input.getNodeConnectorId(), input.getQueueId())); - qiasmBuilder.setTransmittedBytes(StatisticsManagerTest.COUNTER_64_TEST_VALUE); - queueIdAndStatisticsMaps.add(qiasmBuilder.build()); - QueueStatisticsUpdateBuilder qsuBuilder = new QueueStatisticsUpdateBuilder(); - qsuBuilder.setMoreReplies(false); - qsuBuilder.setTransactionId(transId); - qsuBuilder.setId(input.getNode().getValue().firstKeyOf(Node.class, NodeKey.class).getId()); - qsuBuilder.setQueueIdAndStatisticsMap(queueIdAndStatisticsMaps); - notifService.pushDelayedNotification(qsuBuilder.build(), 100); - return Futures.immediateFuture(RpcResultBuilder.success(builder.build()).build()); - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/PortMockGenerator.java b/applications/statistics-manager/src/test/java/test/mock/util/PortMockGenerator.java deleted file mode 100644 index fdd5d52262..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/PortMockGenerator.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - - -import java.util.Random; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortConfig; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortNumberUni; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.port.mod.port.Port; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.port.mod.port.PortBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.port.mod.port.PortKey; - -public class PortMockGenerator { - private static final Random rnd = new Random(); - private static final PortBuilder portBuilder = new PortBuilder(); - - public static Port getRandomPort() { - portBuilder.setKey(new PortKey(TestUtils.nextLong(0, 4294967295L))); - portBuilder.setBarrier(rnd.nextBoolean()); - portBuilder.setPortNumber(new PortNumberUni(TestUtils.nextLong(0, 4294967295L))); - portBuilder.setConfiguration(new PortConfig(rnd.nextBoolean(), rnd.nextBoolean(), rnd.nextBoolean(), rnd.nextBoolean())); - return portBuilder.build(); - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/QueueMockGenerator.java b/applications/statistics-manager/src/test/java/test/mock/util/QueueMockGenerator.java deleted file mode 100644 index a5d7101681..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/QueueMockGenerator.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.Queue; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.QueueBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.QueueKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.queue.rev130925.QueueId; - -import java.util.Random; - -public class QueueMockGenerator { - private static final Random rnd = new Random(); - private static final QueueBuilder queueBuilder = new QueueBuilder(); - - public static Queue getRandomQueue() { - queueBuilder.setKey(new QueueKey(new QueueId(TestUtils.nextLong(0, 4294967295L)))); - queueBuilder.setPort(TestUtils.nextLong(0, 4294967295L)); - queueBuilder.setProperty(rnd.nextInt(65535)); - return queueBuilder.build(); - } - - public static Queue getRandomQueueWithPortNum(long portNum) { - queueBuilder.setKey(new QueueKey(new QueueId(TestUtils.nextLong(0, 4294967295L)))); - queueBuilder.setPort(portNum); - queueBuilder.setProperty(rnd.nextInt(65535)); - return queueBuilder.build(); - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/RpcProviderRegistryMock.java b/applications/statistics-manager/src/test/java/test/mock/util/RpcProviderRegistryMock.java deleted file mode 100644 index 23cef94f80..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/RpcProviderRegistryMock.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.controller.sal.binding.api.rpc.RpcContextIdentifier; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.OpendaylightFlowStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.OpendaylightFlowTableStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.OpendaylightGroupStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.OpendaylightMeterStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.OpendaylightPortStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.OpendaylightQueueStatisticsService; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.binding.RpcService; - -public class RpcProviderRegistryMock implements RpcProviderRegistry { - - OpendaylightFlowStatisticsServiceMock flowStatisticsServiceMock; - OpendaylightFlowTableStatisticsServiceMock flowTableStatisticsServiceMock; - OpendaylightGroupStatisticsServiceMock groupStatisticsServiceMock; - OpendaylightMeterStatisticsServiceMock meterStatisticsServiceMock; - OpendaylightPortStatisticsServiceMock portStatisticsServiceMock; - OpendaylightQueueStatisticsServiceMock queueStatisticsServiceMock; - - public RpcProviderRegistryMock(NotificationProviderServiceHelper notificationProviderService) { - this.flowStatisticsServiceMock = new OpendaylightFlowStatisticsServiceMock(notificationProviderService); - this.flowTableStatisticsServiceMock = new OpendaylightFlowTableStatisticsServiceMock(notificationProviderService); - this.groupStatisticsServiceMock = new OpendaylightGroupStatisticsServiceMock(notificationProviderService); - this.meterStatisticsServiceMock = new OpendaylightMeterStatisticsServiceMock(notificationProviderService); - this.portStatisticsServiceMock = new OpendaylightPortStatisticsServiceMock(notificationProviderService); - this.queueStatisticsServiceMock = new OpendaylightQueueStatisticsServiceMock(notificationProviderService); - } - - @Override - public BindingAwareBroker.RpcRegistration addRpcImplementation(Class serviceInterface, T implementation) throws IllegalStateException { - return null; - } - - @Override - public BindingAwareBroker.RoutedRpcRegistration addRoutedRpcImplementation(Class serviceInterface, T implementation) throws IllegalStateException { - return null; - } - - @Override - public >> ListenerRegistration registerRouteChangeListener(L listener) { - return null; - } - - @SuppressWarnings("unchecked") - @Override - public T getRpcService(Class serviceInterface) { - if (serviceInterface.equals(OpendaylightFlowStatisticsService.class)) { - return (T)flowStatisticsServiceMock; - } else if (serviceInterface.equals(OpendaylightFlowTableStatisticsService.class)) { - return (T) flowTableStatisticsServiceMock; - } else if (serviceInterface.equals(OpendaylightGroupStatisticsService.class)) { - return (T) groupStatisticsServiceMock; - } else if (serviceInterface.equals(OpendaylightMeterStatisticsService.class)) { - return (T) meterStatisticsServiceMock; - } else if (serviceInterface.equals(OpendaylightPortStatisticsService.class)) { - return (T) portStatisticsServiceMock; - } else if (serviceInterface.equals(OpendaylightQueueStatisticsService.class)) { - return (T) queueStatisticsServiceMock; - } else { - return null; - } - } - - public OpendaylightFlowStatisticsServiceMock getFlowStatisticsServiceMock() { - return flowStatisticsServiceMock; - } - - public OpendaylightFlowTableStatisticsServiceMock getFlowTableStatisticsServiceMock() { - return flowTableStatisticsServiceMock; - } - - public OpendaylightGroupStatisticsServiceMock getGroupStatisticsServiceMock() { - return groupStatisticsServiceMock; - } - - public OpendaylightMeterStatisticsServiceMock getMeterStatisticsServiceMock() { - return meterStatisticsServiceMock; - } - - public OpendaylightPortStatisticsServiceMock getPortStatisticsServiceMock() { - return portStatisticsServiceMock; - } - - public OpendaylightQueueStatisticsServiceMock getQueueStatisticsServiceMock() { - return queueStatisticsServiceMock; - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/StatisticsManagerTest.java b/applications/statistics-manager/src/test/java/test/mock/util/StatisticsManagerTest.java deleted file mode 100644 index 6d3a97b4b5..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/StatisticsManagerTest.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ExecutionException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.opendaylight.controller.md.sal.binding.api.WriteTransaction; -import org.opendaylight.controller.md.sal.binding.test.AbstractDataBrokerTest; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.openflowplugin.applications.statistics.manager.StatisticsManager; -import org.opendaylight.openflowplugin.applications.statistics.manager.impl.StatisticsManagerConfig; -import org.opendaylight.openflowplugin.applications.statistics.manager.impl.StatisticsManagerImpl; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Counter32; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Counter64; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FeatureCapability; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdatedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.flow.node.SwitchFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.port.mod.port.Port; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.Queue; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRemovedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdatedBuilder; -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.inventory.rev130819.nodes.NodeBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.nodes.node.MeterFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; - -public abstract class StatisticsManagerTest extends AbstractDataBrokerTest { - - public static final Counter64 COUNTER_64_TEST_VALUE = new Counter64(BigInteger.valueOf(128)); - public static final Counter32 COUNTER_32_TEST_VALUE = new Counter32(64L); - public static final Long MAX_GROUPS_TEST_VALUE = 2000L; - public static final BigInteger BIG_INTEGER_TEST_VALUE = BigInteger.valueOf(1000); - - private static final int DEFAULT_MIN_REQUEST_NET_MONITOR_INTERVAL = 5000; - private static final int MAX_NODES_FOR_COLLECTOR = 16; - - private static Flow flow; - private static Group group; - private static Meter meter; - private static Port port; - private static Queue queue; - private static TableId tableId; - private static NodeConnectorId nodeConnectorId; - - private final NotificationProviderServiceHelper notificationMock = new NotificationProviderServiceHelper(); - protected final NodeKey s1Key = new NodeKey(new NodeId("S1")); - protected RpcProviderRegistryMock rpcRegistry; - - @BeforeClass - public static void setupTests() { - flow = FlowMockGenerator.getRandomFlow(); - group = GroupMockGenerator.getRandomGroup(); - meter = MeterMockGenerator.getRandomMeter(); - port = PortMockGenerator.getRandomPort(); - queue = QueueMockGenerator.getRandomQueueWithPortNum(port.getPortNumber().getUint32()); - tableId = new TableId((short) 2); - nodeConnectorId = new NodeConnectorId("connector.1"); - } - - @Before - public void init() { - rpcRegistry = new RpcProviderRegistryMock(notificationMock); - } - - // node with statistics capabilities will enable cyclic statistics collection - @SafeVarargs - protected final void addFlowCapableNodeWithFeatures(final NodeKey nodeKey, final Boolean hasMeterCapabilities, - final Class... capabilities) - throws ExecutionException, InterruptedException { - final Nodes nodes = new NodesBuilder().setNode(Collections.emptyList()).build(); - final InstanceIdentifier flowNodeIdentifier = InstanceIdentifier.create(Nodes.class) - .child(Node.class, nodeKey); - - final FlowCapableNodeBuilder fcnBuilder = new FlowCapableNodeBuilder(); - final SwitchFeaturesBuilder sfBuilder = new SwitchFeaturesBuilder(); - final List> capabilitiyList = new ArrayList<>(); - for (final Class capability : capabilities) { - capabilitiyList.add(capability); - } - sfBuilder.setCapabilities(capabilitiyList); - sfBuilder.setMaxTables((short) 255); - final NodeBuilder nodeBuilder = new NodeBuilder(); - nodeBuilder.setKey(nodeKey); - fcnBuilder.setSwitchFeatures(sfBuilder.build()); - final List
tables = new ArrayList<>(); - final TableBuilder tBuilder = new TableBuilder(); - tBuilder.setId(getFlow().getTableId()); - tables.add(tBuilder.build()); - fcnBuilder.setTable(tables); - final FlowCapableNode flowCapableNode = fcnBuilder.build(); - nodeBuilder.addAugmentation(FlowCapableNode.class, flowCapableNode); - final Node node = nodeBuilder.build(); - - final WriteTransaction writeTx = getDataBroker().newWriteOnlyTransaction(); - writeTx.put(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodes); - writeTx.put(LogicalDatastoreType.OPERATIONAL, flowNodeIdentifier, nodeBuilder.build()); - if (hasMeterCapabilities) { - final NodeMeterFeaturesBuilder nmfBuilder = new NodeMeterFeaturesBuilder(); - final MeterFeaturesBuilder mfBuilder = new MeterFeaturesBuilder(); - mfBuilder.setMaxBands((short) 4); - nmfBuilder.setMeterFeatures(mfBuilder.build()); - writeTx.put(LogicalDatastoreType.OPERATIONAL, flowNodeIdentifier.augmentation(NodeMeterFeatures.class), - nmfBuilder.build()); - } - writeTx.put(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.create(Nodes.class), nodes); - writeTx.put(LogicalDatastoreType.CONFIGURATION, flowNodeIdentifier, node); - assertCommit(writeTx.submit()); - - final NodeUpdatedBuilder nuBuilder = new NodeUpdatedBuilder(node); - final FlowCapableNodeUpdatedBuilder fcnuBuilder = new FlowCapableNodeUpdatedBuilder(flowCapableNode); - nuBuilder.setNodeRef(new NodeRef(flowNodeIdentifier)); - nuBuilder.addAugmentation(FlowCapableNodeUpdated.class, fcnuBuilder.build()); - notificationMock.pushNotification(nuBuilder.build()); - } - - public void addFlowCapableNode(final NodeKey nodeKey) throws ExecutionException, InterruptedException { - final Nodes nodes = new NodesBuilder().setNode(Collections.emptyList()).build(); - final InstanceIdentifier flowNodeIdentifier = InstanceIdentifier.create(Nodes.class) - .child(Node.class, nodeKey); - - final FlowCapableNodeBuilder fcnBuilder = new FlowCapableNodeBuilder(); - final NodeBuilder nodeBuilder = new NodeBuilder(); - nodeBuilder.setKey(nodeKey); - final SwitchFeaturesBuilder sfBuilder = new SwitchFeaturesBuilder(); - sfBuilder.setMaxTables((short) 255); - fcnBuilder.setSwitchFeatures(sfBuilder.build()); - final FlowCapableNode flowCapableNode = fcnBuilder.build(); - nodeBuilder.addAugmentation(FlowCapableNode.class, flowCapableNode); - final Node node = nodeBuilder.build(); - - final WriteTransaction writeTx = getDataBroker().newWriteOnlyTransaction(); - writeTx.put(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodes); - writeTx.put(LogicalDatastoreType.OPERATIONAL, flowNodeIdentifier, node); - writeTx.put(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.create(Nodes.class), nodes); - writeTx.put(LogicalDatastoreType.CONFIGURATION, flowNodeIdentifier, node); - assertCommit(writeTx.submit()); - - final NodeUpdatedBuilder nuBuilder = new NodeUpdatedBuilder(node); - final FlowCapableNodeUpdatedBuilder fcnuBuilder = new FlowCapableNodeUpdatedBuilder(flowCapableNode); - nuBuilder.setNodeRef(new NodeRef(flowNodeIdentifier)); - nuBuilder.addAugmentation(FlowCapableNodeUpdated.class, fcnuBuilder.build()); - notificationMock.pushNotification(nuBuilder.build()); - } - - protected void removeNode(final NodeKey nodeKey) throws ExecutionException, InterruptedException { - final InstanceIdentifier nodeII = InstanceIdentifier.create(Nodes.class).child(Node.class, nodeKey); - - final WriteTransaction writeTx = getDataBroker().newWriteOnlyTransaction(); - writeTx.delete(LogicalDatastoreType.OPERATIONAL, nodeII); - writeTx.submit().get(); - - final NodeRemovedBuilder nrBuilder = new NodeRemovedBuilder(); - nrBuilder.setNodeRef(new NodeRef(nodeII)); - notificationMock.pushNotification(nrBuilder.build()); - } - - public StatisticsManager setupStatisticsManager() { - StatisticsManagerConfig.StatisticsManagerConfigBuilder confBuilder = StatisticsManagerConfig.builder(); - confBuilder.setMaxNodesForCollector(MAX_NODES_FOR_COLLECTOR); - confBuilder.setMinRequestNetMonitorInterval(DEFAULT_MIN_REQUEST_NET_MONITOR_INTERVAL); - StatisticsManager statsProvider = new StatisticsManagerImpl(getDataBroker(), confBuilder.build()); - statsProvider.start(notificationMock.getNotifBroker(), rpcRegistry); - statsProvider.setOwnershipService(new EntityOwnershipServiceMock()); - return statsProvider; - } - - public static Flow getFlow() { - return flow; - } - - public static Group getGroup() { - return group; - } - - public static Meter getMeter() { - return meter; - } - - public static Port getPort() { - return port; - } - - public static Queue getQueue() { - return queue; - } - - public static TableId getTableId() { - return tableId; - } - - public static NodeConnectorId getNodeConnectorId() { - return nodeConnectorId; - } -} diff --git a/applications/statistics-manager/src/test/java/test/mock/util/TestUtils.java b/applications/statistics-manager/src/test/java/test/mock/util/TestUtils.java deleted file mode 100644 index 79bb308ce4..0000000000 --- a/applications/statistics-manager/src/test/java/test/mock/util/TestUtils.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2014, 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 test.mock.util; - -import java.util.Random; -import java.util.concurrent.atomic.AtomicLong; - -public class TestUtils { - - private static AtomicLong transId = new AtomicLong(); - - private static Random rnd = new Random(); - - public static long nextLong(long RangeBottom, long rangeTop) { - return RangeBottom + ((long)(rnd.nextDouble()*(rangeTop - RangeBottom))); - } - - public static long getNewTransactionId() { - return transId.incrementAndGet(); - } -} diff --git a/applications/statistics-manager/src/test/resources/log4j-test.xml b/applications/statistics-manager/src/test/resources/log4j-test.xml deleted file mode 100644 index bd3bf3cd2c..0000000000 --- a/applications/statistics-manager/src/test/resources/log4j-test.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - -