From 6e5df2b3308ffdc906dc1ef84a4ddde37f8080f6 Mon Sep 17 00:00:00 2001 From: Tomas Slusny Date: Tue, 8 Aug 2017 12:48:42 +0200 Subject: [PATCH] Remove unused code from He design See also: bug 8656 Change-Id: Ib1657f519587e6ec463bf1f2af2e50ccd3b727e5 Signed-off-by: Tomas Slusny --- .../extension/ExtensionConverterProvider.java | 3 - .../core/session/ExtensionSessionManager.java | 5 +- .../openflowplugin/api/OFConstants.java | 10 +- ...AbstractModelDrivenSwitchRegistration.java | 20 - .../api/openflow/md/ModelDrivenSwitch.java | 87 - .../md/ModelDrivenSwitchRegistration.java | 15 - .../openflow/md/core/ConnectionConductor.java | 112 - .../api/openflow/md/core/ErrorHandler.java | 5 +- .../md/core/IMDMessageTranslator.java | 28 - .../md/core/NotificationEnqueuer.java | 21 - .../md/core/NotificationQueueWrapper.java | 63 - .../core/SwitchConnectionDistinguisher.java | 19 - .../md/core/sal/NotificationComposer.java | 25 - .../core/session/IMessageDispatchService.java | 244 -- .../md/core/session/SessionContext.java | 195 -- .../md/core/session/SessionListener.java | 32 - .../md/core/session/SessionManager.java | 157 -- .../md/core/session/SwitchSessionKeyOF.java | 70 - .../api/openflow/md/queue/Enqueuer.java | 31 - .../openflow/md/queue/HarvesterHandle.java | 20 - .../queue/MessageSourcePollRegistrator.java | 44 - .../api/openflow/md/queue/PopListener.java | 18 - .../api/openflow/md/queue/QueueItem.java | 35 - .../api/openflow/md/queue/QueueKeeper.java | 53 - .../api/openflow/md/queue/QueueProcessor.java | 42 - .../openflow/md/queue/WaterMarkListener.java | 22 - .../md/queue/WaterMarkListenerImpl.java | 52 - .../md/util/PollableQueuesPriorityZipper.java | 57 - .../md/util/PollableQueuesZipper.java | 63 - .../blueprint/openflowplugin-api.xml | 6 - .../connection/ConnectionManagerImpl.java | 6 +- .../blueprint/openflowplugin-impl.xml | 2 + openflowplugin/pom.xml | 34 - .../md/core/ConnectionConductorFactory.java | 45 - .../md/core/ConnectionConductorImpl.java | 551 ---- .../md/core/ErrorHandlerSimpleImpl.java | 15 +- .../md/core/HandshakeManagerImpl.java | 24 +- .../md/core/HandshakeStepWrapper.java | 4 - .../openflow/md/core/IMDController.java | 63 - .../openflow/md/core/MDController.java | 416 --- .../openflow/md/core/MessageFactory.java | 51 +- .../md/core/NotificationPopListener.java | 56 - .../md/core/RpcListeningExecutorService.java | 142 - .../openflow/md/core/RpcUtil.java | 38 - .../md/core/SwitchConnectionHandlerImpl.java | 86 - .../core/extension/ActionExtensionHelper.java | 3 - .../md/core/extension/ExtensionResolvers.java | 3 - .../core/extension/MatchExtensionHelper.java | 3 - .../md/core/role/OfEntityManager.java | 473 ---- .../core/role/OpenflowOwnershipListener.java | 25 - .../md/core/role/RoleChangeException.java | 31 - .../core/sal/AbstractModelDrivenSwitch.java | 140 - .../core/sal/BuildSwitchCapabilitiesOF10.java | 3 - .../core/sal/BuildSwitchCapabilitiesOF13.java | 3 - .../md/core/sal/ModelDrivenSwitchImpl.java | 562 ---- .../OFRpcFutureResultTransformFactory.java | 190 -- .../openflow/md/core/sal/OFRpcTask.java | 139 - .../md/core/sal/OFRpcTaskContext.java | 120 - .../md/core/sal/OFRpcTaskFactory.java | 2287 ----------------- .../openflow/md/core/sal/OFRpcTaskUtil.java | 205 -- .../md/core/sal/OpenflowPluginConfig.java | 43 - .../md/core/sal/OpenflowPluginProvider.java | 219 -- .../md/core/sal/SalRegistrationManager.java | 260 -- .../md/core/sal/SwitchFeaturesUtil.java | 4 - .../core/session/ConjunctSessionManager.java | 18 - .../session/ExtensionSessionManagerImpl.java | 47 + .../md/core/session/FeaturesV10Bandwidth.java | 42 - .../md/core/session/FeaturesV13Bandwidth.java | 42 - .../md/core/session/IGetBandwith.java | 26 - .../session/MessageDispatchServiceImpl.java | 327 --- .../md/core/session/OFRoleManager.java | 109 - .../md/core/session/OFSessionUtil.java | 175 +- .../md/core/session/PortFeaturesUtil.java | 67 - .../md/core/session/RolePushException.java | 33 - .../md/core/session/RolePushTask.java | 164 -- .../md/core/session/SessionContextOFImpl.java | 257 -- .../md/core/session/SessionManagerOFImpl.java | 354 --- .../session/SwitchConnectionCookieOFImpl.java | 97 - .../translator/AbstractErrorTranslator.java | 77 - .../md/core/translator/ErrorTranslator.java | 205 -- .../core/translator/ErrorV10Translator.java | 61 - .../translator/ExperimenterTranslator.java | 39 - ...esV10ToNodeConnectorUpdatedTranslator.java | 47 - .../translator/FlowRemovedTranslator.java | 639 ----- ...artMessageDescToNodeUpdatedTranslator.java | 60 - ...yPortToNodeConnectorUpdatedTranslator.java | 53 - ...TableFeaturesToTableUpdatedTranslator.java | 75 - .../translator/MultipartReplyTranslator.java | 515 ---- .../NotificationPlainTranslator.java | 51 - .../core/translator/PacketInTranslator.java | 132 - .../translator/PacketInV10Translator.java | 79 - ...ssageToNodeConnectorUpdatedTranslator.java | 56 - .../queue/MessageSourcePollRegistration.java | 36 - .../openflow/md/queue/QueueItemOFImpl.java | 52 - .../openflow/md/queue/QueueKeeperFactory.java | 58 - .../md/queue/QueueKeeperFairImpl.java | 125 - .../md/queue/QueueKeeperHarvester.java | 90 - .../md/queue/QueueProcessorLightImpl.java | 242 -- .../openflow/md/queue/Ticket.java | 35 - .../openflow/md/queue/TicketFinisher.java | 28 - .../openflow/md/queue/TicketFinisherImpl.java | 85 - .../openflow/md/queue/TicketImpl.java | 98 - .../md/queue/TicketProcessorFactory.java | 59 - .../md/queue/TicketProcessorFactoryImpl.java | 177 -- .../openflow/md/queue/TicketResult.java | 35 - .../openflow/md/queue/WrapperQueueImpl.java | 157 -- .../openflow/md/util/ByteUtil.java | 3 - .../md/util/InventoryDataServiceUtil.java | 44 +- .../openflow/md/util/OpenflowPortsUtil.java | 2 - .../openflow/md/util/PacketInUtil.java | 3 - .../openflow/md/util/RoleUtil.java | 162 -- .../openflow/md/util/RpcInputOutputTuple.java | 42 - .../openflow/md/util/RpcResultUtil.java | 53 - .../openflow/md/util/TaskUtil.java | 47 - .../statistics/MessageSpyCounterImpl.java | 135 - .../main/yang/openflow-plugin-cfg-impl.yang | 28 - .../md/core/ConnectionConductorImplTest.java | 722 ------ .../md/core/ErrorHandlerSimpleImplTest.java | 21 +- .../md/core/HandshakeManagerImplTest.java | 8 +- .../openflow/md/core/MDControllerTest.java | 112 - .../openflow/md/core/MessageFactoryTest.java | 9 +- .../md/core/NotificationQueueWrapperTest.java | 58 - .../md/core/PopListenerCountingImpl.java | 39 - .../core/SwitchConnectionHandlerImplTest.java | 47 - .../core/plan/ConnectionAdapterStackImpl.java | 670 ----- .../openflow/md/core/plan/EventFactory.java | 157 -- .../md/core/plan/SwitchTestCallbackEvent.java | 23 - .../plan/SwitchTestCallbackEventImpl.java | 41 - .../md/core/plan/SwitchTestEvent.java | 16 - .../plan/SwitchTestNotificationEvent.java | 22 - .../plan/SwitchTestNotificationEventImpl.java | 49 - .../core/plan/SwitchTestRcpResponseEvent.java | 27 - .../plan/SwitchTestRcpResponseEventImpl.java | 53 - .../core/plan/SwitchTestWaitForAllEvent.java | 23 - .../plan/SwitchTestWaitForAllEventImpl.java | 46 - .../core/plan/SwitchTestWaitForRpcEvent.java | 26 - .../plan/SwitchTestWaitForRpcEventImpl.java | 50 - .../ConcurrentSalRegistrationManagerTest.java | 258 -- .../core/sal/ModelDrivenSwitchImplTest.java | 1172 --------- .../md/core/sal/OFRpcTaskUtilTest.java | 101 - .../core/sal/OpenflowPluginProviderTest.java | 71 - .../core/sal/SalRegistrationManagerTest.java | 210 -- .../ExtensionSessionManagerImplTest.java | 46 + .../MessageDispatchServiceImplTest.java | 819 ------ .../md/core/session/OFRoleManagerTest.java | 141 - .../md/core/session/PortFeaturesUtilTest.java | 117 - .../session/SessionManagerOFImplTest.java | 151 -- .../SwitchConnectionCookieOFImplTest.java | 139 - .../core/translator/ErrorTranslatorTest.java | 122 - .../translator/ErrorTranslatorV10Test.java | 99 - ...0ToNodeConnectorUpdatedTranslatorTest.java | 145 -- .../translator/FlowRemovedTranslatorTest.java | 624 ----- ...essageDescToNodeUpdatedTranslatorTest.java | 112 - ...tToNodeConnectorUpdatedTranslatorTest.java | 207 -- ...eFeaturesToTableUpdatedTranslatorTest.java | 197 -- .../MultipartReplyTranslatorFifthTest.java | 328 --- .../MultipartReplyTranslatorFirstTest.java | 241 -- .../MultipartReplyTranslatorFourthTest.java | 307 --- .../MultipartReplyTranslatorSecondTest.java | 222 -- .../MultipartReplyTranslatorThirdTest.java | 382 --- .../NotificationPlainTranslatorTest.java | 84 - .../translator/PacketInV10TranslatorTest.java | 269 -- .../md/util/InventoryDataServiceUtilTest.java | 81 +- .../PollableQueuesPriorityZipperTest.java | 90 - .../md/util/PollableQueuesZipperTest.java | 56 - .../openflow/md/util/RoleUtilTest.java | 190 -- .../md/util/WrapperQueueImplTest.java | 170 -- .../statistics/MessageSpyCounterImplTest.java | 48 - 168 files changed, 143 insertions(+), 22718 deletions(-) delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/AbstractModelDrivenSwitchRegistration.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/ModelDrivenSwitch.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/ModelDrivenSwitchRegistration.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/ConnectionConductor.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/IMDMessageTranslator.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/NotificationEnqueuer.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/NotificationQueueWrapper.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/SwitchConnectionDistinguisher.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/sal/NotificationComposer.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/IMessageDispatchService.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SessionContext.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SessionListener.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SessionManager.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SwitchSessionKeyOF.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/Enqueuer.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/HarvesterHandle.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/MessageSourcePollRegistrator.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/PopListener.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/QueueItem.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/QueueKeeper.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/QueueProcessor.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/WaterMarkListener.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/WaterMarkListenerImpl.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/util/PollableQueuesPriorityZipper.java delete mode 100644 openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/util/PollableQueuesZipper.java delete mode 100644 openflowplugin-api/src/main/resources/org/opendaylight/blueprint/openflowplugin-api.xml delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/ConnectionConductorFactory.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/ConnectionConductorImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/IMDController.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/MDController.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/NotificationPopListener.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/RpcListeningExecutorService.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/RpcUtil.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/SwitchConnectionHandlerImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/role/OfEntityManager.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/role/OpenflowOwnershipListener.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/role/RoleChangeException.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/AbstractModelDrivenSwitch.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/ModelDrivenSwitchImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcFutureResultTransformFactory.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTask.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskContext.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskFactory.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskUtil.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OpenflowPluginConfig.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OpenflowPluginProvider.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/SalRegistrationManager.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/ConjunctSessionManager.java create mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/ExtensionSessionManagerImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/FeaturesV10Bandwidth.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/FeaturesV13Bandwidth.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/IGetBandwith.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/MessageDispatchServiceImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/OFRoleManager.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/PortFeaturesUtil.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/RolePushException.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/RolePushTask.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/SessionContextOFImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/SessionManagerOFImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/SwitchConnectionCookieOFImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/AbstractErrorTranslator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorTranslator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorV10Translator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ExperimenterTranslator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FeaturesV10ToNodeConnectorUpdatedTranslator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FlowRemovedTranslator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartMessageDescToNodeUpdatedTranslator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartReplyPortToNodeConnectorUpdatedTranslator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTableFeaturesToTableUpdatedTranslator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/NotificationPlainTranslator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PacketInTranslator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PacketInV10Translator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PortStatusMessageToNodeConnectorUpdatedTranslator.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/MessageSourcePollRegistration.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueItemOFImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueKeeperFactory.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueKeeperFairImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueKeeperHarvester.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueProcessorLightImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/Ticket.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketFinisher.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketFinisherImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketProcessorFactory.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketProcessorFactoryImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketResult.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/WrapperQueueImpl.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/RoleUtil.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/RpcInputOutputTuple.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/RpcResultUtil.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/TaskUtil.java delete mode 100644 openflowplugin/src/main/java/org/opendaylight/openflowplugin/statistics/MessageSpyCounterImpl.java delete mode 100644 openflowplugin/src/main/yang/openflow-plugin-cfg-impl.yang delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/ConnectionConductorImplTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/MDControllerTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/NotificationQueueWrapperTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/PopListenerCountingImpl.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/SwitchConnectionHandlerImplTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/ConnectionAdapterStackImpl.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/EventFactory.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestCallbackEvent.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestCallbackEventImpl.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestEvent.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestNotificationEvent.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestNotificationEventImpl.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestRcpResponseEvent.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestRcpResponseEventImpl.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForAllEvent.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForAllEventImpl.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForRpcEvent.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForRpcEventImpl.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/ConcurrentSalRegistrationManagerTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/ModelDrivenSwitchImplTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskUtilTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OpenflowPluginProviderTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/SalRegistrationManagerTest.java create mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/ExtensionSessionManagerImplTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/MessageDispatchServiceImplTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/OFRoleManagerTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/PortFeaturesUtilTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/SessionManagerOFImplTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/SwitchConnectionCookieOFImplTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorTranslatorTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorTranslatorV10Test.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FeaturesV10ToNodeConnectorUpdatedTranslatorTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FlowRemovedTranslatorTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartMessageDescToNodeUpdatedTranslatorTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartReplyPortToNodeConnectorUpdatedTranslatorTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTableFeaturesToTableUpdatedTranslatorTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorFifthTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorFirstTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorFourthTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorSecondTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorThirdTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/NotificationPlainTranslatorTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PacketInV10TranslatorTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/PollableQueuesPriorityZipperTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/PollableQueuesZipperTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/RoleUtilTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/WrapperQueueImplTest.java delete mode 100644 openflowplugin/src/test/java/org/opendaylight/openflowplugin/statistics/MessageSpyCounterImplTest.java diff --git a/extension/openflowplugin-extension-api/src/main/java/org/opendaylight/openflowplugin/extension/api/core/extension/ExtensionConverterProvider.java b/extension/openflowplugin-extension-api/src/main/java/org/opendaylight/openflowplugin/extension/api/core/extension/ExtensionConverterProvider.java index d61e751916..d3d1617b4c 100644 --- a/extension/openflowplugin-extension-api/src/main/java/org/opendaylight/openflowplugin/extension/api/core/extension/ExtensionConverterProvider.java +++ b/extension/openflowplugin-extension-api/src/main/java/org/opendaylight/openflowplugin/extension/api/core/extension/ExtensionConverterProvider.java @@ -21,9 +21,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.acti import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.experimenter.types.rev151020.experimenter.core.message.ExperimenterMessageOfChoice; import org.opendaylight.yangtools.yang.binding.DataContainer; -/** - * - */ public interface ExtensionConverterProvider { /** diff --git a/extension/openflowplugin-extension-api/src/main/java/org/opendaylight/openflowplugin/extension/api/core/session/ExtensionSessionManager.java b/extension/openflowplugin-extension-api/src/main/java/org/opendaylight/openflowplugin/extension/api/core/session/ExtensionSessionManager.java index c74a165ac7..ec0261c184 100644 --- a/extension/openflowplugin-extension-api/src/main/java/org/opendaylight/openflowplugin/extension/api/core/session/ExtensionSessionManager.java +++ b/extension/openflowplugin-extension-api/src/main/java/org/opendaylight/openflowplugin/extension/api/core/session/ExtensionSessionManager.java @@ -10,13 +10,10 @@ package org.opendaylight.openflowplugin.extension.api.core.session; import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider; -/** - * Created by Martin Bobak mbobak@cisco.com on 10/15/14. - */ public interface ExtensionSessionManager { /** - * @param extensionConverterProvider + * @param extensionConverterProvider extension converter provider */ void setExtensionConverterProvider(ExtensionConverterProvider extensionConverterProvider); diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/OFConstants.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/OFConstants.java index 6148f5fbcd..2df09f091e 100644 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/OFConstants.java +++ b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/OFConstants.java @@ -7,7 +7,9 @@ */ package org.opendaylight.openflowplugin.api; +import com.google.common.collect.ImmutableList; import java.math.BigInteger; +import java.util.List; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie; 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; @@ -76,4 +78,10 @@ public final class OFConstants { /** Persistent ID of OpenFlowPlugin configuration file. */ public static final String CONFIG_FILE_ID = "org.opendaylight.openflowplugin"; -} + + /** supported version ordered by height (highest version is at the beginning). */ + public static final List VERSION_ORDER = ImmutableList + .builder() + .add((short) 0x04, (short) 0x01) + .build(); +} \ No newline at end of file diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/AbstractModelDrivenSwitchRegistration.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/AbstractModelDrivenSwitchRegistration.java deleted file mode 100644 index 2672c08f21..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/AbstractModelDrivenSwitchRegistration.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.api.openflow.md; - -import org.opendaylight.yangtools.concepts.AbstractObjectRegistration; - -public abstract class AbstractModelDrivenSwitchRegistration - extends AbstractObjectRegistration - implements ModelDrivenSwitchRegistration { - - protected AbstractModelDrivenSwitchRegistration(final ModelDrivenSwitch instance) { - super(instance); - } - -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/ModelDrivenSwitch.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/ModelDrivenSwitch.java deleted file mode 100644 index 9a3ef94f50..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/ModelDrivenSwitch.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.api.openflow.md; - -import com.google.common.base.Optional; -import java.math.BigInteger; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService; -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.service.rev130918.SalGroupService; -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.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.SalMeterService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.OpendaylightMeterStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.NodeConfigService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.SalPortService; -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.yang.gen.v1.urn.opendaylight.table.service.rev131026.SalTableService; -import org.opendaylight.yangtools.concepts.Identifiable; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; - -/** - * interface concatenating all md-sal services provided by OF-switch. - */ -public interface ModelDrivenSwitch - extends - SalGroupService, - SalFlowService, - SalMeterService, SalTableService, SalPortService, PacketProcessingService, NodeConfigService, - OpendaylightGroupStatisticsService, OpendaylightMeterStatisticsService, OpendaylightFlowStatisticsService, - OpendaylightPortStatisticsService, OpendaylightFlowTableStatisticsService, OpendaylightQueueStatisticsService, - Identifiable> { - - /** - * Register. - * @param rpcProviderRegistry rpc provider - * @return wrapped list of {service provider + path} registration couples - */ - ModelDrivenSwitchRegistration register(RpcProviderRegistry rpcProviderRegistry); - - /** - * Getter. - * @return id of encapsulated node (served by this impl) - */ - NodeId getNodeId(); - - /** - * returnes the session context associated with this model-driven switch. - * - * @return session context object - */ - SessionContext getSessionContext(); - - /** - * Returns whether this *instance* is entity owner or not. - * @return true if it's entity owner, else false. - */ - boolean isEntityOwner(); - - /** - * Set entity ownership satus of this switch in *this* instance. - * @param isOwner is owner - */ - void setEntityOwnership(boolean isOwner); - - /** - * Send table feature to the switch to get tables features for all the tables. - * @return Transaction id - */ - Optional sendEmptyTableFeatureRequest(); - - /** - * Method send port/desc multipart request to the switch to fetch the initial details. - */ - void requestSwitchDetails(); - -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/ModelDrivenSwitchRegistration.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/ModelDrivenSwitchRegistration.java deleted file mode 100644 index 3c159c465c..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/ModelDrivenSwitchRegistration.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.api.openflow.md; - -import org.opendaylight.yangtools.concepts.ObjectRegistration; - -public interface ModelDrivenSwitchRegistration extends ObjectRegistration { - @Override - void close(); -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/ConnectionConductor.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/ConnectionConductor.java deleted file mode 100644 index 6d517eb73e..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/ConnectionConductor.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.api.openflow.md.core; - -import com.google.common.collect.Lists; -import java.util.List; -import java.util.concurrent.Future; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.DataObject; - - -public interface ConnectionConductor { - - /** distinguished connection states. */ - @SuppressWarnings({"checkstyle:abbreviationaswordinname", "checkstyle:typename"}) - enum CONDUCTOR_STATE { - /** initial phase of talking to switch. */ - HANDSHAKING, - /** standard phase - interacting with switch. */ - WORKING, - /** connection is idle, waiting for echo reply from switch. */ - TIMEOUTING, - /** talking to switch is over - resting in pieces. */ - RIP - } - - /** supported version ordered by height (highest version is at the beginning). */ - List VERSION_ORDER = Lists.newArrayList((short) 0x04, (short) 0x01); - - /** - * initialize wiring around {@link ConnectionAdapter}. - */ - void init(); - - /** - * return the negotiated version. - */ - Short getVersion(); - - /** - * return the state of conductor. - */ - CONDUCTOR_STATE getConductorState(); - - /** - * Setter. - * @param conductorState state - */ - void setConductorState(CONDUCTOR_STATE conductorState); - - /** - * terminates owned connection. - * @return future result of disconnect action - */ - Future disconnect(); - - /** - * assign corresponding {@link SessionContext} to this conductor (to handle disconnect caused by switch). - * @param context session context - */ - void setSessionContext(SessionContext context); - - /** - * assign corresponding {@link org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher} - * to this conductor to handle disconnect caused by switch. This involves auxiliary conductors only. - * @param auxiliaryKey key - */ - void setConnectionCookie(SwitchConnectionDistinguisher auxiliaryKey); - - /** - * return the sessionContext. - */ - SessionContext getSessionContext(); - - /** - * return the auxiliaryKey (null if this is a primary connection). - */ - SwitchConnectionDistinguisher getAuxiliaryKey(); - - /** - * return the connectionAdapter. - */ - ConnectionAdapter getConnectionAdapter(); - - /** - * assign global queueKeeper. - * @param queueKeeper keeper - */ - void setQueueProcessor(QueueProcessor queueKeeper); - - /** - * Setter. - * @param errorHandler for internal exception handling - */ - void setErrorHandler(ErrorHandler errorHandler); - - /** - * Setter. - * @param conductorId id - */ - void setId(int conductorId); - -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/ErrorHandler.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/ErrorHandler.java index 6f930d7cc2..d5480b2c04 100644 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/ErrorHandler.java +++ b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/ErrorHandler.java @@ -7,15 +7,12 @@ */ package org.opendaylight.openflowplugin.api.openflow.md.core; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; - public interface ErrorHandler { /** * Exception handler. * @param throwable cause - * @param sessionContext of source */ - void handleException(Throwable throwable, SessionContext sessionContext); + void handleException(Throwable throwable); } diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/IMDMessageTranslator.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/IMDMessageTranslator.java deleted file mode 100644 index d03f20d1c9..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/IMDMessageTranslator.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.api.openflow.md.core; - -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; - -/** - * translates between messages. - * @param source message type (IN) - * @param result message type (OUT) - */ -public interface IMDMessageTranslator { - - /** - * This method is called in order to translate message to MD-SAL or from MD-SAL. - * @param cookie auxiliary connection identifier - * @param sc The SessionContext which sent the OF message - * @param msg The OF message - * @return translated message - */ - O translate(SwitchConnectionDistinguisher cookie, SessionContext sc, I msg); - -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/NotificationEnqueuer.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/NotificationEnqueuer.java deleted file mode 100644 index 69a83e0e77..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/NotificationEnqueuer.java +++ /dev/null @@ -1,21 +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.api.openflow.md.core; - -/** - * provider of wrapped notification enqueue. - */ -public interface NotificationEnqueuer { - - /** - * enqueue given notification into standard message processing queue. - * @param notification notification - */ - void enqueueNotification(NotificationQueueWrapper notification); - -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/NotificationQueueWrapper.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/NotificationQueueWrapper.java deleted file mode 100644 index 6d50a22859..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/NotificationQueueWrapper.java +++ /dev/null @@ -1,63 +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.api.openflow.md.core; - -import com.google.common.base.Preconditions; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.binding.Notification; - -public class NotificationQueueWrapper implements OfHeader { - - private final Notification notification; - private final Short version; - private Long xid = -1L; - - - /** - * Notofication queue wrapper. - * @param notification notofication - * @param version version - */ - public NotificationQueueWrapper(final Notification notification, final Short version) { - Preconditions.checkArgument(notification != null, "wrapped notification must not be null"); - Preconditions.checkArgument(version != null, "message version of wrapped notification must not be null"); - this.notification = notification; - this.version = version; - } - - @Override - public Class getImplementedInterface() { - return NotificationQueueWrapper.class; - } - - @Override - public Short getVersion() { - return version; - } - - @Override - public Long getXid() { - return xid; - } - - /** - * return the notification. - */ - public Notification getNotification() { - return notification; - } - - /** - * Setter. - * @param xid the xid to set - */ - public void setXid(Long xid) { - this.xid = xid; - } -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/SwitchConnectionDistinguisher.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/SwitchConnectionDistinguisher.java deleted file mode 100644 index 6537711af9..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/SwitchConnectionDistinguisher.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.api.openflow.md.core; - -public interface SwitchConnectionDistinguisher { - - /** - * Getter. - * @return encoded switch session identifier - */ - long getCookie(); - -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/sal/NotificationComposer.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/sal/NotificationComposer.java deleted file mode 100644 index f3c92c8e23..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/sal/NotificationComposer.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.api.openflow.md.core.sal; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yangtools.yang.binding.Notification; - -/** - * Notification composer. - * @param type of notification - */ -public interface NotificationComposer { - - /** - * Compose. - * @param xid corresponding OF transaction id - * @return notification instance - */ - N compose(TransactionId xid); -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/IMessageDispatchService.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/IMessageDispatchService.java deleted file mode 100644 index 8c4ab49d20..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/IMessageDispatchService.java +++ /dev/null @@ -1,244 +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.api.openflow.md.core.session; - -import java.util.concurrent.Future; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetAsyncInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutput; -import org.opendaylight.yangtools.yang.common.RpcResult; - -/** - * Message Dispatch Service to send the message to switch. - */ -public interface IMessageDispatchService { - - String CONNECTION_ERROR_MESSAGE = "Session for the cookie is invalid. Reason: " - + "the switch has been recently disconnected OR inventory provides outdated information."; - - /** - * send barrier message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> barrier(BarrierInput input, SwitchConnectionDistinguisher cookie); - - /** - * send experimenter message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> experimenter(ExperimenterInput input, SwitchConnectionDistinguisher cookie); - - /** - * send flow modification message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> flowMod(FlowModInput input, SwitchConnectionDistinguisher cookie); - - /** - * send get async message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> getAsync(GetAsyncInput input, SwitchConnectionDistinguisher cookie); - - /** - * send get config message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> getConfig(GetConfigInput input, SwitchConnectionDistinguisher cookie); - - /** - * send get features message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> getFeatures(GetFeaturesInput input, SwitchConnectionDistinguisher cookie); - - /** - * send get queue config message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> getQueueConfig(GetQueueConfigInput input, - SwitchConnectionDistinguisher cookie); - - /** - * send group modification message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> groupMod(GroupModInput input, SwitchConnectionDistinguisher cookie); - - /** - * send meter modification message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> meterMod(MeterModInput input, SwitchConnectionDistinguisher cookie); - - /** - * send multipart request message to switch. - * - * @param input - * - multipart request message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> multipartRequest( - MultipartRequestInput input, - SwitchConnectionDistinguisher cookie); - - /** - * send packet out message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> packetOut(PacketOutInput input, SwitchConnectionDistinguisher cookie); - - /** - * send port modification message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> portMod(PortModInput input, SwitchConnectionDistinguisher cookie); - - /** - * send role request message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> roleRequest(RoleRequestInput input, SwitchConnectionDistinguisher cookie); - - /** - * send set async message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> setAsync(SetAsyncInput input, SwitchConnectionDistinguisher cookie); - - /** - * send set config message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> setConfig(SetConfigInput input, SwitchConnectionDistinguisher cookie); - - /** - * send table modification message to switch. - * - * @param input - * - message - * @param cookie - * - to identify connection if null then feel free to send via - * any connection - * @return - the future - */ - Future> tableMod(TableModInput input, SwitchConnectionDistinguisher cookie); - -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SessionContext.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SessionContext.java deleted file mode 100644 index 6413bc9801..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SessionContext.java +++ /dev/null @@ -1,195 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.api.openflow.md.core.session; - -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ControllerRole; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping; - -public interface SessionContext { - - /** - * return primary connection wrapper. - */ - ConnectionConductor getPrimaryConductor(); - - /** - * return the features of corresponding switch. - */ - GetFeaturesOutput getFeatures(); - - /** - * Auxiliary connections. - * @param auxiliaryKey key under which the auxiliary conductor is stored - * @return list of auxiliary connection wrappers - */ - ConnectionConductor getAuxiliaryConductor( - SwitchConnectionDistinguisher auxiliaryKey); - - /** - * return entries of all auxiliary connections wrapped in conductors in this session. - */ - Set> getAuxiliaryConductors(); - - /** - * register new auxiliary connection wrapped in {@link ConnectionConductor}. - * - * @param auxiliaryKey key - * @param conductor connection conductor - */ - void addAuxiliaryConductor(SwitchConnectionDistinguisher auxiliaryKey, - ConnectionConductor conductor); - - /** - * Remove conductor. - * @param connectionCookie cookie - * @return removed connectionConductor - */ - ConnectionConductor removeAuxiliaryConductor( - SwitchConnectionDistinguisher connectionCookie); - - /** - * return true if this session is valid. - */ - boolean isValid(); - - /** - * Setter. - * @param valid the valid to set - */ - void setValid(boolean valid); - - /** - * return the sessionKey. - */ - SwitchSessionKeyOF getSessionKey(); - - /** - * Returns a map containing all OFPhysicalPorts of this switch. - * - * @return The Map of OFPhysicalPort - */ - @Deprecated - Map getPhysicalPorts(); - - /** - * Returns a map containing all bandwidths for all OFPorts of this switch. - * - * @return The Map of bandwidths for all OFPorts - */ - @Deprecated - Map getPortsBandwidth(); - - /** - * Returns a Set containing all port IDs of this switch. - * - * @return The Set of port ID - */ - @Deprecated - Set getPorts(); - - /** - * Returns OFPhysicalPort of the specified portNumber of this switch. - * - * @param portNumber The port ID - * @return OFPhysicalPort for the specified PortNumber - */ - PortGrouping getPhysicalPort(Long portNumber); - - /** - * Returns the bandwidth of the specified portNumber of this switch. - * - * @param portNumber the port ID - * @return bandwidth - */ - Boolean getPortBandwidth(Long portNumber); - - /** - * Returns True if the port is enabled. - * - * @param portNumber port number - * @return True if the port is enabled - */ - boolean isPortEnabled(long portNumber); - - /** - * Returns True if the port is enabled. - * - * @param port port - * @return True if the port is enabled - */ - boolean isPortEnabled(PortGrouping port); - - /** - * Returns a list containing all enabled ports of this switch. - * - * @return List containing all enabled ports of this switch - */ - List getEnabledPorts(); - - // TODO:: add listeners here, manager will set them and conductor use them - - /** - * get message dispatch service to send the message to switch. - * - * @return the message service - */ - IMessageDispatchService getMessageDispatchService(); - - /** - * return the unique xid for this session. - * @return xid - */ - Long getNextXid(); - - /** - * Setter. - * @param registration provider composite registration - */ - void setProviderRegistration(ModelDrivenSwitchRegistration registration); - - /** - * return provider composite registration. - * @return ModelDrivenSwitchRegistration - */ - ModelDrivenSwitchRegistration getProviderRegistration(); - - /** - * return seed value for random operations. - * @return int - */ - int getSeed(); - - /** - * return (wrapped) notification enqueue service - {@link NotificationQueueWrapper}. - * @return NotificationEnqueuer - */ - NotificationEnqueuer getNotificationEnqueuer(); - - /** - * Setter. - * @param roleOnDevice role - */ - void setRoleOnDevice(ControllerRole roleOnDevice); - - /** - * return actual role. - * @return role - */ - ControllerRole getRoleOnDevice(); -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SessionListener.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SessionListener.java deleted file mode 100644 index 9795a8a669..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SessionListener.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.api.openflow.md.core.session; - -import java.util.EventListener; - -/** - * listens on session changes. - */ -public interface SessionListener extends EventListener { - - /** - * fired upon session added. - * @param sessionKey session key - * @param context context - */ - void onSessionAdded(SwitchSessionKeyOF sessionKey, SessionContext context); - - /** - * fired upon session removed. - * @param context context - */ - void onSessionRemoved(SessionContext context); - - void setRole(SessionContext context); - -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SessionManager.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SessionManager.java deleted file mode 100644 index 89456c1b74..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SessionManager.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.api.openflow.md.core.session; - -import com.google.common.util.concurrent.ListeningExecutorService; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey; -import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.binding.DataObject; - -public interface SessionManager extends AutoCloseable { - - /** - * primary connection. - * @param sessionKey session key - * @return corresponding conductor, holding {@link ConnectionAdapter} to - */ - SessionContext getSessionContext(SwitchSessionKeyOF sessionKey); - - /** - * disconnect all underlying {@link ConnectionAdapter}s and notify listeners. - * - * @param sessionKey session key - */ - void invalidateSessionContext(SwitchSessionKeyOF sessionKey); - - /** - * register session context. - * - * @param sessionKey session key - * @param context context - */ - void addSessionContext(SwitchSessionKeyOF sessionKey, SessionContext context); - - void setRole(SessionContext context); - - /** - * disconnect particular auxiliary {@link ConnectionAdapter}, identified by - * sessionKey and connectionCookie. - * - * @param sessionKey session key - * @param connectionCookie cookie - */ - void invalidateAuxiliary(SwitchSessionKeyOF sessionKey, - SwitchConnectionDistinguisher connectionCookie); - - /** - * Invalidate on disconnect. - * @param connectionConductor connection conductor. - */ - void invalidateOnDisconnect(ConnectionConductor connectionConductor); - - /** - * Setter. - * @param translatorMapping translators - */ - void setTranslatorMapping( - Map>>> translatorMapping); - - /** - * Getter. - * @return translator mapping - */ - Map>>> getTranslatorMapping(); - - /** - * Setter. - * @param notificationProviderService notofication provider - */ - void setNotificationProviderService(NotificationProviderService notificationProviderService); - - /** - * Getter. - * @return notificationServiceProvider - */ - DataBroker getDataBroker(); - - /** - * Setter. - * @param dataBroker databroker - */ - void setDataBroker(DataBroker dataBroker); - - /** - * Gatter. - * @return notificationServiceProvider - */ - NotificationProviderService getNotificationProviderService(); - - /** - * Session listener registration. - * @param listener listener - * @return registration - */ - ListenerRegistration registerSessionListener(SessionListener listener); - - /** - * Getter. - * @return popListener mapping, key=message type; value=collection of listeners - */ - Map, Collection>> getPopListenerMapping(); - - /** - * Setter. - * @param popListenerMapping the popListenerMapping to set - */ - void setPopListenerMapping( - Map, Collection>> popListenerMapping); - - /** - * Setter. - * @param rpcPoolDelegator rpc pool delegator - */ - void setRpcPool(ListeningExecutorService rpcPoolDelegator); - - /** - * Getter. - * @return the rpcPool instance - */ - ListeningExecutorService getRpcPool(); - - /** - * Setter. - * @param messageSpy message spy - */ - void setMessageSpy(MessageSpy messageSpy); - - /** - * Getter. - * @return the messageSpy - */ - MessageSpy getMessageSpy(); - - /** - * Getter. - * @return collection of current sessions - */ - Collection getAllSessions(); -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SwitchSessionKeyOF.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SwitchSessionKeyOF.java deleted file mode 100644 index 2a54db0841..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/core/session/SwitchSessionKeyOF.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.api.openflow.md.core.session; - -import java.math.BigInteger; - -public class SwitchSessionKeyOF { - - private BigInteger datapathId; - - /** - * default ctor. - */ - public SwitchSessionKeyOF() { - // NOOP - } - - /** - * Setter. - * @param datapathId the datapathId to set - */ - public void setDatapathId(BigInteger datapathId) { - this.datapathId = datapathId; - } - - /** - * Getter. - * @return the datapathId - */ - public byte[] getId() { - return datapathId.toByteArray(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((datapathId == null) ? 0 : datapathId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - SwitchSessionKeyOF other = (SwitchSessionKeyOF) obj; - if (datapathId == null) { - if (other.datapathId != null) { - return false; - } - } else if (!datapathId.equals(other.datapathId)) { - return false; - } - return true; - } -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/Enqueuer.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/Enqueuer.java deleted file mode 100644 index 38a49d1e2b..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/Enqueuer.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.api.openflow.md.queue; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; - -/** - * Enqueuer. - * @param type of queue items (IN) - */ -public interface Enqueuer { - - /** - * item to be enqueued. - * @param queueItem item to be enqueued - */ - void enqueueQueueItem(I queueItem); - - /** - * for testing and comparing purposes - this strategy blocks netty threads. - * @param queueItem item - * @deprecated for testing and comparing purposes - this strategy blocks netty threads - */ - @Deprecated - void directProcessQueueItem(QueueItem queueItem); -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/HarvesterHandle.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/HarvesterHandle.java deleted file mode 100644 index ec93933d5f..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/HarvesterHandle.java +++ /dev/null @@ -1,20 +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.api.openflow.md.queue; - -/** - * message harvester simple control. - */ -public interface HarvesterHandle { - - /** - * wakeup harvester in case it is in phase of starving sleep. - */ - void ping(); - -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/MessageSourcePollRegistrator.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/MessageSourcePollRegistrator.java deleted file mode 100644 index 87a71f3e5f..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/MessageSourcePollRegistrator.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.api.openflow.md.queue; - -import java.util.Collection; - -/** - * MessageSourcePollRegistrator. - * @param message wrapping type (IN) - * - */ -public interface MessageSourcePollRegistrator { - - /** - * Message source to read from during processing. - * @param messageSource to read from during processing - * @return closeable registration - */ - AutoCloseable registerMessageSource(I messageSource); - - /** - * Unregister message source. - * @param messageSource to be unregistered - * @return true if successfully unregistered - */ - boolean unregisterMessageSource(I messageSource); - - /** - * Getter. - * @return collection of registered message sources - */ - Collection getMessageSources(); - - /** - * Getter. - * @return the harvest handle - */ - HarvesterHandle getHarvesterHandle(); -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/PopListener.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/PopListener.java deleted file mode 100644 index da3c4675c6..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/PopListener.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.api.openflow.md.queue; - - -/** - * PopListener. - * @param result type - * - */ -public interface PopListener { - void onPop(T processedMessage); -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/QueueItem.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/QueueItem.java deleted file mode 100644 index 96f3b38e8a..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/QueueItem.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.api.openflow.md.queue; - -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; - -/** - * Queue item. - * @param input message type (IN) - */ -public interface QueueItem { - - /** - * Getter. - * @return wrapped message - */ - I getMessage(); - - /** - * Getter. - * @return conductor the message arrived to - */ - ConnectionConductor getConnectionConductor(); - - /** - * Getter. - * @return queue type associated to this item - */ - QueueKeeper.QueueType getQueueType(); -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/QueueKeeper.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/QueueKeeper.java deleted file mode 100644 index 4fc3ff3a25..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/QueueKeeper.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.api.openflow.md.queue; - -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; - -/** - * This processing mechanism based on queue. Processing consists of 2 steps: translate and publish. - * Proposed workflow (might slightly deviate in implementations): - *
    - *
  1. messages of input type are pushed in (via {@link QueueKeeper} and similar)
  2. - *
  3. ticket (executable task) is build upon each pushed message and enqueued
  4. - *
  5. ticket is translated using appropriate translator
  6. - *
  7. ticket is dequeued and result is published by appropriate popListener
  8. - *
- * Message order might be not important, e.g. when speed is of the essence - * @param source type (IN) - */ -public interface QueueKeeper extends AutoCloseable { - - /** type of message enqueue. */ - enum QueueType { - /** ordered processing. */ - DEFAULT, - /** unordered processing - bypass fair processing. */ - UNORDERED - } - - /** - * enqueue message for processing. - * @param message message - * @param conductor source of message - * @param queueType - {@link QueueType#DEFAULT} if message order matters, {@link QueueType#UNORDERED} otherwise - */ - void push(I message, ConnectionConductor conductor, QueueType queueType); - - /** - * oldest item from queue - if available and remove it from queue. - * @return oldest item from queue - */ - QueueItem poll(); - - /** - * Setter. - * @param processingRegistration the processingRegistration to set (in order to provide close method) - */ - void setPollRegistration(AutoCloseable processingRegistration); -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/QueueProcessor.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/QueueProcessor.java deleted file mode 100644 index e2dc95e695..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/QueueProcessor.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.api.openflow.md.queue; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey; - -/** - * This processing mechanism based on queue. Processing consists of 2 steps: translate and publish. - * Proposed workflow (might slightly deviate in implementations): - *
    - *
  1. messages of input type are pushed in (via {@link QueueKeeper and similar})
  2. - *
  3. ticket (executable task) is build upon each pushed message and enqueued
  4. - *
  5. ticket is translated using appropriate translator
  6. - *
  7. ticket is dequeued and result is published by appropriate popListener
  8. - *
- * Message order might be not important, e.g. when speed is of the essence - * @param source type (IN) - * @param result type (OUT) - */ -public interface QueueProcessor extends MessageSourcePollRegistrator>, Enqueuer> { - - /** - * translators for message processing. - * @param translatorMapping translators for message processing - */ - void setTranslatorMapping(Map>>> translatorMapping); - - /** - * listeners invoked when processing done. - * @param popListenersMapping listeners invoked when processing done - */ - void setPopListenersMapping(Map, Collection>> popListenersMapping); -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/WaterMarkListener.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/WaterMarkListener.java deleted file mode 100644 index 5c56516bd6..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/WaterMarkListener.java +++ /dev/null @@ -1,22 +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.api.openflow.md.queue; - -public interface WaterMarkListener { - - /** - * When HighWaterMark reached and currently not flooded. - */ - void onHighWaterMark(); - - /** - * When LowWaterMark reached and currently flooded. - */ - void onLowWaterMark(); -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/WaterMarkListenerImpl.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/WaterMarkListenerImpl.java deleted file mode 100644 index d39e7acd0b..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/queue/WaterMarkListenerImpl.java +++ /dev/null @@ -1,52 +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.api.openflow.md.queue; - -import com.google.common.base.Preconditions; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class WaterMarkListenerImpl implements WaterMarkListener { - - private static final Logger LOG = LoggerFactory - .getLogger(WaterMarkListenerImpl.class); - - private ConnectionAdapter connectionAdapter; - - public WaterMarkListenerImpl(ConnectionAdapter connectionAdapter) { - this.connectionAdapter = Preconditions.checkNotNull(connectionAdapter); - } - - /* - * (non-Javadoc) - * - * @see org.opendaylight.openflowplugin.api.openflow.md.queue.QueueListener# - * onHighWaterMark - * (org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter) - */ - @Override - public void onHighWaterMark() { - connectionAdapter.setAutoRead(false); - LOG.debug("AutoRead is set on false: {}", connectionAdapter.getRemoteAddress()); - } - - /* - * (non-Javadoc) - * - * @see org.opendaylight.openflowplugin.api.openflow.md.queue.QueueListener# - * onLowWaterMark - * (org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter) - */ - @Override - public void onLowWaterMark() { - connectionAdapter.setAutoRead(true); - LOG.debug("AutoRead is set on true: {}", connectionAdapter.getRemoteAddress()); - } -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/util/PollableQueuesPriorityZipper.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/util/PollableQueuesPriorityZipper.java deleted file mode 100644 index 55ca10a570..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/util/PollableQueuesPriorityZipper.java +++ /dev/null @@ -1,57 +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.api.openflow.md.util; - -import java.util.Queue; - -/** - * Zipper groups together a list of queues and exposes one poll method. Polling - * iterates through all groups and returns first not-null result of poll method - * on each queue. If after polling each grouped queue for one time there is - * still null result, poll will return null.
- * Iterating keeps last position so this polling is supposed to be fairly - * distributed. - * - * @param common item type of zipped queues - */ -public class PollableQueuesPriorityZipper { - - private Queue prioritizedSource; - private PollableQueuesZipper zipper; - - public PollableQueuesPriorityZipper() { - zipper = new PollableQueuesZipper<>(); - } - - /** - * Add all member queues before first invocation of {@link PollableQueuesPriorityZipper#poll()}. - * @param queue to be added to group - */ - public void addSource(Queue queue) { - zipper.addSource(queue); - } - - /** - * Next common product. - * @return next common product of polling member groups - */ - public T poll() { - T item = null; - - item = prioritizedSource.poll(); - if (item == null) { - item = zipper.poll(); - } - - return item; - } - - public void setPrioritizedSource(Queue prioritizedSource) { - this.prioritizedSource = prioritizedSource; - } -} diff --git a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/util/PollableQueuesZipper.java b/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/util/PollableQueuesZipper.java deleted file mode 100644 index c6aca0ef86..0000000000 --- a/openflowplugin-api/src/main/java/org/opendaylight/openflowplugin/api/openflow/md/util/PollableQueuesZipper.java +++ /dev/null @@ -1,63 +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.api.openflow.md.util; - -import com.google.common.collect.Iterators; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Queue; - -/** - * Zipper groups together a list of queues and exposes one poll method. Polling iterates through - * all groups and returns first not-null result of poll method on each queue. If after polling each - * grouped queue for one time there is still null result, poll will return null. - *
- * Iterating keeps last position so this polling is supposed to be fairly distributed. - * - * @param common item type of zipped queues - */ -public class PollableQueuesZipper { - - private List> sources; - private Iterator> cursor; - - public PollableQueuesZipper() { - sources = new ArrayList<>(); - } - - /** - * Add all member queues before first invocation of {@link PollableQueuesZipper#poll()}. - * @param queue to be added to group - */ - public void addSource(Queue queue) { - sources.add(queue); - } - - /** - * Next common product. - * @return next common product of polling member groups - */ - public T poll() { - T item = null; - if (cursor == null) { - cursor = Iterators.cycle(sources); - } - - Queue queue; - for (int i = 0; i < sources.size(); i++) { - queue = cursor.next(); - item = queue.poll(); - if (item != null) { - break; - } - } - - return item; - } -} diff --git a/openflowplugin-api/src/main/resources/org/opendaylight/blueprint/openflowplugin-api.xml b/openflowplugin-api/src/main/resources/org/opendaylight/blueprint/openflowplugin-api.xml deleted file mode 100644 index 8b9bbd4942..0000000000 --- a/openflowplugin-api/src/main/resources/org/opendaylight/blueprint/openflowplugin-api.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - diff --git a/openflowplugin-impl/src/main/java/org/opendaylight/openflowplugin/impl/connection/ConnectionManagerImpl.java b/openflowplugin-impl/src/main/java/org/opendaylight/openflowplugin/impl/connection/ConnectionManagerImpl.java index e1fb42fb76..a97b44837b 100644 --- a/openflowplugin-impl/src/main/java/org/opendaylight/openflowplugin/impl/connection/ConnectionManagerImpl.java +++ b/openflowplugin-impl/src/main/java/org/opendaylight/openflowplugin/impl/connection/ConnectionManagerImpl.java @@ -12,12 +12,12 @@ import java.net.InetAddress; import java.util.concurrent.ThreadPoolExecutor; import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener; +import org.opendaylight.openflowplugin.api.OFConstants; import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext; import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionManager; import org.opendaylight.openflowplugin.api.openflow.connection.HandshakeContext; import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceConnectedHandler; import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceDisconnectedHandler; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeListener; import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeManager; import org.opendaylight.openflowplugin.impl.connection.listener.ConnectionReadyListenerImpl; @@ -82,8 +82,8 @@ public class ConnectionManagerImpl implements ConnectionManager { private HandshakeManager createHandshakeManager(final ConnectionAdapter connectionAdapter, final HandshakeListener handshakeListener) { HandshakeManagerImpl handshakeManager = new HandshakeManagerImpl(connectionAdapter, - ConnectionConductor.VERSION_ORDER.get(0), - ConnectionConductor.VERSION_ORDER); + OFConstants.VERSION_ORDER.get(0), + OFConstants.VERSION_ORDER); handshakeManager.setUseVersionBitmap(BITMAP_NEGOTIATION_ENABLED); handshakeManager.setHandshakeListener(handshakeListener); handshakeManager.setErrorHandler(new ErrorHandlerSimpleImpl()); diff --git a/openflowplugin-impl/src/main/resources/org/opendaylight/blueprint/openflowplugin-impl.xml b/openflowplugin-impl/src/main/resources/org/opendaylight/blueprint/openflowplugin-impl.xml index c4bde35aca..d6e37a2095 100644 --- a/openflowplugin-impl/src/main/resources/org/opendaylight/blueprint/openflowplugin-impl.xml +++ b/openflowplugin-impl/src/main/resources/org/opendaylight/blueprint/openflowplugin-impl.xml @@ -3,6 +3,8 @@ xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0" odl:use-default-for-reference-types="true"> + + diff --git a/openflowplugin/pom.xml b/openflowplugin/pom.xml index 1bebdfaf66..17d8ea5d66 100644 --- a/openflowplugin/pom.xml +++ b/openflowplugin/pom.xml @@ -17,40 +17,6 @@ org.apache.felix maven-bundle-plugin - - org.opendaylight.yangtools - yang-maven-plugin - - - - generate-sources - - - - - - org.opendaylight.mdsal.binding.maven.api.gen.plugin.CodeGeneratorImpl - - ${project.build.directory}/generated-sources/sal - - - org.opendaylight.mdsal.binding.yang.unified.doc.generator.maven.DocumentationGeneratorImpl - ${project.build.directory}/site/models - - - true - - - - - - org.opendaylight.mdsal - maven-sal-api-gen-plugin - ${mdsal.model.version} - jar - - - diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/ConnectionConductorFactory.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/ConnectionConductorFactory.java deleted file mode 100644 index 26e6e77224..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/ConnectionConductorFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core; - -import java.util.concurrent.atomic.AtomicInteger; - -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.DataObject; - -/** - * @author mirehak - * - */ -public final class ConnectionConductorFactory { - - private static AtomicInteger conductorId = new AtomicInteger(); - - private ConnectionConductorFactory() { - throw new UnsupportedOperationException(); - } - - /** - * @param connectionAdapter connection conductor adaptor - * @param queueProcessor message queue process - * @return conductor for given connection - */ - public static ConnectionConductor createConductor(ConnectionAdapter connectionAdapter, - QueueProcessor queueProcessor) { - ConnectionConductor connectionConductor = new ConnectionConductorImpl(connectionAdapter); - connectionConductor.setQueueProcessor(queueProcessor); - connectionConductor.setId(conductorId.getAndIncrement()); - connectionConductor.init(); - return connectionConductor; - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/ConnectionConductorImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/ConnectionConductorImpl.java deleted file mode 100644 index 3b4d6bafbd..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/ConnectionConductorImpl.java +++ /dev/null @@ -1,551 +0,0 @@ -/** - * Copyright (c) 2013, 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.openflow.md.core; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.util.concurrent.Futures; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.connection.HandshakeContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler; -import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeListener; -import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeManager; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper.QueueType; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor; -import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListener; -import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListenerImpl; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil; -import org.opendaylight.openflowplugin.openflow.md.core.session.PortFeaturesUtil; -import org.opendaylight.openflowplugin.openflow.md.queue.QueueKeeperFactory; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatus; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author mirehak - */ -public class ConnectionConductorImpl implements OpenflowProtocolListener, - SystemNotificationsListener, ConnectionConductor, - ConnectionReadyListener, HandshakeListener, NotificationEnqueuer, - AutoCloseable { - - /** - * ingress queue limit - */ - private static final int INGRESS_QUEUE_MAX_SIZE = 200; - - protected static final Logger LOG = LoggerFactory - .getLogger(ConnectionConductorImpl.class); - - /* - * variable to make BitMap-based negotiation enabled / disabled. it will - * help while testing and isolating issues related to processing of BitMaps - * from switches. - */ - private boolean isBitmapNegotiationEnable = true; - protected ErrorHandler errorHandler; - - private final ConnectionAdapter connectionAdapter; - private ConnectionConductor.CONDUCTOR_STATE conductorState; - private Short version; - - protected SwitchConnectionDistinguisher auxiliaryKey; - - protected SessionContext sessionContext; - - private QueueProcessor queueProcessor; - private QueueKeeper queue; - private ThreadPoolExecutor hsPool; - private HandshakeManager handshakeManager; - - private boolean firstHelloProcessed; - - private PortFeaturesUtil portFeaturesUtils; - - private int conductorId; - - private int ingressMaxQueueSize; - private HandshakeContext handshakeContext; - - /** - * @param connectionAdapter connection adaptor for switch - */ - public ConnectionConductorImpl(ConnectionAdapter connectionAdapter) { - this(connectionAdapter, INGRESS_QUEUE_MAX_SIZE); - } - - /** - * @param connectionAdapter connection adaptor for switch - * @param ingressMaxQueueSize ingress queue limit (blocking) - */ - public ConnectionConductorImpl(ConnectionAdapter connectionAdapter, - int ingressMaxQueueSize) { - this.connectionAdapter = connectionAdapter; - this.ingressMaxQueueSize = ingressMaxQueueSize; - conductorState = CONDUCTOR_STATE.HANDSHAKING; - firstHelloProcessed = false; - handshakeManager = new HandshakeManagerImpl(connectionAdapter, - ConnectionConductor.VERSION_ORDER.get(0), - ConnectionConductor.VERSION_ORDER); - handshakeManager.setUseVersionBitmap(isBitmapNegotiationEnable); - handshakeManager.setHandshakeListener(this); - portFeaturesUtils = PortFeaturesUtil.getInstance(); - } - - @Override - public void init() { - int handshakeThreadLimit = 1; - hsPool = new ThreadPoolLoggingExecutor(handshakeThreadLimit, - handshakeThreadLimit, 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue(), "OFHandshake-" - + conductorId); - - connectionAdapter.setMessageListener(this); - connectionAdapter.setSystemListener(this); - connectionAdapter.setConnectionReadyListener(this); - WaterMarkListener waterMarkListener = new WaterMarkListenerImpl( - connectionAdapter); - queue = QueueKeeperFactory.createFairQueueKeeper(queueProcessor, - ingressMaxQueueSize, waterMarkListener); - } - - @Override - public void setQueueProcessor( - QueueProcessor queueProcessor) { - this.queueProcessor = queueProcessor; - } - - /** - * @param errorHandler the errorHandler to set - */ - @Override - public void setErrorHandler(ErrorHandler errorHandler) { - this.errorHandler = errorHandler; - handshakeManager.setErrorHandler(errorHandler); - } - - @Override - public void onEchoRequestMessage(final EchoRequestMessage echoRequestMessage) { - new Thread(new Runnable() { - @Override - public void run() { - LOG.debug("echo request received: " - + echoRequestMessage.getXid()); - EchoReplyInputBuilder builder = new EchoReplyInputBuilder(); - builder.setVersion(echoRequestMessage.getVersion()); - builder.setXid(echoRequestMessage.getXid()); - builder.setData(echoRequestMessage.getData()); - - getConnectionAdapter().echoReply(builder.build()); - } - }).start(); - } - - @Override - public void onErrorMessage(ErrorMessage errorMessage) { - enqueueMessage(errorMessage); - } - - /** - * @param message - */ - private void enqueueMessage(OfHeader message) { - enqueueMessage(message, QueueType.DEFAULT); - } - - @Override - public void enqueueNotification(NotificationQueueWrapper notification) { - enqueueMessage(notification); - } - - /** - * @param message - * @param queueType enqueue type - */ - private void enqueueMessage(OfHeader message, QueueType queueType) { - queue.push(message, this, queueType); - } - - @Override - public void onExperimenterMessage(ExperimenterMessage experimenterMessage) { - enqueueMessage(experimenterMessage); - } - - @Override - public void onFlowRemovedMessage(FlowRemovedMessage message) { - enqueueMessage(message); - } - - /** - * version negotiation happened as per following steps: 1. If HelloMessage - * version field has same version, continue connection processing. If - * HelloMessage version is lower than supported versions, just disconnect. - * 2. If HelloMessage contains bitmap and common version found in bitmap - * then continue connection processing. if no common version found, just - * disconnect. 3. If HelloMessage version is not supported, send - * HelloMessage with lower supported version. 4. If Hello message received - * again with not supported version, just disconnect. - */ - @Override - public void onHelloMessage(final HelloMessage hello) { - LOG.debug("processing HELLO.xid: {}", hello.getXid()); - firstHelloProcessed = true; - checkState(CONDUCTOR_STATE.HANDSHAKING); - HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper( - hello, handshakeManager, connectionAdapter); - hsPool.submit(handshakeStepWrapper); - } - - /** - * @return rpc-response timeout in [ms] - */ - protected long getMaxTimeout() { - // TODO:: get from configuration - return 2000; - } - - /** - * @return milliseconds - */ - protected TimeUnit getMaxTimeoutUnit() { - // TODO:: get from configuration - return TimeUnit.MILLISECONDS; - } - - @Override - public void onMultipartReplyMessage(MultipartReplyMessage message) { - enqueueMessage(message); - } - - @Override - public void onPacketInMessage(PacketInMessage message) { - enqueueMessage(message, QueueKeeper.QueueType.UNORDERED); - } - - @Override - public void onPortStatusMessage(PortStatusMessage message) { - try { - processPortStatusMsg(message); - } finally { - enqueueMessage(message); - } - } - - protected void processPortStatusMsg(PortStatus msg) { - if (msg.getReason().getIntValue() == 2) { - updatePort(msg); - } else if (msg.getReason().getIntValue() == 0) { - updatePort(msg); - } else if (msg.getReason().getIntValue() == 1) { - deletePort(msg); - } - } - - protected void updatePort(PortStatus msg) { - Long portNumber = msg.getPortNo(); - Boolean portBandwidth = portFeaturesUtils.getPortBandwidth(msg); - - if (portBandwidth == null) { - LOG.debug( - "can't get bandwidth info from port: {}, aborting port update", - msg.toString()); - } else { - if (null != this.sessionContext) { - //FIXME these two properties are never used in code - this.getSessionContext().getPhysicalPorts().put(portNumber, msg); - this.getSessionContext().getPortsBandwidth() - .put(portNumber, portBandwidth); - } else { - LOG.warn("Trying to process update port message before session context was created."); - } - } - } - - protected void deletePort(PortGrouping port) { - Long portNumber = port.getPortNo(); - - this.getSessionContext().getPhysicalPorts().remove(portNumber); - this.getSessionContext().getPortsBandwidth().remove(portNumber); - } - - @Override - public void onSwitchIdleEvent(SwitchIdleEvent notification) { - new Thread(new Runnable() { - @Override - public void run() { - if (!CONDUCTOR_STATE.WORKING.equals(getConductorState())) { - // idle state in any other conductorState than WORKING means - // real - // problem and wont be handled by echoReply, but - // disconnection - disconnect(); - OFSessionUtil.getSessionManager().invalidateOnDisconnect( - ConnectionConductorImpl.this); - } else { - LOG.debug( - "first idle state occured, sessionCtx={}|auxId={}", - sessionContext, auxiliaryKey); - EchoInputBuilder builder = new EchoInputBuilder(); - builder.setVersion(getVersion()); - builder.setXid(getSessionContext().getNextXid()); - - Future> echoReplyFuture = getConnectionAdapter() - .echo(builder.build()); - - try { - RpcResult echoReplyValue = echoReplyFuture - .get(getMaxTimeout(), getMaxTimeoutUnit()); - if (echoReplyValue.isSuccessful()) { - setConductorState(CONDUCTOR_STATE.WORKING); - } else { - for (RpcError replyError : echoReplyValue - .getErrors()) { - Throwable cause = replyError.getCause(); - LOG.error( - "while receiving echoReply in TIMEOUTING state: " - + cause.getMessage(), cause); - } - // switch issue occurred - throw new Exception("switch issue occurred"); - } - } catch (Exception e) { - LOG.error("while waiting for echoReply in TIMEOUTING state: " - + e.getMessage()); - errorHandler.handleException(e, sessionContext); - // switch is not responding - disconnect(); - OFSessionUtil.getSessionManager() - .invalidateOnDisconnect( - ConnectionConductorImpl.this); - } - } - } - - }).start(); - } - - /** - * @param conductorState the connectionState to set - */ - @Override - public void setConductorState(CONDUCTOR_STATE conductorState) { - this.conductorState = conductorState; - } - - @Override - public CONDUCTOR_STATE getConductorState() { - return conductorState; - } - - /** - * @param expectedState connection conductor state - */ - protected void checkState(CONDUCTOR_STATE expectedState) { - if (!conductorState.equals(expectedState)) { - LOG.warn("State of connection to switch {} is not correct, " - + "terminating the connection", connectionAdapter.getRemoteAddress()); - throw new IllegalStateException("Expected state: " + expectedState - + ", actual state:" + conductorState); - } - } - - @Override - public void onDisconnectEvent(DisconnectEvent arg0) { - SessionManager sessionManager = OFSessionUtil.getSessionManager(); - sessionManager.invalidateOnDisconnect(this); - close(); - } - - @Override - public Short getVersion() { - return version; - } - - @Override - public Future disconnect() { - LOG.trace("disconnecting: sessionCtx={}|auxId={}", sessionContext, - auxiliaryKey); - - Future result = null; - if (connectionAdapter.isAlive()) { - result = connectionAdapter.disconnect(); - } else { - LOG.debug("connection already disconnected"); - result = Futures.immediateFuture(true); - } - close(); - return result; - } - - @Override - public void setConnectionCookie(SwitchConnectionDistinguisher auxiliaryKey) { - this.auxiliaryKey = auxiliaryKey; - } - - @Override - public void setSessionContext(SessionContext sessionContext) { - this.sessionContext = sessionContext; - } - - @Override - public SwitchConnectionDistinguisher getAuxiliaryKey() { - return auxiliaryKey; - } - - @Override - public SessionContext getSessionContext() { - return sessionContext; - } - - @Override - public ConnectionAdapter getConnectionAdapter() { - return connectionAdapter; - } - - @Override - public void onConnectionReady() { - LOG.debug("connection is ready-to-use"); - if (!firstHelloProcessed) { - checkState(CONDUCTOR_STATE.HANDSHAKING); - HandshakeStepWrapper handshakeStepWrapper = new HandshakeStepWrapper( - null, handshakeManager, connectionAdapter); - hsPool.execute(handshakeStepWrapper); - firstHelloProcessed = true; - } else { - LOG.debug("already touched by hello message"); - } - } - - @Override - public void onHandshakeSuccessful(GetFeaturesOutput featureOutput, - Short negotiatedVersion) { - postHandshakeBasic(featureOutput, negotiatedVersion); - } - - @Override - public void onHandshakeFailure() { - LOG.info("OF handshake failed, doing cleanup."); - close(); - } - - /** - * used by tests - * - * @param featureOutput feature request output - * @param negotiatedVersion negotiated openflow connection version - */ - protected void postHandshakeBasic(GetFeaturesOutput featureOutput, - Short negotiatedVersion) { - version = negotiatedVersion; - if (version == OFConstants.OFP_VERSION_1_0) { - // Because the GetFeaturesOutput contains information about the port - // in OF1.0 (that we would otherwise get from the PortDesc) we have - // to pass - // it up for parsing to convert into a NodeConnectorUpdate - // - // BUG-1988 - this must be the first item in queue in order not to - // get behind link-up message - enqueueMessage(featureOutput); - } - - SessionContext sessionContext = OFSessionUtil.registerSession(this, featureOutput, negotiatedVersion); - hsPool.shutdown(); - hsPool.purge(); - conductorState = CONDUCTOR_STATE.WORKING; - QueueKeeperFactory.plugQueue(queueProcessor, queue); - } - - /** - * @param isBitmapNegotiationEnable the isBitmapNegotiationEnable to set - */ - public void setBitmapNegotiationEnable(boolean isBitmapNegotiationEnable) { - this.isBitmapNegotiationEnable = isBitmapNegotiationEnable; - } - - @Override - public void setId(int conductorId) { - this.conductorId = conductorId; - } - - @Override - public void close() { - conductorState = CONDUCTOR_STATE.RIP; - if (handshakeContext != null) { - try { - handshakeContext.close(); - } catch (Exception e) { - LOG.warn("Closing handshake context failed: {}", e.getMessage()); - LOG.debug("Detail in hanshake context close:", e); - } - } else { - //This condition will occure when Old Helium openflowplugin implementation will be used. - shutdownPoolPolitely(); - } - } - - private void shutdownPoolPolitely() { - LOG.debug("Terminating handshake pool for node {}", connectionAdapter.getRemoteAddress()); - hsPool.shutdown(); - try { - hsPool.awaitTermination(1, TimeUnit.SECONDS); - } catch (InterruptedException e) { - LOG.debug("Error while awaiting termination of pool. Will force shutdown now."); - } finally { - hsPool.purge(); - if (!hsPool.isTerminated()) { - hsPool.shutdownNow(); - } - LOG.debug("is handshake pool for node {} is terminated : {}", - connectionAdapter.getRemoteAddress(), hsPool.isTerminated()); - } - } - - @Override - public void setHandshakeContext(HandshakeContext handshakeContext) { - this.handshakeContext = handshakeContext; - } - - @VisibleForTesting - ThreadPoolExecutor getHsPool() { - return hsPool; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/ErrorHandlerSimpleImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/ErrorHandlerSimpleImpl.java index 645ee9bee3..282c2a08ea 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/ErrorHandlerSimpleImpl.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/ErrorHandlerSimpleImpl.java @@ -8,17 +8,13 @@ package org.opendaylight.openflowplugin.openflow.md.core; -import java.util.Arrays; - import org.opendaylight.openflowplugin.api.ConnectionException; import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * dumping all exceptions to log - * @author mirehak */ public class ErrorHandlerSimpleImpl implements ErrorHandler { @@ -26,16 +22,11 @@ public class ErrorHandlerSimpleImpl implements ErrorHandler { .getLogger(ErrorHandlerSimpleImpl.class); @Override - public void handleException(Throwable e, SessionContext sessionContext) { - String sessionKeyId = null; - if (sessionContext != null) { - sessionKeyId = Arrays.toString(sessionContext.getSessionKey().getId()); - } - + public void handleException(Throwable e) { if (e instanceof ConnectionException) { - LOG.warn("exception -> {}, session -> {}", e.getMessage(), sessionKeyId, e); + LOG.warn("exception -> {}", e.getMessage(), e); } else { - LOG.error("exception -> {}, session -> {}", e.getMessage(), sessionKeyId, e); + LOG.error("exception -> {}", e.getMessage(), e); } } } diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/HandshakeManagerImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/HandshakeManagerImpl.java index 785a568b4a..9392e8ee7e 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/HandshakeManagerImpl.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/HandshakeManagerImpl.java @@ -7,12 +7,16 @@ */ package org.opendaylight.openflowplugin.openflow.md.core; +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.JdkFutureAdapters; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.SettableFuture; import java.util.List; import java.util.Objects; import java.util.concurrent.Future; - import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; +import org.opendaylight.openflowplugin.api.OFConstants; import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler; import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeListener; import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeManager; @@ -26,16 +30,6 @@ import org.opendaylight.yangtools.yang.common.RpcResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.JdkFutureAdapters; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.SettableFuture; - -/** - * @author mirehak - * - */ public class HandshakeManagerImpl implements HandshakeManager { private static final long activeXID = 20L; @@ -118,7 +112,7 @@ public class HandshakeManagerImpl implements HandshakeManager { handleStepByStepVersionNegotiation(remoteVersion); } } catch (Exception ex) { - errorHandler.handleException(ex, null); + errorHandler.handleException(ex); LOG.trace("ret - shake fail - closing"); handshakeListener.onHandshakeFailure(); } @@ -144,7 +138,7 @@ public class HandshakeManagerImpl implements HandshakeManager { try { stepByStepVersionSubStep(remoteVersion, lastProposedVersion); } catch (Exception e) { - errorHandler.handleException(e, null); + errorHandler.handleException(e); handshakeListener.onHandshakeFailure(); } } @@ -267,7 +261,7 @@ public class HandshakeManagerImpl implements HandshakeManager { for(Elements element : list) { List bitmap = element.getVersionBitmap(); // check for version bitmap - for(short bitPos : ConnectionConductor.VERSION_ORDER) { + for(short bitPos : OFConstants.VERSION_ORDER) { // with all the version it should work. if(bitmap.get(bitPos % Integer.SIZE)) { supportedHighestVersion = bitPos; diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/HandshakeStepWrapper.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/HandshakeStepWrapper.java index ccaa6cdf61..3cadce4479 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/HandshakeStepWrapper.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/HandshakeStepWrapper.java @@ -14,10 +14,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731 import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * @author mirehak - * - */ public class HandshakeStepWrapper implements Runnable { private static final Logger LOG = LoggerFactory diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/IMDController.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/IMDController.java deleted file mode 100644 index 86a09aafdc..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/IMDController.java +++ /dev/null @@ -1,63 +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.openflow.md.core; - -import java.util.List; - -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.DataObject; - -public interface IMDController { - - /** - * Allows application to start translating OF messages received from switches. - * - * @param messageType - * the type of OF message that applications want to receive - * @param version corresponding OF version - * @param translator - * : Object that implements the {@link org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator} - */ - public void addMessageTranslator(Class messageType, int version, IMDMessageTranslator> translator); - - /** - * Allows application to stop receiving OF message received from switches. - * - * @param messageType - * The type of OF message that applications want to stop - * receiving - * @param version TODO - * @param translator - * The object that implements the {@link IMDMessageTranslator} - */ - public void removeMessageTranslator(Class messageType, int version, IMDMessageTranslator> translator); - - /** - * Allows application to start pop-listening MD-SAL messages received from switches. - * - * @param messageType - * the type of OF message that applications want to receive - * @param popListener - * : Object that implements the {@link PopListener} - */ - void removeMessagePopListener(Class messageType, PopListener popListener); - - /** - * Allows application to stop pop-listening MD-SAL messages received from switches. - * - * @param messageType - * the type of OF message that applications want to receive - * @param popListener - * : Object that implements the {@link PopListener} - */ - void addMessagePopListener(Class messageType, PopListener popListener); - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/MDController.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/MDController.java deleted file mode 100644 index 95c3717a4f..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/MDController.java +++ /dev/null @@ -1,416 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core; - -import com.google.common.util.concurrent.ForwardingBlockingQueue; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import org.opendaylight.openflowjava.protocol.spi.connection.SwitchConnectionProvider; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper; -import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey; -import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil; -import org.opendaylight.openflowplugin.openflow.md.core.translator.ErrorTranslator; -import org.opendaylight.openflowplugin.openflow.md.core.translator.ErrorV10Translator; -import org.opendaylight.openflowplugin.openflow.md.core.translator.ExperimenterTranslator; -import org.opendaylight.openflowplugin.openflow.md.core.translator.FeaturesV10ToNodeConnectorUpdatedTranslator; -import org.opendaylight.openflowplugin.openflow.md.core.translator.FlowRemovedTranslator; -import org.opendaylight.openflowplugin.openflow.md.core.translator.MultiPartMessageDescToNodeUpdatedTranslator; -import org.opendaylight.openflowplugin.openflow.md.core.translator.MultiPartReplyPortToNodeConnectorUpdatedTranslator; -import org.opendaylight.openflowplugin.openflow.md.core.translator.MultipartReplyTableFeaturesToTableUpdatedTranslator; -import org.opendaylight.openflowplugin.openflow.md.core.translator.MultipartReplyTranslator; -import org.opendaylight.openflowplugin.openflow.md.core.translator.NotificationPlainTranslator; -import org.opendaylight.openflowplugin.openflow.md.core.translator.PacketInTranslator; -import org.opendaylight.openflowplugin.openflow.md.core.translator.PacketInV10Translator; -import org.opendaylight.openflowplugin.openflow.md.core.translator.PortStatusMessageToNodeConnectorUpdatedTranslator; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.NodeErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SwitchFlowRemoved; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.AggregateFlowStatisticsUpdate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowsStatisticsUpdate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsUpdate; -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.inventory.rev130819.NodeConnectorRemoved; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdated; -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.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.node.error.service.rev140410.BadActionErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadInstructionErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadMatchErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadRequestErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.ExperimenterErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.FlowModErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.GroupModErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.HelloFailedErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.MeterModErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.PortModErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.QueueOpErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.RoleRequestErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.SwitchConfigErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.TableFeaturesErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.TableModErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.NodeConnectorStatisticsUpdate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.QueueStatisticsUpdate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.TableUpdated; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class MDController implements IMDController, AutoCloseable { - - private static final Logger LOG = LoggerFactory.getLogger(MDController.class); - private final ConvertorExecutor convertorExecutor; - - private Collection switchConnectionProviders; - - private ConcurrentMap>>> messageTranslators; - private Map, Collection>> popListeners; - private MessageSpy messageSpyCounter; - - final private int OF10 = OFConstants.OFP_VERSION_1_0; - final private int OF13 = OFConstants.OFP_VERSION_1_3; - - private ErrorHandlerSimpleImpl errorHandler; - - private ExtensionConverterProvider extensionConverterProvider; - - public MDController(ConvertorExecutor convertorExecutor) { - this.convertorExecutor = convertorExecutor; - } - - /** - * @return translator mapping - */ - public Map>>> getMessageTranslators() { - return messageTranslators; - } - - /** - * provisioning of translator mapping - */ - public void init() { - LOG.debug("init"); - - messageTranslators = new ConcurrentHashMap<>(); - popListeners = new ConcurrentHashMap<>(); - //TODO: move registration to factory - addMessageTranslator(ErrorMessage.class, OF10, new ErrorV10Translator()); - addMessageTranslator(ErrorMessage.class, OF13, new ErrorTranslator()); - addMessageTranslator(FlowRemovedMessage.class, OF10, new FlowRemovedTranslator(convertorExecutor)); - addMessageTranslator(FlowRemovedMessage.class, OF13, new FlowRemovedTranslator(convertorExecutor)); - addMessageTranslator(PacketInMessage.class,OF10, new PacketInV10Translator()); - addMessageTranslator(PacketInMessage.class,OF13, new PacketInTranslator(convertorExecutor)); - addMessageTranslator(PortStatusMessage.class,OF10, new PortStatusMessageToNodeConnectorUpdatedTranslator()); - addMessageTranslator(PortStatusMessage.class,OF13, new PortStatusMessageToNodeConnectorUpdatedTranslator()); - addMessageTranslator(MultipartReplyMessage.class,OF13,new MultiPartReplyPortToNodeConnectorUpdatedTranslator()); - addMessageTranslator(MultipartReplyMessage.class,OF10, new MultiPartMessageDescToNodeUpdatedTranslator()); - addMessageTranslator(MultipartReplyMessage.class,OF13, new MultiPartMessageDescToNodeUpdatedTranslator()); - addMessageTranslator(ExperimenterMessage.class, OF10, new ExperimenterTranslator()); - addMessageTranslator(MultipartReplyMessage.class,OF10, new MultipartReplyTranslator(convertorExecutor)); - addMessageTranslator(MultipartReplyMessage.class,OF13, new MultipartReplyTranslator(convertorExecutor)); - addMessageTranslator(MultipartReplyMessage.class,OF13,new MultipartReplyTableFeaturesToTableUpdatedTranslator(convertorExecutor)); - addMessageTranslator(GetFeaturesOutput.class,OF10, new FeaturesV10ToNodeConnectorUpdatedTranslator()); - addMessageTranslator(NotificationQueueWrapper.class, OF10, new NotificationPlainTranslator()); - addMessageTranslator(NotificationQueueWrapper.class, OF13, new NotificationPlainTranslator()); - - NotificationPopListener notificationPopListener = new NotificationPopListener(); - notificationPopListener.setNotificationProviderService( - OFSessionUtil.getSessionManager().getNotificationProviderService()); - notificationPopListener.setMessageSpy(messageSpyCounter); - - //TODO: move registration to factory - addMessagePopListener(NodeErrorNotification.class, notificationPopListener); - addMessagePopListener(BadActionErrorNotification.class, notificationPopListener); - addMessagePopListener(BadInstructionErrorNotification.class, notificationPopListener); - addMessagePopListener(BadMatchErrorNotification.class, notificationPopListener); - addMessagePopListener(BadRequestErrorNotification.class, notificationPopListener); - addMessagePopListener(ExperimenterErrorNotification.class, notificationPopListener); - addMessagePopListener(FlowModErrorNotification.class, notificationPopListener); - addMessagePopListener(GroupModErrorNotification.class, notificationPopListener); - addMessagePopListener(HelloFailedErrorNotification.class, notificationPopListener); - addMessagePopListener(MeterModErrorNotification.class, notificationPopListener); - addMessagePopListener(PortModErrorNotification.class, notificationPopListener); - addMessagePopListener(QueueOpErrorNotification.class, notificationPopListener); - addMessagePopListener(RoleRequestErrorNotification.class, notificationPopListener); - addMessagePopListener(SwitchConfigErrorNotification.class, notificationPopListener); - addMessagePopListener(TableFeaturesErrorNotification.class, notificationPopListener); - addMessagePopListener(TableModErrorNotification.class, notificationPopListener); - addMessagePopListener(NodeConnectorUpdated.class,notificationPopListener); - addMessagePopListener(NodeConnectorRemoved.class,notificationPopListener); - addMessagePopListener(PacketReceived.class,notificationPopListener); - addMessagePopListener(TransmitPacketInput.class, notificationPopListener); - addMessagePopListener(NodeUpdated.class, notificationPopListener); - addMessagePopListener(NodeRemoved.class, notificationPopListener); - - addMessagePopListener(SwitchFlowRemoved.class, notificationPopListener); - addMessagePopListener(TableUpdated.class, notificationPopListener); - - //Notification registration for flow statistics - addMessagePopListener(FlowsStatisticsUpdate.class, notificationPopListener); - addMessagePopListener(AggregateFlowStatisticsUpdate.class, notificationPopListener); - - //Notification registrations for group-statistics - addMessagePopListener(GroupStatisticsUpdated.class, notificationPopListener); - addMessagePopListener(GroupFeaturesUpdated.class, notificationPopListener); - addMessagePopListener(GroupDescStatsUpdated.class, notificationPopListener); - - //Notification registrations for meter-statistics - addMessagePopListener(MeterStatisticsUpdated.class, notificationPopListener); - addMessagePopListener(MeterConfigStatsUpdated.class, notificationPopListener); - addMessagePopListener(MeterFeaturesUpdated.class, notificationPopListener); - - //Notification registration for port-statistics - addMessagePopListener(NodeConnectorStatisticsUpdate.class, notificationPopListener); - - //Notification registration for flow-table statistics - addMessagePopListener(FlowTableStatisticsUpdate.class, notificationPopListener); - - //Notification registration for queue-statistics - addMessagePopListener(QueueStatisticsUpdate.class, notificationPopListener); - - // Push the updated Listeners to Session Manager which will be then picked up by ConnectionConductor eventually - OFSessionUtil.getSessionManager().setTranslatorMapping(messageTranslators); - OFSessionUtil.getSessionManager().setPopListenerMapping(popListeners); - OFSessionUtil.getSessionManager().setMessageSpy(messageSpyCounter); - - // prepare worker pool for rpc - // TODO: get size from configSubsystem - int rpcThreadLimit = 10; - ListeningExecutorService rpcPoolDelegator = createRpcPoolSpyDecorated(rpcThreadLimit, messageSpyCounter); - OFSessionUtil.getSessionManager().setRpcPool(rpcPoolDelegator); - OFSessionUtil.getSessionManager().setExtensionConverterProvider(extensionConverterProvider); - - } - - /** - * @param rpcThreadLimit - * @param messageSpy - * @return - */ - private static ListeningExecutorService createRpcPoolSpyDecorated(final int rpcThreadLimit, final MessageSpy messageSpy) { - final BlockingQueue delegate = new LinkedBlockingQueue<>(100000); - final BlockingQueue queue = new ForwardingBlockingQueue() { - @Override - protected BlockingQueue delegate() { - return delegate; - } - - @Override - public boolean offer(final Runnable r) { - // ThreadPoolExecutor will spawn a new thread after core size is reached only - // if the queue.offer returns false. - return false; - } - }; - - ThreadPoolLoggingExecutor rpcPool = new ThreadPoolLoggingExecutor(rpcThreadLimit, rpcThreadLimit, 0L, - TimeUnit.MILLISECONDS, queue, "OFRpc"); - rpcPool.setRejectedExecutionHandler(new RejectedExecutionHandler() { - @Override - public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) { - try { - executor.getQueue().put(r); - } catch (InterruptedException e) { - throw new RejectedExecutionException("Interrupted while waiting on queue", e); - } - - } - }); - ListeningExecutorService listeningRpcPool = MoreExecutors.listeningDecorator(rpcPool); - RpcListeningExecutorService rpcPoolDecorated = new RpcListeningExecutorService(listeningRpcPool); - rpcPoolDecorated.setMessageSpy(messageSpy); - return rpcPoolDecorated; - } - - /** - * @param switchConnectionProviders - * the switchConnectionProviders to set - */ - public void setSwitchConnectionProviders(final Collection switchConnectionProviders) { - this.switchConnectionProviders = switchConnectionProviders; - } - - /** - * Function called by dependency manager after "init ()" is called and after - * the services provided by the class are registered in the service registry - * - */ - public void start() { - LOG.debug("starting .."); - LOG.debug("switchConnectionProvider: " + switchConnectionProviders); - // setup handler - SwitchConnectionHandlerImpl switchConnectionHandler = new SwitchConnectionHandlerImpl(); - switchConnectionHandler.setMessageSpy(messageSpyCounter); - - errorHandler = new ErrorHandlerSimpleImpl(); - - switchConnectionHandler.setErrorHandler(errorHandler); - switchConnectionHandler.init(); - - List> starterChain = new ArrayList<>(switchConnectionProviders.size()); - for (SwitchConnectionProvider switchConnectionPrv : switchConnectionProviders) { - switchConnectionPrv.setSwitchConnectionHandler(switchConnectionHandler); - ListenableFuture isOnlineFuture = switchConnectionPrv.startup(); - starterChain.add(isOnlineFuture); - } - - Future> srvStarted = Futures.allAsList(starterChain); - } - - /** - * Function called by the dependency manager before the services exported by - * the component are unregistered, this will be followed by a "destroy ()" - * calls - * - */ - public void stop() { - LOG.debug("stopping"); - List> stopChain = new ArrayList<>(switchConnectionProviders.size()); - try { - for (SwitchConnectionProvider switchConnectionPrv : switchConnectionProviders) { - ListenableFuture shutdown = switchConnectionPrv.shutdown(); - stopChain.add(shutdown); - } - Futures.allAsList(stopChain).get(5000, TimeUnit.MILLISECONDS); - } catch (InterruptedException | ExecutionException | TimeoutException e) { - LOG.warn("failed to stop MDController: {}", e.getMessage()); - LOG.debug("failed to stop MDController.. ", e); - } - close(); - } - - /** - * Function called by the dependency manager when at least one dependency - * become unsatisfied or when the component is shutting down because for - * example bundle is being stopped. - * - */ - public void destroy() { - close(); - } - - @Override - public void addMessageTranslator(final Class messageType, final int version, final IMDMessageTranslator> translator) { - TranslatorKey tKey = new TranslatorKey(version, messageType.getName()); - - Collection>> existingValues = messageTranslators.get(tKey); - if (existingValues == null) { - existingValues = new LinkedHashSet<>(); - messageTranslators.put(tKey, existingValues); - } - existingValues.add(translator); - LOG.debug("{} is now translated by {}", messageType, translator); - } - - @Override - public void removeMessageTranslator(final Class messageType, final int version, final IMDMessageTranslator> translator) { - TranslatorKey tKey = new TranslatorKey(version, messageType.getName()); - Collection>> values = messageTranslators.get(tKey); - if (values != null) { - values.remove(translator); - if (values.isEmpty()) { - messageTranslators.remove(tKey); - } - LOG.debug("{} is now removed from translators", translator); - } - } - - @Override - public void addMessagePopListener(final Class messageType, final PopListener popListener) { - Collection> existingValues = popListeners.get(messageType); - if (existingValues == null) { - existingValues = new LinkedHashSet<>(); - popListeners.put(messageType, existingValues); - } - existingValues.add(popListener); - LOG.debug("{} is now popListened by {}", messageType, popListener); - } - - @Override - public void removeMessagePopListener(final Class messageType, final PopListener popListener) { - Collection> values = popListeners.get(messageType); - if (values != null) { - values.remove(popListener); - if (values.isEmpty()) { - popListeners.remove(messageType); - } - LOG.debug("{} is now removed from popListeners", popListener); - } - } - - /** - * @param messageSpyCounter the messageSpyCounter to set - */ - public void setMessageSpyCounter( - final MessageSpy messageSpyCounter) { - this.messageSpyCounter = messageSpyCounter; - } - - @Override - public void close() { - LOG.debug("close"); - messageSpyCounter = null; - messageTranslators = null; - popListeners = null; - for (SwitchConnectionProvider switchConnectionPrv : switchConnectionProviders) { - switchConnectionPrv.setSwitchConnectionHandler(null); - } - switchConnectionProviders = null; - OFSessionUtil.releaseSessionManager(); - errorHandler = null; - } - - /** - * @param extensionConverterProvider extension convertor provider - */ - public void setExtensionConverterProvider(ExtensionConverterProvider extensionConverterProvider) { - this.extensionConverterProvider = extensionConverterProvider; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/MessageFactory.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/MessageFactory.java index ffc39ebbf1..a5ba531848 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/MessageFactory.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/MessageFactory.java @@ -10,24 +10,17 @@ package org.opendaylight.openflowplugin.openflow.md.core; import java.util.ArrayList; import java.util.Collections; import java.util.List; - import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.HelloElementType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.hello.Elements; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.hello.ElementsBuilder; -/** - * @author mirehak - * - */ public abstract class MessageFactory { /** * @param helloVersion openflow version for hello message to send to switch - * @param helloXid transaction id for hello message + * @param helloXid transaction id for hello message * @return HelloInput without elements */ public static HelloInput createHelloInput(short helloVersion, long helloXid) { @@ -36,7 +29,7 @@ public abstract class MessageFactory { /** * @param highestVersion highest openflow version - * @param xid transaction id + * @param xid transaction id * @return builder with prepared header */ private static HelloInputBuilder prepareHelloInputBuilder( @@ -46,17 +39,17 @@ public abstract class MessageFactory { helloInputbuilder.setXid(xid); return helloInputbuilder; } - + /** * @param helloVersion openflow version for hello message to send to switch - * @param helloXid transaction id for hello message + * @param helloXid transaction id for hello message * @param versionOrder list of openflow version in order * @return HelloInput with elements (version bitmap) */ public static HelloInput createHelloInput(short helloVersion, long helloXid, List versionOrder) { HelloInputBuilder helloInputbuilder = prepareHelloInputBuilder(helloVersion, helloXid); if (versionOrder != null) { - + ElementsBuilder elementsBuilder = new ElementsBuilder(); elementsBuilder.setType(HelloElementType.VERSIONBITMAP); int resultVersionListSize = 0; @@ -64,9 +57,9 @@ public abstract class MessageFactory { resultVersionListSize = versionOrder.get(0) + 1; } List booleanList = new ArrayList<>(resultVersionListSize); - + int versionOrderIndex = versionOrder.size() - 1; - + while (versionOrderIndex >= 0) { short version = versionOrder.get(versionOrderIndex); if (version == booleanList.size()) { @@ -76,7 +69,7 @@ public abstract class MessageFactory { booleanList.add(false); } } - + elementsBuilder.setVersionBitmap(booleanList); List elementList = Collections.singletonList(elementsBuilder.build()); @@ -100,32 +93,4 @@ public abstract class MessageFactory { } return result; } - - /** - * @param ofVersion openflow version - * @param ofXid transaction id - * @return barrier message - */ - public static BarrierInput createBarrier(short ofVersion, long ofXid) { - BarrierInputBuilder barrierInput = new BarrierInputBuilder(); - barrierInput.setVersion(ofVersion); - barrierInput.setXid(ofXid); - return barrierInput.build(); - } - -// /** -// * @param input -// * @param cookie -// * @param session -// * @param messageService -// * @return barrier result -// */ -// public static Future> sendBarrier( -// SwitchConnectionDistinguisher cookie, SessionContext session, -// IMessageDispatchService messageService) { -// BarrierInputBuilder barrierInput = new BarrierInputBuilder(); -// barrierInput.setVersion(session.getFeatures().getVersion()); -// barrierInput.setXid(session.getNextXid()); -// return messageService.barrier(barrierInput.build(), cookie); -// } } diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/NotificationPopListener.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/NotificationPopListener.java deleted file mode 100644 index c145c5855d..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/NotificationPopListener.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core; - -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.yangtools.yang.binding.Notification; - -/** - * general publisher to MD-SAL - * - * @param type of supported notification - */ -public class NotificationPopListener implements PopListener { - - private MessageSpy messageSpy; - private NotificationProviderService notificationProviderService; - - /** - * @param messageSpy the messageSpy to set - */ - public void setMessageSpy(MessageSpy messageSpy) { - this.messageSpy = messageSpy; - } - - /** - * @param notificationProviderService the notificationProviderService to set - */ - public void setNotificationProviderService( - NotificationProviderService notificationProviderService) { - this.notificationProviderService = notificationProviderService; - } - - @Override - public void onPop(T processedMessage) { - boolean published = false; - if(processedMessage instanceof Notification) { - if (notificationProviderService != null) { - notificationProviderService.publish((Notification) processedMessage); - messageSpy.spyMessage(processedMessage, MessageSpy.StatisticsGroup.FROM_SWITCH_PUBLISHED_SUCCESS); - published = true; - } - } - - if (! published) { - messageSpy.spyMessage(processedMessage, MessageSpy.StatisticsGroup.FROM_SWITCH_PUBLISHED_FAILURE); - } - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/RpcListeningExecutorService.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/RpcListeningExecutorService.java deleted file mode 100644 index 7127d8b586..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/RpcListeningExecutorService.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core; - -import java.util.Collection; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTask; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.yangtools.yang.binding.DataContainer; - -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.ListeningExecutorService; - -/** - * - */ -public class RpcListeningExecutorService implements ListeningExecutorService { - - private MessageSpy messageSpy; - private ListeningExecutorService executorServiceDelegate; - private DataContainer notSupportedTask = new NoDataContainerTask(); - - /** - * @param executorService executor service - */ - public RpcListeningExecutorService(ListeningExecutorService executorService) { - this.executorServiceDelegate = executorService; - } - - /** - * @param messageSpy the messageSpy to set - */ - public void setMessageSpy(MessageSpy messageSpy) { - this.messageSpy = messageSpy; - } - - @Override - public void shutdown() { - executorServiceDelegate.shutdown(); - } - - @Override - public ListenableFuture submit(Callable task) { - ListenableFuture resultFuture = executorServiceDelegate.submit(task); - - boolean covered = false; - if (task instanceof OFRpcTask) { - if (((OFRpcTask) task).getInput() instanceof DataContainer) { - messageSpy.spyMessage((DataContainer) ((OFRpcTask) task).getInput(), - MessageSpy.StatisticsGroup.TO_SWITCH_ENQUEUED_SUCCESS); - covered = true; - } - } - - if (! covered) { - messageSpy.spyMessage(notSupportedTask, MessageSpy.StatisticsGroup.TO_SWITCH_ENQUEUED_FAILED); - } - - return resultFuture; - } - - @Override - public ListenableFuture submit(Runnable task) { - throw new IllegalAccessError("not supported"); - } - - @Override - public ListenableFuture submit(Runnable task, T result) { - throw new IllegalAccessError("not supported"); - } - - @Override - public List> invokeAll(Collection> tasks) - throws InterruptedException { - return executorServiceDelegate.invokeAll(tasks); - } - - @Override - public List> invokeAll( - Collection> tasks, long timeout, TimeUnit unit) - throws InterruptedException { - return executorServiceDelegate.invokeAll(tasks, timeout, unit); - } - - @Override - public void execute(Runnable command) { - throw new IllegalAccessError("not supported"); - } - - @Override - public List shutdownNow() { - return executorServiceDelegate.shutdownNow(); - } - - @Override - public boolean isShutdown() { - return executorServiceDelegate.isShutdown(); - } - - @Override - public boolean isTerminated() { - return executorServiceDelegate.isTerminated(); - } - - @Override - public boolean awaitTermination(long timeout, TimeUnit unit) - throws InterruptedException { - return executorServiceDelegate.awaitTermination(timeout, unit); - } - - @Override - public T invokeAny(Collection> tasks) - throws InterruptedException, ExecutionException { - throw new IllegalAccessError("not supported"); - } - - @Override - public T invokeAny(Collection> tasks, - long timeout, TimeUnit unit) throws InterruptedException, - ExecutionException, TimeoutException { - throw new IllegalAccessError("not supported"); - } - - protected static class NoDataContainerTask implements DataContainer { - @Override - public Class getImplementedInterface() { - return null; - } - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/RpcUtil.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/RpcUtil.java deleted file mode 100644 index 925a327b65..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/RpcUtil.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core; - -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcResult; - -/** - * @author mirehak - * - */ -public abstract class RpcUtil { - - /** - * @param result rpc result - * @throws Exception exception thrown by method if rpc fails - */ - public static void smokeRpc(RpcResult result) throws Exception { - if (!result.isSuccessful()) { - Throwable firstCause = null; - StringBuilder sb = new StringBuilder(); - for (RpcError error : result.getErrors()) { - if (firstCause != null) { - firstCause = error.getCause(); - } - - sb.append("rpcError:").append(error.getCause().getMessage()).append(';'); - } - throw new Exception(sb.toString(), firstCause); - } - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/SwitchConnectionHandlerImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/SwitchConnectionHandlerImpl.java deleted file mode 100644 index 287b605d55..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/SwitchConnectionHandlerImpl.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core; - -import java.net.InetAddress; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowjava.protocol.api.connection.SwitchConnectionHandler; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil; -import org.opendaylight.openflowplugin.openflow.md.queue.QueueProcessorLightImpl; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.yangtools.yang.binding.DataContainer; - -/** - * basic interconnecting piece between plugin and library - */ -public class SwitchConnectionHandlerImpl implements SwitchConnectionHandler { - - private ScheduledThreadPoolExecutor spyPool; - - private QueueProcessorLightImpl queueProcessor; - private ErrorHandler errorHandler; - private MessageSpy messageSpy; - private int spyRate = 10; - - /** - * - */ - public SwitchConnectionHandlerImpl() { - queueProcessor = new QueueProcessorLightImpl(); - - //TODO: implement shutdown invocation upon service stop event - spyPool = new ScheduledThreadPoolExecutor(1); - } - - /** - * wire all up - */ - public void init() { - queueProcessor.setTranslatorMapping(OFSessionUtil.getTranslatorMap()); - queueProcessor.setPopListenersMapping(OFSessionUtil.getPopListenerMapping()); - queueProcessor.setMessageSpy(messageSpy); - - queueProcessor.init(); - - spyPool.scheduleAtFixedRate(messageSpy, spyRate, spyRate, TimeUnit.SECONDS); - } - - @Override - public boolean accept(InetAddress address) { - // TODO:: add policy derived rules - return true; - } - - @Override - public void onSwitchConnected(ConnectionAdapter connectionAdapter) { - ConnectionConductor conductor = ConnectionConductorFactory.createConductor( - connectionAdapter, queueProcessor); - conductor.setErrorHandler(errorHandler); - } - - /** - * @param messageSpy the messageSpy to set - */ - public void setMessageSpy(MessageSpy messageSpy) { - this.messageSpy = messageSpy; - } - - /** - * @param errorHandler the errorHandler to set - */ - public void setErrorHandler(ErrorHandler errorHandler) { - this.errorHandler = errorHandler; - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/extension/ActionExtensionHelper.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/extension/ActionExtensionHelper.java index 80afdd46dc..7ebdbe99db 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/extension/ActionExtensionHelper.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/extension/ActionExtensionHelper.java @@ -21,9 +21,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.action.rev1 import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * - */ public final class ActionExtensionHelper { private static final Logger LOG = LoggerFactory diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/extension/ExtensionResolvers.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/extension/ExtensionResolvers.java index 6f1ade5b12..2d4bf09ea4 100755 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/extension/ExtensionResolvers.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/extension/ExtensionResolvers.java @@ -38,9 +38,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.ge import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralAugMatchRpcUpdateGroupUpdatedSetField; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.general.rev140714.GeneralExtensionListGrouping; -/** - * - */ public class ExtensionResolvers { private static GroupingLooseResolver matchExtensionResolver = diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/extension/MatchExtensionHelper.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/extension/MatchExtensionHelper.java index 129f529fc8..7b69f1349e 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/extension/MatchExtensionHelper.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/extension/MatchExtensionHelper.java @@ -45,9 +45,6 @@ import org.opendaylight.yangtools.yang.binding.Augmentation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * - */ public final class MatchExtensionHelper { private static final Logger LOG = LoggerFactory diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/role/OfEntityManager.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/role/OfEntityManager.java deleted file mode 100644 index d878aeb369..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/role/OfEntityManager.java +++ /dev/null @@ -1,473 +0,0 @@ -/** - * Copyright (c) 2013, 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.openflow.md.core.role; - -import java.math.BigInteger; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; -import org.opendaylight.controller.md.sal.common.api.clustering.CandidateAlreadyRegisteredException; -import com.google.common.base.Optional; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction; -import org.opendaylight.controller.md.sal.common.api.data.TransactionChain; -import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener; -import org.opendaylight.controller.md.sal.common.api.clustering.Entity; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipState; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipCandidateRegistration; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitch; -import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper; -import org.opendaylight.openflowplugin.openflow.md.core.sal.OpenflowPluginConfig; -import org.opendaylight.yangtools.yang.common.QName; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange; -import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole; -import org.opendaylight.openflowplugin.openflow.md.core.session.RolePushTask; -import org.opendaylight.openflowplugin.openflow.md.core.session.RolePushException; -import org.opendaylight.openflowplugin.openflow.md.util.RoleUtil; -import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.ConcurrentHashMap; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.CheckedFuture; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class OfEntityManager implements TransactionChainListener{ - private static final Logger LOG = LoggerFactory.getLogger(OfEntityManager.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 DataBroker dataBroker; - private EntityOwnershipService entityOwnershipService; - private final OpenflowOwnershipListener ownershipListener; - private final AtomicBoolean registeredListener = new AtomicBoolean(); - private ConcurrentHashMap entsession; - private ConcurrentHashMap entRegistrationMap; - private final String DEVICE_TYPE = "openflow"; - - private final ListeningExecutorService pool; - - private final OpenflowPluginConfig openflowPluginConfig; - - public OfEntityManager(EntityOwnershipService entityOwnershipService, OpenflowPluginConfig ofPluginConfig) { - this.entityOwnershipService = entityOwnershipService; - openflowPluginConfig = ofPluginConfig; - ownershipListener = new OpenflowOwnershipListener(this); - entsession = new ConcurrentHashMap<>(); - entRegistrationMap = new ConcurrentHashMap<>(); - ThreadPoolLoggingExecutor delegate = new ThreadPoolLoggingExecutor( - 20, 20, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), "ofEntity"); - pool = MoreExecutors.listeningDecorator(delegate); - } - - public void setDataBroker(DataBroker dbBroker) { - this.dataBroker = dbBroker; - } - - public void init(){ - registerEntityOwnershipChangeListener(); - } - - public void registerEntityOwnershipChangeListener() { - if(entityOwnershipService!=null) { - if(LOG.isDebugEnabled()) { - LOG.debug("registerEntityOwnershipChangeListener: Registering entity ownership change listener for entitier of type {}", DEVICE_TYPE); - } - entityOwnershipService.registerListener(DEVICE_TYPE, ownershipListener); - } - } - - public void requestOpenflowEntityOwnership(final ModelDrivenSwitch ofSwitch, - final SessionContext context, - final NotificationQueueWrapper wrappedNotification, - final RpcProviderRegistry rpcProviderRegistry) { - MDSwitchMetaData entityMetaData = - new MDSwitchMetaData(ofSwitch,context,wrappedNotification,rpcProviderRegistry); - - final Entity entity = new Entity(DEVICE_TYPE, ofSwitch.getNodeId().getValue()); - entsession.put(entity, entityMetaData); - - //Register as soon as possible to avoid missing any entity ownership change event - final EntityOwnershipCandidateRegistration entityRegistration; - try { - entityRegistration = entityOwnershipService.registerCandidate(entity); - entRegistrationMap.put(entity, entityRegistration); - LOG.info("requestOpenflowEntityOwnership: Registered controller for the ownership of {}", ofSwitch.getNodeId() ); - } catch (CandidateAlreadyRegisteredException e) { - // we can log and move for this error, as listener is present and role changes will be served. - LOG.error("requestOpenflowEntityOwnership : Controller registration for ownership of {} failed ", ofSwitch.getNodeId(), e ); - } - - Optional entityOwnershipStateOptional = - entityOwnershipService.getOwnershipState(entity); - - if (entityOwnershipStateOptional.isPresent()) { - final EntityOwnershipState entityOwnershipState = entityOwnershipStateOptional.get(); - if (entityOwnershipState.hasOwner()) { - final OfpRole newRole ; - if (entityOwnershipState.isOwner()) { - LOG.info("requestOpenflowEntityOwnership: Set controller as a MASTER controller " + - "because it's the OWNER of the {}", ofSwitch.getNodeId()); - newRole = OfpRole.BECOMEMASTER; - setDeviceOwnershipState(entity,true); - registerRoutedRPCForSwitch(entsession.get(entity)); - } else { - LOG.info("requestOpenflowEntityOwnership: Set controller as a SLAVE controller " + - "because it's is not the owner of the {}", ofSwitch.getNodeId()); - newRole = OfpRole.BECOMESLAVE; - setDeviceOwnershipState(entity,false); - } - RolePushTask task = new RolePushTask(newRole, context); - ListenableFuture rolePushResult = pool.submit(task); - CheckedFuture rolePushResultChecked = - RoleUtil.makeCheckedRuleRequestFxResult(rolePushResult); - Futures.addCallback(rolePushResult, new FutureCallback(){ - @Override - public void onSuccess(Boolean result){ - LOG.info("requestOpenflowEntityOwnership: Controller is now {} of the {}", - newRole == OfpRole.BECOMEMASTER?"MASTER":"SLAVE",ofSwitch.getNodeId() ); - - sendNodeAddedNotification(entsession.get(entity)); - } - @Override - public void onFailure(Throwable t){ - LOG.warn("requestOpenflowEntityOwnership: Controller is not able to set " + - "the role for {}",ofSwitch.getNodeId(), t); - - if(newRole == OfpRole.BECOMEMASTER) { - LOG.info("requestOpenflowEntityOwnership: ..and controller is the owner of the " + - "device {}. Closing the registration, so other controllers can try to " + - "become owner and attempt to be master controller.",ofSwitch.getNodeId()); - - EntityOwnershipCandidateRegistration ownershipRegistrent = entRegistrationMap.get(entity); - if (ownershipRegistrent != null) { - ownershipRegistrent.close(); - entRegistrationMap.remove(entity); - } - - LOG.info("requestOpenflowEntityOwnership: ..and registering it back to participate" + - " in ownership of the entity."); - - EntityOwnershipCandidateRegistration entityRegistration; - try { - entityRegistration = entityOwnershipService.registerCandidate(entity); - entRegistrationMap.put(entity, entityRegistration); - LOG.info("requestOpenflowEntityOwnership: re-registered controller for " + - "ownership of the {}", ofSwitch.getNodeId() ); - } catch (CandidateAlreadyRegisteredException e) { - // we can log and move for this error, as listener is present and role changes will be served. - LOG.error("requestOpenflowEntityOwnership: *Surprisingly* Entity is already " + - "registered with EntityOwnershipService : {}", ofSwitch.getNodeId(), e ); - } - - } else { - LOG.error("requestOpenflowEntityOwnership : Not able to set role {} for {}" - , newRole == OfpRole.BECOMEMASTER?"MASTER":"SLAVE", ofSwitch.getNodeId()); - } - } - }); - } - } - } - - public void setSlaveRole(SessionContext sessionContext) { - OfpRole newRole = OfpRole.BECOMESLAVE; - if (sessionContext != null) { - final BigInteger targetSwitchDPId = sessionContext.getFeatures().getDatapathId(); - LOG.debug("setSlaveRole: Set controller as a SLAVE controller for {}", targetSwitchDPId.toString()); - - RolePushTask task = new RolePushTask(newRole, sessionContext); - ListenableFuture rolePushResult = pool.submit(task); - final CheckedFuture rolePushResultChecked = - RoleUtil.makeCheckedRuleRequestFxResult(rolePushResult); - Futures.addCallback(rolePushResult, new FutureCallback(){ - @Override - public void onSuccess(Boolean result){ - LOG.debug("setSlaveRole: Controller is set as a SLAVE for {}", targetSwitchDPId.toString()); - } - @Override - public void onFailure(Throwable e){ - LOG.error("setSlaveRole: Role request to set controller as a SLAVE failed for {}", - targetSwitchDPId.toString(), e); - } - }); - } else { - LOG.warn("setSlaveRole: sessionContext is not set. Device is not connected anymore"); - } - } - - public void onDeviceOwnershipChanged(final EntityOwnershipChange ownershipChange) { - final OfpRole newRole; - final Entity entity = ownershipChange.getEntity(); - SessionContext sessionContext = entsession.get(entity)!=null?entsession.get(entity).getContext():null; - if (!ownershipChange.inJeopardy()) { - if (ownershipChange.isOwner()) { - LOG.info("onDeviceOwnershipChanged: Set controller as a MASTER controller because " + - "it's the OWNER of the {}", entity); - newRole = OfpRole.BECOMEMASTER; - } else { - newRole = OfpRole.BECOMESLAVE; - if (sessionContext != null && ownershipChange.hasOwner()) { - LOG.info("onDeviceOwnershipChanged: Set controller as a SLAVE controller because " + - "it's not the OWNER of the {}", entity); - - if (ownershipChange.wasOwner()) { - setDeviceOwnershipState(entity, false); - deregisterRoutedRPCForSwitch(entsession.get(entity)); - // You don't have to explicitly set role to Slave in this case, - // because other controller will be taking over the master role - // and that will force other controller to become slave. - } else { - boolean isOwnershipInitialized = entsession.get(entity).getIsOwnershipInitialized(); - setDeviceOwnershipState(entity, false); - if (!isOwnershipInitialized) { - setSlaveRole(sessionContext); - sendNodeAddedNotification(entsession.get(entity)); - } - } - } - return; - } - } else { - LOG.error("onDeviceOwnershipChanged: inJeopardy{}", ownershipChange.inJeopardy()); - //if i am the owner at present , i have lost quorum - //thus transitioning to slave - //if i am not the owner , election will be triggered - if(entsession.get(entity).getOfSwitch().isEntityOwner()){ - newRole = OfpRole.BECOMESLAVE; - setSlaveRole(sessionContext); - setDeviceOwnershipState(entity, false); - deregisterRoutedRPCForSwitch(entsession.get(entity)); - }else{ - LOG.error(" owner of the switch {}",entsession.get(entity).getOfSwitch().isEntityOwner()); - } - return; - } - - if (sessionContext != null) { - //Register the RPC, given *this* controller instance is going to be master owner. - //If role registration fails for this node, it will deregister as a candidate for - //ownership and that will make this controller non-owner and it will deregister the - // router rpc. - setDeviceOwnershipState(entity,newRole==OfpRole.BECOMEMASTER); - registerRoutedRPCForSwitch(entsession.get(entity)); - - final String targetSwitchDPId = sessionContext.getFeatures().getDatapathId().toString(); - RolePushTask task = new RolePushTask(newRole, sessionContext); - ListenableFuture rolePushResult = pool.submit(task); - - final CheckedFuture rolePushResultChecked = - RoleUtil.makeCheckedRuleRequestFxResult(rolePushResult); - Futures.addCallback(rolePushResult, new FutureCallback(){ - @Override - public void onSuccess(Boolean result){ - LOG.info("onDeviceOwnershipChanged: Controller is successfully set as a " + - "MASTER controller for {}", targetSwitchDPId); - if(!openflowPluginConfig.skipTableFeatures()) { - if(LOG.isDebugEnabled()){ - LOG.debug("Send table feature request for entity {}",entity.getId()); - } - entsession.get(entity).getOfSwitch().sendEmptyTableFeatureRequest(); - } - sendNodeAddedNotification(entsession.get(entity)); - - } - @Override - public void onFailure(Throwable e){ - - LOG.warn("onDeviceOwnershipChanged: Controller is not able to set the " + - "MASTER role for {}.", targetSwitchDPId,e); - if(newRole == OfpRole.BECOMEMASTER) { - LOG.info("onDeviceOwnershipChanged: ..and this *instance* is owner of the device {}. " + - "Closing the registration, so other entity can become owner " + - "and attempt to be master controller.",targetSwitchDPId); - - EntityOwnershipCandidateRegistration ownershipRegistrent = entRegistrationMap.get(entity); - if (ownershipRegistrent != null) { - setDeviceOwnershipState(entity,false); - ownershipRegistrent.close(); - MDSwitchMetaData switchMetadata = entsession.get(entity); - if(switchMetadata != null){ - switchMetadata.setIsOwnershipInitialized(false); - //We can probably leave deregistration till the node ownerhsip change. - //But that can probably cause some race condition. - deregisterRoutedRPCForSwitch(switchMetadata); - } - } - - LOG.info("onDeviceOwnershipChanged: ..and registering it back to participate in " + - "ownership and re-try"); - - EntityOwnershipCandidateRegistration entityRegistration; - try { - entityRegistration = entityOwnershipService.registerCandidate(entity); - entRegistrationMap.put(entity, entityRegistration); - LOG.info("onDeviceOwnershipChanged: re-registered candidate for " + - "ownership of the {}", targetSwitchDPId ); - } catch (CandidateAlreadyRegisteredException ex) { - // we can log and move for this error, as listener is present and role changes will be served. - LOG.error("onDeviceOwnershipChanged: *Surprisingly* Entity is already " + - "registered with EntityOwnershipService : {}", targetSwitchDPId, ex ); - } - - } else { - LOG.error("onDeviceOwnershipChanged : Not able to set role {} for " + - " {}", newRole == OfpRole.BECOMEMASTER?"MASTER":"SLAVE", targetSwitchDPId); - } - } - }); - } else { - LOG.warn("onDeviceOwnershipChanged: sessionContext is not available. Releasing ownership of the device"); - EntityOwnershipCandidateRegistration ownershipRegistrant = entRegistrationMap.get(entity); - if (ownershipRegistrant != null) { - ownershipRegistrant.close(); - } - } - } - - public void unregisterEntityOwnershipRequest(NodeId nodeId) { - Entity entity = new Entity(DEVICE_TYPE, nodeId.getValue()); - entsession.remove(entity); - EntityOwnershipCandidateRegistration entRegCandidate = entRegistrationMap.get(entity); - if(entRegCandidate != null){ - LOG.info("unregisterEntityOwnershipRequest: Unregister controller entity ownership " + - "request for {}", nodeId); - entRegCandidate.close(); - entRegistrationMap.remove(entity); - } - } - - @Override - public void onTransactionChainFailed(final TransactionChain chain, final AsyncTransaction transaction, - final Throwable cause) { - } - - @Override - public void onTransactionChainSuccessful(final TransactionChain chain) { - // NOOP - } - - private static void registerRoutedRPCForSwitch(MDSwitchMetaData entityMetadata) { - // Routed RPC registration is only done when *this* instance is owner of - // the entity. - if(entityMetadata.getOfSwitch().isEntityOwner()) { - if (!entityMetadata.isRPCRegistrationDone.get()) { - entityMetadata.setIsRPCRegistrationDone(true); - ModelDrivenSwitchRegistration registration = - entityMetadata.getOfSwitch().register(entityMetadata.getRpcProviderRegistry()); - - entityMetadata.getContext().setProviderRegistration(registration); - - LOG.info("registerRoutedRPCForSwitch: Registered routed rpc for ModelDrivenSwitch {}", - entityMetadata.getOfSwitch().getNodeId().getValue()); - } - } else { - LOG.info("registerRoutedRPCForSwitch: Skipping routed rpc registration for ModelDrivenSwitch {}", - entityMetadata.getOfSwitch().getNodeId().getValue()); - } - } - - private static void deregisterRoutedRPCForSwitch(MDSwitchMetaData entityMetadata) { - - ModelDrivenSwitchRegistration registration = entityMetadata.getContext().getProviderRegistration(); - if (null != registration) { - registration.close(); - entityMetadata.getContext().setProviderRegistration(null); - entityMetadata.setIsRPCRegistrationDone(false); - } - LOG.info("deregisterRoutedRPCForSwitch: De-registered routed rpc for ModelDrivenSwitch {}", - entityMetadata.getOfSwitch().getNodeId().getValue()); - } - - private static void sendNodeAddedNotification(MDSwitchMetaData entityMetadata) { - //Node added notification need to be sent irrespective of whether - // *this* instance is owner of the entity or not. Because yang notifications - // are local, and we should maintain the behavior across the application. - if (entityMetadata != null && entityMetadata.getOfSwitch() != null) { - LOG.info("sendNodeAddedNotification: Node Added notification is sent for ModelDrivenSwitch {}", - entityMetadata.getOfSwitch().getNodeId().getValue()); - - entityMetadata.getContext().getNotificationEnqueuer().enqueueNotification( - entityMetadata.getWrappedNotification()); - - //Send multipart request to get other details of the switch. - entityMetadata.getOfSwitch().requestSwitchDetails(); - } else { - LOG.debug("Switch got disconnected, skip node added notification."); - } - } - - private void setDeviceOwnershipState(Entity entity, boolean isMaster) { - MDSwitchMetaData entityMetadata = entsession.get(entity); - entityMetadata.setIsOwnershipInitialized(true); - entityMetadata.getOfSwitch().setEntityOwnership(isMaster); - } - - private class MDSwitchMetaData { - - final private ModelDrivenSwitch ofSwitch; - final private SessionContext context; - final private NotificationQueueWrapper wrappedNotification; - final private RpcProviderRegistry rpcProviderRegistry; - final private AtomicBoolean isRPCRegistrationDone = new AtomicBoolean(false); - final private AtomicBoolean isOwnershipInitialized = new AtomicBoolean(false); - - MDSwitchMetaData(ModelDrivenSwitch ofSwitch, - SessionContext context, - NotificationQueueWrapper wrappedNotification, - RpcProviderRegistry rpcProviderRegistry) { - this.ofSwitch = ofSwitch; - this.context = context; - this.wrappedNotification = wrappedNotification; - this.rpcProviderRegistry = rpcProviderRegistry; - } - - public ModelDrivenSwitch getOfSwitch() { - return ofSwitch; - } - - public SessionContext getContext() { - return context; - } - - public NotificationQueueWrapper getWrappedNotification() { - return wrappedNotification; - } - - public RpcProviderRegistry getRpcProviderRegistry() { - return rpcProviderRegistry; - } - - public AtomicBoolean getIsRPCRegistrationDone() { - return isRPCRegistrationDone; - } - - public void setIsRPCRegistrationDone(boolean isRPCRegistrationDone) { - this.isRPCRegistrationDone.set(isRPCRegistrationDone); - } - - public boolean getIsOwnershipInitialized() { - return isOwnershipInitialized.get(); - } - - public void setIsOwnershipInitialized( boolean ownershipState) { - this.isOwnershipInitialized.set(ownershipState); - } - } -} \ No newline at end of file diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/role/OpenflowOwnershipListener.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/role/OpenflowOwnershipListener.java deleted file mode 100644 index 3e61d7839b..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/role/OpenflowOwnershipListener.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * Copyright (c) 2013, 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.openflow.md.core.role; - -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipListener; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipChange; - -public class OpenflowOwnershipListener implements EntityOwnershipListener { - private final OfEntityManager entManager; - - public OpenflowOwnershipListener(OfEntityManager entManager) { - this.entManager = entManager; - } - - @Override - public void ownershipChanged(EntityOwnershipChange ownershipChange) { - this.entManager.onDeviceOwnershipChanged(ownershipChange); - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/role/RoleChangeException.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/role/RoleChangeException.java deleted file mode 100644 index 1205bf3d96..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/role/RoleChangeException.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright (c) 2015, 2016 Dell. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.role; - - -public class RoleChangeException extends Exception { - private static final long serialVersionUID = -615991366447313972L; - - /** - * default ctor - * - * @param message exception message - */ - public RoleChangeException(String message) { - super(message); - } - - /** - * @param message exception message - * @param cause exception cause - */ - public RoleChangeException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/AbstractModelDrivenSwitch.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/AbstractModelDrivenSwitch.java deleted file mode 100644 index 088bc74800..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/AbstractModelDrivenSwitch.java +++ /dev/null @@ -1,140 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.sal; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableList.Builder; -import java.util.Collection; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.openflowplugin.api.openflow.md.AbstractModelDrivenSwitchRegistration; -import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitch; -import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SalFlowService; -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.service.rev130918.SalGroupService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.OpendaylightGroupStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeContext; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.SalMeterService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.OpendaylightMeterStatisticsService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.NodeConfigService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketProcessingService; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.SalPortService; -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.yang.gen.v1.urn.opendaylight.table.service.rev131026.SalTableService; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; - -/** - * RPC abstract for MD-switch - */ -public abstract class AbstractModelDrivenSwitch implements ModelDrivenSwitch { - - private final InstanceIdentifier identifier; - - protected final SessionContext sessionContext; - - private boolean isEntityOwner = false; - - protected AbstractModelDrivenSwitch(InstanceIdentifier identifier,SessionContext conductor) { - this.identifier = identifier; - this.sessionContext = conductor; - } - - @Override - public final InstanceIdentifier getIdentifier() { - return this.identifier; - } - - @Override - public ModelDrivenSwitchRegistration register(RpcProviderRegistry rpcProviderRegistry) { - final Builder> builder = ImmutableList.builder(); - - final RoutedRpcRegistration flowRegistration = rpcProviderRegistry.addRoutedRpcImplementation(SalFlowService.class, this); - flowRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(flowRegistration); - - final RoutedRpcRegistration portRegistration = rpcProviderRegistry.addRoutedRpcImplementation(SalPortService.class, this); - portRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(portRegistration); - - final RoutedRpcRegistration meterRegistration = rpcProviderRegistry.addRoutedRpcImplementation(SalMeterService.class, this); - meterRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(meterRegistration); - - final RoutedRpcRegistration groupRegistration = rpcProviderRegistry.addRoutedRpcImplementation(SalGroupService.class, this); - groupRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(groupRegistration); - - final RoutedRpcRegistration tableRegistration = rpcProviderRegistry.addRoutedRpcImplementation(SalTableService.class, this); - tableRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(tableRegistration); - - final RoutedRpcRegistration packetRegistration = rpcProviderRegistry.addRoutedRpcImplementation(PacketProcessingService.class, this); - packetRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(packetRegistration); - - final RoutedRpcRegistration flowStatisticsRegistration = rpcProviderRegistry.addRoutedRpcImplementation(OpendaylightFlowStatisticsService.class, this); - flowStatisticsRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(flowStatisticsRegistration); - - final RoutedRpcRegistration groupStatisticsRegistration = rpcProviderRegistry.addRoutedRpcImplementation(OpendaylightGroupStatisticsService.class, this); - groupStatisticsRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(groupStatisticsRegistration); - - final RoutedRpcRegistration meterStatisticsRegistration = rpcProviderRegistry.addRoutedRpcImplementation(OpendaylightMeterStatisticsService.class, this); - meterStatisticsRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(meterStatisticsRegistration); - - final RoutedRpcRegistration portStatisticsRegistration = rpcProviderRegistry.addRoutedRpcImplementation(OpendaylightPortStatisticsService.class, this); - portStatisticsRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(portStatisticsRegistration); - - final RoutedRpcRegistration nodeConfigRegistration = rpcProviderRegistry.addRoutedRpcImplementation(NodeConfigService.class, this); - nodeConfigRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(nodeConfigRegistration); - - final RoutedRpcRegistration flowTableStatisticsRegistration = rpcProviderRegistry.addRoutedRpcImplementation(OpendaylightFlowTableStatisticsService.class, this); - flowTableStatisticsRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(flowTableStatisticsRegistration); - - final RoutedRpcRegistration queueStatisticsRegistration = rpcProviderRegistry.addRoutedRpcImplementation(OpendaylightQueueStatisticsService.class, this); - queueStatisticsRegistration.registerPath(NodeContext.class, getIdentifier()); - builder.add(queueStatisticsRegistration); - - final Collection> registrations = builder.build(); - return new AbstractModelDrivenSwitchRegistration(this) { - @Override - protected void removeRegistration() { - for (RoutedRpcRegistration r : registrations) { - r.close(); - } - } - }; - } - - /** - * @return session context - */ - public SessionContext getSessionContext() { - return sessionContext; - } - - @Override - public boolean isEntityOwner() { - return isEntityOwner; - } - - @Override - public void setEntityOwnership(boolean isOwner) { - isEntityOwner = isOwner; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/BuildSwitchCapabilitiesOF10.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/BuildSwitchCapabilitiesOF10.java index 0fbc1a1e7f..9f9fce6d0d 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/BuildSwitchCapabilitiesOF10.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/BuildSwitchCapabilitiesOF10.java @@ -27,9 +27,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731 /** * SwitchFeature builder for OF 1.0 - * - * @author jsebin - * */ public final class BuildSwitchCapabilitiesOF10 implements BuildSwitchFeatures { diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/BuildSwitchCapabilitiesOF13.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/BuildSwitchCapabilitiesOF13.java index f9d1f4370f..b84af923a0 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/BuildSwitchCapabilitiesOF13.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/BuildSwitchCapabilitiesOF13.java @@ -25,9 +25,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731 /** * SwitchFeature builder for OF 1.3 - * - * @author jsebin - * */ public final class BuildSwitchCapabilitiesOF13 implements BuildSwitchFeatures { diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/ModelDrivenSwitchImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/ModelDrivenSwitchImpl.java deleted file mode 100644 index 74f503cb62..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/ModelDrivenSwitchImpl.java +++ /dev/null @@ -1,562 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.sal; - -import com.google.common.base.Optional; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import java.math.BigInteger; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.PacketOutConvertor; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.PacketOutConvertorData; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil; -import org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput; -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.GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput; -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.GetAllFlowsStatisticsFromAllFlowTablesInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesOutput; -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.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.group.service.rev130918.AddGroupInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput; -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.GetGroupDescriptionInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionOutput; -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.GetGroupStatisticsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput; -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.GetAllMeterStatisticsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsOutput; -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.GetMeterStatisticsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.SetConfigInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.SetConfigOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestDescCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestPortDescCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestTableFeaturesCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.table.features._case.MultipartRequestTableFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.ConnectionCookie; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.TransmitPacketInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutput; -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.GetNodeConnectorStatisticsInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsOutput; -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.GetAllQueuesStatisticsFromGivenPortInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortOutput; -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.table.service.rev131026.UpdateTableInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutput; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.slf4j.Logger; - -/** - * RPC implementation of MD-switch - */ -public class ModelDrivenSwitchImpl extends AbstractModelDrivenSwitch { - - private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(ModelDrivenSwitchImpl.class); - private final NodeId nodeId; - private final IMessageDispatchService messageService; - private short version = 0; - private final ConvertorExecutor convertorExecutor; - private OFRpcTaskContext rpcTaskContext; - - // TODO:read timeout from configSubsystem - protected long maxTimeout = 1000; - protected TimeUnit maxTimeoutUnit = TimeUnit.MILLISECONDS; - - protected ModelDrivenSwitchImpl(final NodeId nodeId, final InstanceIdentifier identifier, - final SessionContext sessionContext, final ConvertorExecutor convertorExecutor) { - super(identifier, sessionContext); - this.nodeId = nodeId; - messageService = sessionContext.getMessageDispatchService(); - version = sessionContext.getPrimaryConductor().getVersion(); - this.convertorExecutor = convertorExecutor; - final NotificationProviderService rpcNotificationProviderService = OFSessionUtil.getSessionManager().getNotificationProviderService(); - - rpcTaskContext = new OFRpcTaskContext(); - rpcTaskContext.setSession(sessionContext); - rpcTaskContext.setMessageService(messageService); - rpcTaskContext.setRpcNotificationProviderService(rpcNotificationProviderService); - rpcTaskContext.setMaxTimeout(maxTimeout); - rpcTaskContext.setMaxTimeoutUnit(maxTimeoutUnit); - rpcTaskContext.setRpcPool(OFSessionUtil.getSessionManager().getRpcPool()); - rpcTaskContext.setMessageSpy(OFSessionUtil.getSessionManager().getMessageSpy()); - - } - - @Override - public Future> addFlow(final AddFlowInput input) { - LOG.debug("Calling the FlowMod RPC method on MessageDispatchService"); - // use primary connection - SwitchConnectionDistinguisher cookie = null; - - OFRpcTask> task = - OFRpcTaskFactory.createAddFlowTask(rpcTaskContext, input, cookie, convertorExecutor); - ListenableFuture> result = task.submit(); - - return Futures.transform(result, OFRpcFutureResultTransformFactory.createForAddFlowOutput()); - } - - - @Override - public Future> addGroup(final AddGroupInput input) { - LOG.debug("Calling the GroupMod RPC method on MessageDispatchService"); - - // use primary connection - SwitchConnectionDistinguisher cookie = null; - - OFRpcTask> task = - OFRpcTaskFactory.createAddGroupTask(rpcTaskContext, input, cookie, convertorExecutor); - ListenableFuture> result = task.submit(); - - return Futures.transform(result, OFRpcFutureResultTransformFactory.createForAddGroupOutput()); - } - - @Override - public Future> addMeter(final AddMeterInput input) { - LOG.debug("Calling the MeterMod RPC method on MessageDispatchService"); - - // use primary connection - SwitchConnectionDistinguisher cookie = null; - - OFRpcTask> task = - OFRpcTaskFactory.createAddMeterTask(rpcTaskContext, input, cookie, convertorExecutor); - ListenableFuture> result = task.submit(); - - return Futures.transform(result, OFRpcFutureResultTransformFactory.createForAddMeterOutput()); - } - - @Override - public Future> removeFlow(final RemoveFlowInput input) { - LOG.debug("Calling the removeFlow RPC method on MessageDispatchService"); - - // use primary connection - SwitchConnectionDistinguisher cookie = null; - OFRpcTask> task = - OFRpcTaskFactory.createRemoveFlowTask(rpcTaskContext, input, cookie, convertorExecutor); - ListenableFuture> result = task.submit(); - - return Futures.transform(result, OFRpcFutureResultTransformFactory.createForRemoveFlowOutput()); - } - - @Override - public Future> removeGroup(final RemoveGroupInput input) { - LOG.debug("Calling the Remove Group RPC method on MessageDispatchService"); - - SwitchConnectionDistinguisher cookie = null; - OFRpcTask> task = - OFRpcTaskFactory.createRemoveGroupTask(rpcTaskContext, input, cookie, convertorExecutor); - ListenableFuture> result = task.submit(); - - return Futures.transform(result, OFRpcFutureResultTransformFactory.createForRemoveGroupOutput()); - } - - @Override - public Future> removeMeter(final RemoveMeterInput input) { - LOG.debug("Calling the Remove MeterMod RPC method on MessageDispatchService"); - - SwitchConnectionDistinguisher cookie = null; - OFRpcTask> task = - OFRpcTaskFactory.createRemoveMeterTask(rpcTaskContext, input, cookie, convertorExecutor); - ListenableFuture> result = task.submit(); - - return Futures.transform(result, OFRpcFutureResultTransformFactory.createForRemoveMeterOutput()); - } - - @Override - public Future> transmitPacket(final TransmitPacketInput input) { - LOG.debug("TransmitPacket - {}", input); - // Convert TransmitPacket to PacketOutInput - final PacketOutConvertorData data = new PacketOutConvertorData(version); - data.setDatapathId(sessionContext.getFeatures().getDatapathId()); - data.setXid(sessionContext.getNextXid()); - - final java.util.Optional message = convertorExecutor.convert(input, data); - - SwitchConnectionDistinguisher cookie = null; - ConnectionCookie connectionCookie = input.getConnectionCookie(); - if (connectionCookie != null && connectionCookie.getValue() != null) { - cookie = new SwitchConnectionCookieOFImpl(connectionCookie.getValue()); - } - - LOG.debug("Calling the transmitPacket RPC method"); - return messageService.packetOut(message - .orElse(PacketOutConvertor.defaultResult(version)), cookie); - } - - @Override - public Future> updateFlow(final UpdateFlowInput input) { - LOG.debug("Calling the updateFlow RPC method on MessageDispatchService"); - - // use primary connection - SwitchConnectionDistinguisher cookie = null; - final ReadWriteTransaction rwTx = OFSessionUtil.getSessionManager().getDataBroker().newReadWriteTransaction(); - OFRpcTask> task = - OFRpcTaskFactory.createUpdateFlowTask(rpcTaskContext, input, cookie, rwTx, convertorExecutor); - ListenableFuture> result = task.submit(); - - return result; - } - - @Override - public Future> updateGroup(final UpdateGroupInput input) { - LOG.debug("Calling the update Group Mod RPC method on MessageDispatchService"); - - // use primary connection - SwitchConnectionDistinguisher cookie = null; - - OFRpcTask> task = - OFRpcTaskFactory.createUpdateGroupTask(rpcTaskContext, input, cookie, convertorExecutor); - ListenableFuture> result = task.submit(); - - return result; - } - - @Override - public Future> updateMeter(final UpdateMeterInput input) { - LOG.debug("Calling the MeterMod RPC method on MessageDispatchService"); - - // use primary connection - SwitchConnectionDistinguisher cookie = null; - - OFRpcTask> task = - OFRpcTaskFactory.createUpdateMeterTask(rpcTaskContext, input, cookie, convertorExecutor); - ListenableFuture> result = task.submit(); - - return result; - } - - @Override - public NodeId getNodeId() { - return nodeId; - } - - - @Override - public Future> getAllGroupStatistics(final GetAllGroupStatisticsInput input) { - // use primary connection - LOG.debug("Calling the getAllGroupStatistics RPC method on MessageDispatchService"); - SwitchConnectionDistinguisher cookie = null; - - OFRpcTask> task = - OFRpcTaskFactory.createGetAllGroupStatisticsTask(rpcTaskContext, input, cookie); - ListenableFuture> result = task.submit(); - - return result; - - } - - @Override - public Future> getGroupDescription(final GetGroupDescriptionInput input) { - LOG.debug("Calling the getGroupDescription RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetGroupDescriptionTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getGroupFeatures(final GetGroupFeaturesInput input) { - LOG.debug("Calling the getGroupFeatures RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetGroupFeaturesTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getGroupStatistics(final GetGroupStatisticsInput input) { - LOG.debug("Calling the getGroupStatistics RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetGroupStatisticsTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getAllMeterConfigStatistics( - final GetAllMeterConfigStatisticsInput input) { - LOG.debug("Calling the getAllMeterConfigStatistics RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetAllMeterConfigStatisticsTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getAllMeterStatistics( - final GetAllMeterStatisticsInput input) { - LOG.debug("Calling the getAllMeterStatistics RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetAllMeterStatisticsTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getMeterFeatures( - final GetMeterFeaturesInput input) { - LOG.debug("Calling the getMeterFeatures RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetMeterFeaturesTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getMeterStatistics( - final GetMeterStatisticsInput input) { - LOG.debug("Calling the getMeterStatistics RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetMeterStatisticsTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getAllNodeConnectorsStatistics( - final GetAllNodeConnectorsStatisticsInput input) { - LOG.debug("Calling the getAllNodeConnectorsStatistics RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetAllNodeConnectorsStatisticsTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getNodeConnectorStatistics( - final GetNodeConnectorStatisticsInput input) { - LOG.debug("Calling the getNodeConnectorStatistics RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetNodeConnectorStatisticsTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> updatePort(final UpdatePortInput input) { - LOG.debug("Calling the updatePort RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createUpdatePortTask(rpcTaskContext, input, null, convertorExecutor); - return task.submit(); - } - - @Override - public Future> updateTable(final UpdateTableInput input) { - LOG.debug("Calling the updateTable RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createUpdateTableTask(rpcTaskContext, input, null, convertorExecutor); - return task.submit(); - } - - @Override - public Future> getAllFlowStatisticsFromFlowTable( - final GetAllFlowStatisticsFromFlowTableInput input) { - LOG.debug("Calling the getAllFlowStatisticsFromFlowTable RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetAllFlowStatisticsFromFlowTableTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getAllFlowsStatisticsFromAllFlowTables( - final GetAllFlowsStatisticsFromAllFlowTablesInput input) { - LOG.debug("Calling the getAllFlowsStatisticsFromAllFlowTables RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetAllFlowsStatisticsFromAllFlowTablesTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getFlowStatisticsFromFlowTable( - final GetFlowStatisticsFromFlowTableInput input) { - LOG.debug("Calling the getFlowStatisticsFromFlowTable RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetFlowStatisticsFromFlowTableTask(rpcTaskContext, input, null, convertorExecutor); - return task.submit(); - } - - @Override - public Future> getAggregateFlowStatisticsFromFlowTableForAllFlows( - final GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput input) { - LOG.debug("Calling the getAggregateFlowStatisticsFromFlowTableForAllFlows RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetAggregateFlowStatisticsFromFlowTableForAllFlowsTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getAggregateFlowStatisticsFromFlowTableForGivenMatch( - final GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput input) { - LOG.debug("Calling the getAggregateFlowStatisticsFromFlowTableForGivenMatch RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetAggregateFlowStatisticsFromFlowTableForGivenMatchTask(rpcTaskContext, input, null, convertorExecutor); - return task.submit(); - } - - @Override - public Future> getFlowTablesStatistics( - final GetFlowTablesStatisticsInput input) { - LOG.debug("Calling the getFlowTablesStatistics RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetFlowTablesStatisticsTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getAllQueuesStatisticsFromAllPorts( - final GetAllQueuesStatisticsFromAllPortsInput input) { - LOG.debug("Calling the getAllQueuesStatisticsFromAllPorts RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetAllQueuesStatisticsFromAllPortsTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getAllQueuesStatisticsFromGivenPort( - final GetAllQueuesStatisticsFromGivenPortInput input) { - LOG.debug("Calling the getAllQueuesStatisticsFromGivenPort RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetAllQueuesStatisticsFromGivenPortTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> getQueueStatisticsFromGivenPort( - final GetQueueStatisticsFromGivenPortInput input) { - LOG.debug("Calling the getQueueStatisticsFromGivenPort RPC method on MessageDispatchService"); - - OFRpcTask> task = - OFRpcTaskFactory.createGetQueueStatisticsFromGivenPortTask(rpcTaskContext, input, null); - return task.submit(); - } - - @Override - public Future> setConfig(SetConfigInput input) { - OFRpcTask> task = OFRpcTaskFactory.createSetNodeConfigTask(rpcTaskContext, input, null); - return task.submit(); - } - @Override - public Optional sendEmptyTableFeatureRequest() { - LOG.debug("Send table feature request to {}",nodeId); - - final Long xid = rpcTaskContext.getSession().getNextXid(); - - MultipartRequestTableFeaturesCaseBuilder caseBuilder = new MultipartRequestTableFeaturesCaseBuilder(); - MultipartRequestTableFeaturesBuilder requestBuilder = new MultipartRequestTableFeaturesBuilder(); - caseBuilder.setMultipartRequestTableFeatures(requestBuilder.build()); - - MultipartRequestInputBuilder mprInput = new MultipartRequestInputBuilder(); - mprInput.setType(MultipartType.OFPMPTABLEFEATURES); - mprInput.setVersion(rpcTaskContext.getSession().getPrimaryConductor().getVersion()); - mprInput.setXid(xid); - mprInput.setFlags(new MultipartRequestFlags(false)); - - mprInput.setMultipartRequestBody(caseBuilder.build()); - - Future> resultFromOFLib = rpcTaskContext.getMessageService() - .multipartRequest(mprInput.build(), null); - - return Optional.of(BigInteger.valueOf(xid)); - - } - - @Override - public void requestSwitchDetails(){ - // post-handshake actions - if (version == OFConstants.OFP_VERSION_1_3) { - requestPorts(); - } - - requestDesc(); - } - - /* - * Send an OFPMP_DESC request message to the switch - */ - private void requestDesc() { - MultipartRequestInputBuilder builder = new MultipartRequestInputBuilder(); - builder.setType(MultipartType.OFPMPDESC); - builder.setVersion(version); - builder.setFlags(new MultipartRequestFlags(false)); - builder.setMultipartRequestBody(new MultipartRequestDescCaseBuilder() - .build()); - builder.setXid(getSessionContext().getNextXid()); - rpcTaskContext.getSession().getPrimaryConductor().getConnectionAdapter().multipartRequest(builder.build()); - } - - private void requestPorts() { - MultipartRequestInputBuilder builder = new MultipartRequestInputBuilder(); - builder.setType(MultipartType.OFPMPPORTDESC); - builder.setVersion(version); - builder.setFlags(new MultipartRequestFlags(false)); - builder.setMultipartRequestBody(new MultipartRequestPortDescCaseBuilder() - .build()); - builder.setXid(getSessionContext().getNextXid()); - rpcTaskContext.getSession().getPrimaryConductor().getConnectionAdapter().multipartRequest(builder.build()); - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcFutureResultTransformFactory.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcFutureResultTransformFactory.java deleted file mode 100644 index 41cb4bb639..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcFutureResultTransformFactory.java +++ /dev/null @@ -1,190 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.sal; - -import com.google.common.base.Function; -import java.util.Collection; -import org.opendaylight.controller.sal.common.util.Rpcs; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput; -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * collection of transformation functions dedicated to rpc future results - */ -public abstract class OFRpcFutureResultTransformFactory { - - private static final String MSG_ADD_FLOW_RPC = "Returning the Add Flow RPC result to MD-SAL"; - protected static final Logger LOG = LoggerFactory - .getLogger(OFRpcFutureResultTransformFactory.class); - - /** - * - * @param input rpc result input - * @param result results - * @param rpc result input type - * @return rpc result - */ - protected static RpcResult assembleRpcResult(RpcResult input, E result) { - Collection errors = input.getErrors(); - return Rpcs.getRpcResult(input.isSuccessful(), result, errors); - } - - /** - * @return translator from {@link UpdateFlowOutput} to {@link AddFlowOutput} - */ - public static Function,RpcResult> createForAddFlowOutput() { - return new Function,RpcResult>() { - - @Override - public RpcResult apply(RpcResult input) { - - UpdateFlowOutput updateFlowOutput = input.getResult(); - - AddFlowOutputBuilder addFlowOutput = new AddFlowOutputBuilder(); - addFlowOutput.setTransactionId(updateFlowOutput.getTransactionId()); - AddFlowOutput result = addFlowOutput.build(); - - RpcResult rpcResult = assembleRpcResult(input, result); - LOG.debug(MSG_ADD_FLOW_RPC); - return rpcResult; - } - - }; - } - - /** - * @return translator from {@link UpdateFlowOutput} to {@link RemoveFlowOutput} - */ - public static Function,RpcResult> createForRemoveFlowOutput() { - return new Function,RpcResult>() { - - @Override - public RpcResult apply(RpcResult input) { - - UpdateFlowOutput updateFlowOutput = input.getResult(); - - RemoveFlowOutputBuilder removeFlowOutput = new RemoveFlowOutputBuilder(); - removeFlowOutput.setTransactionId(updateFlowOutput.getTransactionId()); - RemoveFlowOutput result = removeFlowOutput.build(); - - RpcResult rpcResult = assembleRpcResult(input, result); - LOG.debug("Returning the Remove Flow RPC result to MD-SAL"); - return rpcResult; - } - - }; - } - - /** - * @return translator from {@link UpdateGroupOutput} to {@link AddGroupOutput} - */ - public static Function, RpcResult> createForAddGroupOutput() { - return new Function,RpcResult>() { - - @Override - public RpcResult apply(final RpcResult input) { - UpdateGroupOutput updateGroupOutput = input.getResult(); - - AddGroupOutputBuilder addGroupOutput = new AddGroupOutputBuilder(); - addGroupOutput.setTransactionId(updateGroupOutput.getTransactionId()); - AddGroupOutput result = addGroupOutput.build(); - - RpcResult rpcResult = assembleRpcResult(input, result); - LOG.debug("Returning the Add Group RPC result to MD-SAL"); - return rpcResult; - } - }; - } - - /** - * @return rpc result function for group udpate - */ - public static Function,RpcResult> createForRemoveGroupOutput() { - return new Function,RpcResult>() { - - @Override - public RpcResult apply(RpcResult input) { - - UpdateGroupOutput updateGroupOutput = input.getResult(); - - RemoveGroupOutputBuilder removeGroupOutput = new RemoveGroupOutputBuilder(); - removeGroupOutput.setTransactionId(updateGroupOutput.getTransactionId()); - RemoveGroupOutput result = removeGroupOutput.build(); - - RpcResult rpcResult = assembleRpcResult(input, result); - LOG.debug("Returning the Remove Group RPC result to MD-SAL"); - return rpcResult; - } - - }; - } - - /** - * @return translator from {@link UpdateMeterOutput} to {@link AddMeterOutput} - */ - public static Function, RpcResult> createForAddMeterOutput() { - return new Function,RpcResult>() { - - @Override - public RpcResult apply(final RpcResult input) { - UpdateMeterOutput updateMeterOutput = input.getResult(); - - AddMeterOutputBuilder addMeterOutput = new AddMeterOutputBuilder(); - addMeterOutput.setTransactionId(updateMeterOutput.getTransactionId()); - AddMeterOutput result = addMeterOutput.build(); - - RpcResult rpcResult = assembleRpcResult(input, result); - LOG.debug("Returning the Add Meter RPC result to MD-SAL"); - return rpcResult; - } - }; - } - - - /** - * @return return rpc result function - */ - public static Function, RpcResult> createForRemoveMeterOutput() { - return new Function,RpcResult>() { - - @Override - public RpcResult apply(final RpcResult input) { - UpdateMeterOutput updateMeterOutput = input.getResult(); - - RemoveMeterOutputBuilder removeMeterOutput = new RemoveMeterOutputBuilder(); - removeMeterOutput.setTransactionId(updateMeterOutput.getTransactionId()); - RemoveMeterOutput result = removeMeterOutput.build(); - - RpcResult rpcResult = assembleRpcResult(input, result); - LOG.debug("Returning the Remove Meter RPC result to MD-SAL"); - return rpcResult; - } - }; - } - - - - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTask.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTask.java deleted file mode 100644 index b2f0f4588e..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTask.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.sal; - -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit; - -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; - -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; - -/** - * @param input type - * @param future output type - */ -public abstract class OFRpcTask implements Callable> { - - private OFRpcTaskContext taskContext; - private T input; - private SwitchConnectionDistinguisher cookie; - - /** - * @param taskContext rpc task context - * @param input task input - * @param cookie switch connection distinguisher cookie value - */ - public OFRpcTask(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, T input) { - this.taskContext = taskContext; - this.cookie = cookie; - this.input = input; - } - - /** - * @return the cookie - */ - public SwitchConnectionDistinguisher getCookie() { - return cookie; - } - - /** - * @param cookie the cookie to set - */ - public void setCookie(SwitchConnectionDistinguisher cookie) { - this.cookie = cookie; - } - - /** - * @return the input - */ - public T getInput() { - return input; - } - - /** - * @param input the input to set - */ - public void setInput(T input) { - this.input = input; - } - - /** - * @return the rpcNotificationProviderService - */ - public NotificationProviderService getRpcNotificationProviderService() { - return taskContext.getRpcNotificationProviderService(); - } - - /** - * @return message service - * @see org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskContext#getMessageService() - */ - public IMessageDispatchService getMessageService() { - return taskContext.getMessageService(); - } - - /** - * @return session - * @see org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskContext#getSession() - */ - public SessionContext getSession() { - return taskContext.getSession(); - } - - /** - * @return max timeout - * @see org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskContext#getMaxTimeout() - */ - public long getMaxTimeout() { - return taskContext.getMaxTimeout(); - } - - /** - * @return time unit for max timeout - * @see org.opendaylight.openflowplugin.openflow.md.core.sal.OFRpcTaskContext#getMaxTimeoutUnit() - */ - public TimeUnit getMaxTimeoutUnit() { - return taskContext.getMaxTimeoutUnit(); - } - - /** - * @return protocol version - */ - public Short getVersion() { - return taskContext.getSession().getFeatures().getVersion(); - - } - - /** - * @return the taskContext - */ - public OFRpcTaskContext getTaskContext() { - return taskContext; - } - - /** - * submit task into rpc worker pool - * @return future result of task - */ - public ListenableFuture submit() { - ListenableFuture> compoundResult = getTaskContext().getRpcPool().submit(this); - return Futures.dereference(compoundResult); - } - - /** - * @return required barrier value - */ - public Boolean isBarrier() { - return null; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskContext.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskContext.java deleted file mode 100644 index d2d1964887..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskContext.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.sal; - -import java.util.concurrent.TimeUnit; - -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.yangtools.yang.binding.DataContainer; - -import com.google.common.util.concurrent.ListeningExecutorService; - -/** - * - */ -public class OFRpcTaskContext { - - private IMessageDispatchService messageService; - private SessionContext session; - private NotificationProviderService rpcNotificationProviderService; - private long maxTimeout; - private TimeUnit maxTimeoutUnit; - private ListeningExecutorService rpcPool; - private MessageSpy messageSpy; - - /** - * @return the messageService - */ - public IMessageDispatchService getMessageService() { - return messageService; - } - /** - * @param messageService the messageService to set - */ - public void setMessageService(IMessageDispatchService messageService) { - this.messageService = messageService; - } - /** - * @return the session - */ - public SessionContext getSession() { - return session; - } - /** - * @param session the session to set - */ - public void setSession(SessionContext session) { - this.session = session; - } - /** - * @return the rpcNotificationProviderService - */ - public NotificationProviderService getRpcNotificationProviderService() { - return rpcNotificationProviderService; - } - /** - * @param rpcNotificationProviderService the rpcNotificationProviderService to set - */ - public void setRpcNotificationProviderService( - NotificationProviderService rpcNotificationProviderService) { - this.rpcNotificationProviderService = rpcNotificationProviderService; - } - /** - * @return the maxTimeout - */ - public long getMaxTimeout() { - return maxTimeout; - } - /** - * @param maxTimeout the maxTimeout to set - */ - public void setMaxTimeout(long maxTimeout) { - this.maxTimeout = maxTimeout; - } - /** - * @return the maxTimeoutUnit - */ - public TimeUnit getMaxTimeoutUnit() { - return maxTimeoutUnit; - } - /** - * @param maxTimeoutUnit the maxTimeoutUnit to set - */ - public void setMaxTimeoutUnit(TimeUnit maxTimeoutUnit) { - this.maxTimeoutUnit = maxTimeoutUnit; - } - /** - * @param rpcPool executor service pool for rpc - */ - public void setRpcPool(ListeningExecutorService rpcPool) { - this.rpcPool = rpcPool; - } - - /** - * @return the rpcPool - */ - public ListeningExecutorService getRpcPool() { - return rpcPool; - } - - /** - * @param messageSpy the message spy - */ - public void setMessageSpy(MessageSpy messageSpy) { - this.messageSpy = messageSpy; - } - /** - * @return the messageSpy - */ - public MessageSpy getMessageSpy() { - return messageSpy; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskFactory.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskFactory.java deleted file mode 100644 index a0a9056dda..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskFactory.java +++ /dev/null @@ -1,2287 +0,0 @@ -/** - * Copyright (c) 2013, 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.openflow.md.core.sal; - -import com.google.common.base.Optional; -import com.google.common.util.concurrent.AsyncFunction; -import com.google.common.util.concurrent.CheckedFuture; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.JdkFutureAdapters; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.SettableFuture; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.Future; -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.openflowjava.protocol.api.util.BinContent; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.sal.NotificationComposer; -import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.GroupConvertor; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.MeterConvertor; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.PortConvertor; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.VersionConvertorData; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.VersionDatapathIdConvertorData; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.match.MatchReactor; -import org.opendaylight.openflowplugin.openflow.md.util.FlowCreatorUtil; -import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowHashIdMapping; -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.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.table.FlowKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowAdded; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowAddedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemoved; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemovedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowUpdatedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlow; -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.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.transaction.rev150304.TransactionId; -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.rev131026.Flow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupAdded; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupAddedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupRemoved; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupRemovedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.GroupUpdatedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput; -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.types.rev131018.Group; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.MeterAdded; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.MeterAddedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.MeterRemoved; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.MeterRemovedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.MeterUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.MeterUpdatedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput; -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.types.rev130918.Meter; -import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.SetConfigInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.SetConfigOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.module.config.rev141015.SetConfigOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.GroupId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MeterId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.SwitchConfigFlag; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestAggregateCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestFlowCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestGroupCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestGroupDescCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestGroupFeaturesCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestMeterCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestMeterConfigCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestMeterFeaturesCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestPortStatsCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestQueueCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestTableCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.MultipartRequestTableFeaturesCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.aggregate._case.MultipartRequestAggregateBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.flow._case.MultipartRequestFlowBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.group._case.MultipartRequestGroupBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.meter._case.MultipartRequestMeterBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.meter.config._case.MultipartRequestMeterConfigBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.port.stats._case.MultipartRequestPortStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.queue._case.MultipartRequestQueueBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.table._case.MultipartRequestTableBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.table.features._case.MultipartRequestTableFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.request.multipart.request.body.multipart.request.table.features._case.multipart.request.table.features.TableFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutput; -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.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.table.service.rev131026.UpdateTableInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutputBuilder; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; -import org.opendaylight.yangtools.yang.common.RpcError.ErrorType; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public abstract class OFRpcTaskFactory { - protected static final Logger LOG = LoggerFactory.getLogger(OFRpcTaskFactory.class); - - private OFRpcTaskFactory() { - // hiding implicit constructor - } - - /** - * @param taskContext task context - * @param input flow object input - * @param cookie switch connection distinguisher cookie value - * @param convertorExecutor - * @return UpdateFlow task - */ - public static OFRpcTask> createAddFlowTask( - OFRpcTaskContext taskContext, AddFlowInput input, - SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) { - - class OFRpcTaskImpl extends OFRpcTask> { - - private final ConvertorExecutor convertorExecutor; - private final VersionDatapathIdConvertorData data; - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, AddFlowInput input, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, input); - this.convertorExecutor = convertorExecutor; - data = new VersionDatapathIdConvertorData(getVersion()); - data.setDatapathId(getSession().getFeatures().getDatapathId()); - } - - @Override - public ListenableFuture> call() { - ListenableFuture> result = SettableFuture.create(); - - // Convert the AddFlowInput to FlowModInput - final java.util.Optional> ofFlowModInputs = - convertorExecutor.convert(getInput(), data); - - final List flowModInputs = ofFlowModInputs.orElse(Collections.emptyList()); - LOG.debug("Number of flows to push to switch: {}", flowModInputs.size()); - result = chainFlowMods(flowModInputs, 0, getTaskContext(), getCookie()); - result = OFRpcTaskUtil.chainFutureBarrier(this, result); - OFRpcTaskUtil.hookFutureNotification(this, result, - getRpcNotificationProviderService(), - createFlowAddedNotification(getInput())); - return result; - } - - @Override - public Boolean isBarrier() { - return getInput().isBarrier(); - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor); - } - - /** - * Recursive helper method for {@link OFRpcTaskFactory#createAddFlowTask(OFRpcTaskContext, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput, org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher, org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor)} - * and {@link OFRpcTaskFactory#createUpdateFlowTask(OFRpcTaskContext, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput, org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher, org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction, org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor)} to chain results - * of multiple flowmods. - * The next flowmod gets executed if the earlier one is successful. - * All the flowmods should have the same xid, in-order to cross-reference - * the notification - * @param taskContext task context - * @param ofFlowModInputs list of flow mod as input - * @param index starting index - * @param cookie switch connection distinguisher - * @return listenable future with update flow output - * - */ - protected static ListenableFuture> chainFlowMods( - final List ofFlowModInputs, final int index, - final OFRpcTaskContext taskContext, final SwitchConnectionDistinguisher cookie) { - - Future> resultFromOFLib = - createResultForFlowMod(taskContext, ofFlowModInputs.get(index), cookie); - - ListenableFuture> result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - if (ofFlowModInputs.size() > index + 1) { - // there are more flowmods to chain - return Futures.transformAsync(result, - new AsyncFunction, RpcResult>() { - @Override - public ListenableFuture> apply(RpcResult input) throws Exception { - if (input.isSuccessful()) { - return chainFlowMods(ofFlowModInputs, index + 1, taskContext, cookie); - } else { - LOG.warn("Flowmod failed. Any chained flowmods are ignored. xid:{}", - ofFlowModInputs.get(index).getXid()); - return Futures.immediateFuture(input); - } - } - } - ); - } else { - return result; - } - } - - private static Future> createResultForFlowMod( - OFRpcTaskContext taskContext, FlowModInputBuilder flowModInput, - SwitchConnectionDistinguisher cookie) { - flowModInput.setXid(taskContext.getSession().getNextXid()); - return taskContext.getMessageService().flowMod(flowModInput.build(), cookie); - } - - - /** - * @param input flow input - * @return flow added notification - */ - protected static NotificationComposer createFlowAddedNotification( - final AddFlowInput input) { - return new NotificationComposer() { - @Override - public FlowAdded compose(TransactionId tXid) { - FlowAddedBuilder newFlow = new FlowAddedBuilder((Flow) input); - newFlow.setTransactionId(tXid); - newFlow.setFlowRef(input.getFlowRef()); - return newFlow.build(); - } - }; - } - - /** - * @param taskContext task context - * @param input update flow input - * @param cookie switch connection distinguisher cookie value - * @param rwTx read write transaction - * @param convertorExecutor - * @return UpdateFlow task - */ - public static OFRpcTask> createUpdateFlowTask( - final OFRpcTaskContext taskContext, UpdateFlowInput input, - SwitchConnectionDistinguisher cookie, final ReadWriteTransaction rwTx, ConvertorExecutor convertorExecutor) { - - class OFRpcTaskImpl extends OFRpcTask> { - final ReadWriteTransaction rwTx; - private final ConvertorExecutor convertorExecutor; - private final VersionDatapathIdConvertorData data; - InstanceIdentifier iiToTable = null; - String flowId = null; - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - final UpdateFlowInput in, final ReadWriteTransaction rwTx, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, in); - this.convertorExecutor = convertorExecutor; - final FlowRef flowRef = in.getFlowRef(); - if (flowRef != null) { - InstanceIdentifier iiToFlow = (InstanceIdentifier)(flowRef.getValue()); - iiToTable = flowRef.getValue().firstIdentifierOf(Table.class); - FlowKey flowKey = iiToFlow.firstKeyOf( - org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow.class, FlowKey.class); - if (flowKey != null) { - flowId = flowKey.getId().getValue(); - } - } - this.rwTx = rwTx; - data = new VersionDatapathIdConvertorData(getVersion()); - data.setDatapathId(getSession().getFeatures().getDatapathId()); - } - - @Override - public ListenableFuture> call() { - ListenableFuture> result = null; - - UpdateFlowInput in = getInput(); - UpdatedFlow updated = in.getUpdatedFlow(); - OriginalFlow original = in.getOriginalFlow(); - - List allFlowMods = new ArrayList<>(); - java.util.Optional> ofFlowModInputs; - - if (!FlowCreatorUtil.canModifyFlow(original, updated, getVersion())) { - // We would need to remove original and add updated. - - //remove flow - RemoveFlowInputBuilder removeflow = new RemoveFlowInputBuilder(original); - java.util.Optional> ofFlowRemoveInput = - convertorExecutor.convert(removeflow.build(), data); - - if (ofFlowRemoveInput.isPresent()) { - // remove flow should be the first - allFlowMods.addAll(ofFlowRemoveInput.get()); - } - - AddFlowInputBuilder addFlowInputBuilder = new AddFlowInputBuilder(updated); - ofFlowModInputs = convertorExecutor.convert(addFlowInputBuilder.build(), data); - } else { - ofFlowModInputs = convertorExecutor.convert(updated, data); - } - - //deleting flow hash value from operational DS - if (flowId != null) { - CheckedFuture, ReadFailedException> hashDeletionFuture - = readFlowHashIdMappingFromOperationalDS(rwTx); - Futures.addCallback(hashDeletionFuture, new FutureCallback>() { - @Override - public void onSuccess(Optional optFlowHashIdMapping) { - FlowHashIdMapKey flowHashIdMapKeyToDelete = null; - if (optFlowHashIdMapping.isPresent()) { - FlowHashIdMapping flowHashIdMapping = optFlowHashIdMapping.get(); - for (FlowHashIdMap flowHashId : flowHashIdMapping.getFlowHashIdMap()) { - if (flowHashId.getFlowId().getValue().equals(flowId)) { - flowHashIdMapKeyToDelete = flowHashId.getKey(); - break; - } - } - } - if (flowHashIdMapKeyToDelete != null) { - final KeyedInstanceIdentifier iiToFlowHashIdToDelete = iiToTable - .augmentation(FlowHashIdMapping.class).child(FlowHashIdMap.class, flowHashIdMapKeyToDelete); - final InstanceIdentifier flowRef = iiToTable.child( - org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table. - Flow.class, new FlowKey(new FlowId(flowId))); - //Clean-up the respective flow as well. - rwTx.delete(LogicalDatastoreType.OPERATIONAL, flowRef); - rwTx.delete(LogicalDatastoreType.OPERATIONAL, iiToFlowHashIdToDelete); - rwTx.submit(); - } - } - - @Override - public void onFailure(Throwable t) { - LOG.debug("Reading flow-hash-id map from operational DS wasn't successful"); - } - }); - - } - - if (ofFlowModInputs.isPresent()) { - allFlowMods.addAll(ofFlowModInputs.get()); - } - - LOG.debug("Number of flows to push to switch: {}", allFlowMods.size()); - result = chainFlowMods(allFlowMods, 0, getTaskContext(), getCookie()); - - result = OFRpcTaskUtil.chainFutureBarrier(this, result); - OFRpcTaskUtil.hookFutureNotification(this, result, - getRpcNotificationProviderService(), - createFlowUpdatedNotification(in)); - - return result; - } - - - CheckedFuture, ReadFailedException> readFlowHashIdMappingFromOperationalDS(final ReadWriteTransaction rwTx) { - InstanceIdentifier iiToFlowHashIdMapping = iiToTable - .augmentation(FlowHashIdMapping.class); - return rwTx.read(LogicalDatastoreType.OPERATIONAL, iiToFlowHashIdMapping); - } - - @Override - public Boolean isBarrier() { - return getInput().getUpdatedFlow().isBarrier(); - } - } - return new OFRpcTaskImpl(taskContext, cookie, input, rwTx, convertorExecutor); - } - - - /** - * @param input update flow input - * @return flow update notification - */ - protected static NotificationComposer createFlowUpdatedNotification(final UpdateFlowInput input) { - return new NotificationComposer() { - @Override - public FlowUpdated compose(TransactionId tXid) { - FlowUpdatedBuilder updFlow = new FlowUpdatedBuilder(input.getUpdatedFlow()); - updFlow.setTransactionId(tXid); - updFlow.setFlowRef(input.getFlowRef()); - return updFlow.build(); - } - }; - } - - /** - * @param taskContext taks context - * @param input group update input - * @param cookie switch connection distinguisher cookie value - * @param convertorExecutor - * @return update group task - */ - public static OFRpcTask> createAddGroupTask( - final OFRpcTaskContext taskContext, AddGroupInput input, - final SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) { - class OFRpcTaskImpl extends OFRpcTask> { - - private final ConvertorExecutor convertorExecutor; - private final VersionDatapathIdConvertorData data; - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, AddGroupInput input, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, input); - this.convertorExecutor = convertorExecutor; - data = new VersionDatapathIdConvertorData(getVersion()); - data.setDatapathId(getSession().getFeatures().getDatapathId()); - } - - @Override - public ListenableFuture> call() { - ListenableFuture> result = SettableFuture.create(); - - // Convert the AddGroupInput to GroupModInput - final java.util.Optional ofGroupModInput = convertorExecutor.convert(getInput(), data); - final GroupModInputBuilder groupModInputBuilder = ofGroupModInput - .orElse(GroupConvertor.defaultResult(getVersion())) - .setXid(getSession().getNextXid()); - - Future> resultFromOFLib = getMessageService() - .groupMod(groupModInputBuilder.build(), getCookie()); - result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - result = OFRpcTaskUtil.chainFutureBarrier(this, result); - OFRpcTaskUtil.hookFutureNotification(this, result, - getRpcNotificationProviderService(), createGroupAddedNotification(getInput())); - - return result; - } - - @Override - public Boolean isBarrier() { - return getInput().isBarrier(); - } - }; - - return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor); - } - - - /** - * @param input group add input - * @return group added notification - */ - protected static NotificationComposer createGroupAddedNotification( - final AddGroupInput input) { - return new NotificationComposer() { - @Override - public GroupAdded compose(TransactionId tXid) { - GroupAddedBuilder groupMod = new GroupAddedBuilder((Group) input); - groupMod.setTransactionId(tXid); - groupMod.setGroupRef(input.getGroupRef()); - return groupMod.build(); - } - }; - } - - /** - * @param taskContext task context - * @param input meter add input - * @param cookie switch connection distinguisher - * @param convertorExecutor - * @return update meter task - */ - public static OFRpcTask> createAddMeterTask( - OFRpcTaskContext taskContext, AddMeterInput input, - SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) { - class OFRpcTaskImpl extends OFRpcTask> { - - private final ConvertorExecutor convertorExecutor; - private final VersionConvertorData data; - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, AddMeterInput input, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, input); - this.convertorExecutor = convertorExecutor; - data = new VersionConvertorData(getVersion()); - } - - @Override - public ListenableFuture> call() { - ListenableFuture> result = SettableFuture.create(); - - // Convert the AddMeterInput to UpdateMeterOutput - final java.util.Optional ofMeterModInput = convertorExecutor.convert(getInput(), data); - - final MeterModInputBuilder meterModInputBuilder = ofMeterModInput - .orElse(MeterConvertor.defaultResult(getVersion())) - .setXid(getSession().getNextXid()); - - Future> resultFromOFLib = getMessageService() - .meterMod(meterModInputBuilder.build(), getCookie()); - result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - result = OFRpcTaskUtil.chainFutureBarrier(this, result); - OFRpcTaskUtil.hookFutureNotification(this, result, - getRpcNotificationProviderService(), createMeterAddedNotification(getInput())); - - return result; - } - - @Override - public Boolean isBarrier() { - return getInput().isBarrier(); - } - }; - - return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor); - } - - /** - * @param input add meter input - * @return meter added notification composer - */ - protected static NotificationComposer createMeterAddedNotification( - final AddMeterInput input) { - return new NotificationComposer() { - @Override - public MeterAdded compose(TransactionId tXid) { - MeterAddedBuilder meterMod = new MeterAddedBuilder((Meter) input); - meterMod.setTransactionId(tXid); - meterMod.setMeterRef(input.getMeterRef()); - return meterMod.build(); - } - }; - } - - /** - * @param taskContext task context - * @param input update group output - * @param cookie switch connection distinguisher cookie value - * @param convertorExecutor - * @return UpdateFlow task - */ - public static OFRpcTask> createUpdateGroupTask( - OFRpcTaskContext taskContext, UpdateGroupInput input, - SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) { - class OFRpcTaskImpl extends OFRpcTask> { - - private final ConvertorExecutor convertorExecutor; - private final VersionDatapathIdConvertorData data; - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - UpdateGroupInput input, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, input); - this.convertorExecutor = convertorExecutor; - data = new VersionDatapathIdConvertorData(getVersion()); - data.setDatapathId(getSession().getFeatures().getDatapathId()); - } - - @Override - public ListenableFuture> call() { - ListenableFuture> result = null; - - // Convert the UpdateGroupInput to GroupModInput - final java.util.Optional ofGroupModInput = - convertorExecutor.convert(getInput().getUpdatedGroup(), data); - - final GroupModInputBuilder groupModInputBuilder = ofGroupModInput - .orElse(GroupConvertor.defaultResult(getVersion())) - .setXid(getSession().getNextXid()); - - Future> resultFromOFLib = - getMessageService().groupMod(groupModInputBuilder.build(), getCookie()); - result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - result = OFRpcTaskUtil.chainFutureBarrier(this, result); - OFRpcTaskUtil.hookFutureNotification(this, result, - getRpcNotificationProviderService(), createGroupUpdatedNotification(getInput())); - - return result; - } - - @Override - public Boolean isBarrier() { - return getInput().getUpdatedGroup().isBarrier(); - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor); - } - - /** - * @param input group update input - * @return group updated notification composer - */ - protected static NotificationComposer createGroupUpdatedNotification( - final UpdateGroupInput input) { - return new NotificationComposer() { - @Override - public GroupUpdated compose(TransactionId tXid) { - GroupUpdatedBuilder groupMod = new GroupUpdatedBuilder(input.getUpdatedGroup()); - groupMod.setTransactionId(tXid); - groupMod.setGroupRef(input.getGroupRef()); - return groupMod.build(); - } - }; - } - - /** - * @param taskContext task context - * @param input update meter input - * @param cookie switch connection distinguisher cookie value - * @param convertorExecutor - * @return update meter task - */ - public static OFRpcTask> createUpdateMeterTask( - OFRpcTaskContext taskContext, UpdateMeterInput input, - SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) { - class OFRpcTaskImpl extends OFRpcTask> { - - private final ConvertorExecutor convertorExecutor; - private final VersionConvertorData data; - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - UpdateMeterInput input, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, input); - this.convertorExecutor = convertorExecutor; - data = new VersionConvertorData(getVersion()); - } - - @Override - public ListenableFuture> call() { - ListenableFuture> result = null; - - // Convert the UpdateMeterInput to MeterModInput - final java.util.Optional ofMeterModInput = convertorExecutor.convert(getInput().getUpdatedMeter(), data); - - final MeterModInputBuilder meterModInputBuilder = ofMeterModInput - .orElse(MeterConvertor.defaultResult(getVersion())) - .setXid(getSession().getNextXid()); - - Future> resultFromOFLib = - getMessageService().meterMod(meterModInputBuilder.build(), getCookie()); - result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - result = OFRpcTaskUtil.chainFutureBarrier(this, result); - OFRpcTaskUtil.hookFutureNotification(this, result, - getRpcNotificationProviderService(), createMeterUpdatedNotification(getInput())); - return result; - } - - @Override - public Boolean isBarrier() { - return getInput().getUpdatedMeter().isBarrier(); - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor); - } - - /** - * @param input meter update input - * @return meter updated notification - */ - protected static NotificationComposer createMeterUpdatedNotification( - final UpdateMeterInput input) { - return new NotificationComposer() { - @Override - public MeterUpdated compose(TransactionId tXid) { - MeterUpdatedBuilder meterMod = new MeterUpdatedBuilder(input.getUpdatedMeter()); - meterMod.setTransactionId(tXid); - meterMod.setMeterRef(input.getMeterRef()); - return meterMod.build(); - } - }; - } - - - /** - * @param taskContext task context - * @param input update flow input - * @param cookie switch connection distinguisher cookie value - * @param convertorExecutor - * @return task remove flow task - */ - public static OFRpcTask> createRemoveFlowTask( - OFRpcTaskContext taskContext, RemoveFlowInput input, - SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) { - class OFRpcTaskImpl extends OFRpcTask> { - - private final VersionDatapathIdConvertorData data; - private final ConvertorExecutor convertorExecutor; - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - RemoveFlowInput input, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, input); - this.convertorExecutor = convertorExecutor; - data = new VersionDatapathIdConvertorData(getVersion()); - data.setDatapathId(getSession().getFeatures().getDatapathId()); - } - - @Override - public ListenableFuture> call() { - ListenableFuture> result = SettableFuture.create(); - - // Convert the AddFlowInput to FlowModInput - final java.util.Optional> ofFlowModInputs = convertorExecutor.convert(getInput(), data); - - result = chainFlowMods(ofFlowModInputs.orElse(Collections.emptyList()), 0, getTaskContext(), getCookie()); - result = OFRpcTaskUtil.chainFutureBarrier(this, result); - - OFRpcTaskUtil.hookFutureNotification(this, result, - getRpcNotificationProviderService(), - createFlowRemovedNotification(getInput())); - return result; - } - - @Override - public Boolean isBarrier() { - return getInput().isBarrier(); - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor); - } - - /** - * @param input remove flow input - * @return flow removed notification - */ - protected static NotificationComposer createFlowRemovedNotification( - final RemoveFlowInput input) { - return new NotificationComposer() { - @Override - public FlowRemoved compose(TransactionId tXid) { - FlowRemovedBuilder removedFlow = new FlowRemovedBuilder((Flow) input); - removedFlow.setTransactionId(tXid); - removedFlow.setFlowRef(input.getFlowRef()); - return removedFlow.build(); - } - }; - } - - - /** - * @param taskContext task context - * @param input remove group input - * @param cookie switch connection distinguisher cookie value - * @param convertorExecutor - * @return task remove group task - */ - public static OFRpcTask> createRemoveGroupTask( - final OFRpcTaskContext taskContext, RemoveGroupInput input, - final SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) { - class OFRpcTaskImpl extends OFRpcTask> { - - private final ConvertorExecutor convertorExecutor; - private final VersionDatapathIdConvertorData data; - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - RemoveGroupInput input, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, input); - this.convertorExecutor = convertorExecutor; - data = new VersionDatapathIdConvertorData(getVersion()); - data.setDatapathId(getSession().getFeatures().getDatapathId()); - } - - @Override - public ListenableFuture> call() { - ListenableFuture> result = SettableFuture.create(); - - // Convert the AddGroupInput to GroupModInput - final java.util.Optional ofGroupModInput = convertorExecutor.convert(getInput(), data); - - final GroupModInputBuilder groupModInputBuilder = ofGroupModInput - .orElse(GroupConvertor.defaultResult(getVersion())) - .setXid(getSession().getNextXid()); - - Future> resultFromOFLib = getMessageService() - .groupMod(groupModInputBuilder.build(), getCookie()); - result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - result = OFRpcTaskUtil.chainFutureBarrier(this, result); - OFRpcTaskUtil.hookFutureNotification(this, result, - getRpcNotificationProviderService(), createGroupRemovedNotification(getInput())); - - return result; - } - - @Override - public Boolean isBarrier() { - return getInput().isBarrier(); - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor); - } - - /** - * @param input group remove input - * @return group removed notification - */ - protected static NotificationComposer createGroupRemovedNotification( - final RemoveGroupInput input) { - return new NotificationComposer() { - @Override - public GroupRemoved compose(TransactionId tXid) { - GroupRemovedBuilder removedGroup = new GroupRemovedBuilder((Group) input); - removedGroup.setTransactionId(tXid); - removedGroup.setGroupRef(input.getGroupRef()); - return removedGroup.build(); - } - }; - } - - /** - * @param taskContext task context - * @param input meter removed input - * @param cookie switch connection distinguisher cookie value - * @param convertorExecutor - * @return task meter remove task - */ - public static OFRpcTask> createRemoveMeterTask( - OFRpcTaskContext taskContext, RemoveMeterInput input, - SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) { - - class OFRpcTaskImpl extends OFRpcTask> { - - private final ConvertorExecutor convertorExecutor; - private final VersionConvertorData data; - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - RemoveMeterInput input, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, input); - this.convertorExecutor = convertorExecutor; - data = new VersionConvertorData(getVersion()); - } - - @Override - public ListenableFuture> call() { - ListenableFuture> result = SettableFuture.create(); - - // Convert the RemoveMeterInput to UpdateMeterOutput - final java.util.Optional ofMeterModInput = convertorExecutor.convert(getInput(), data); - - final MeterModInputBuilder meterModInputBuilder = ofMeterModInput - .orElse(MeterConvertor.defaultResult(getVersion())) - .setXid(getSession().getNextXid()); - - Future> resultFromOFLib = getMessageService() - .meterMod(meterModInputBuilder.build(), getCookie()); - result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - result = OFRpcTaskUtil.chainFutureBarrier(this, result); - OFRpcTaskUtil.hookFutureNotification(this, result, - getRpcNotificationProviderService(), createMeterRemovedNotification(getInput())); - - return result; - } - - @Override - public Boolean isBarrier() { - return getInput().isBarrier(); - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor); - - } - - /** - * @param input remove meter input - * @return meter removed notification composer - */ - protected static NotificationComposer createMeterRemovedNotification( - final RemoveMeterInput input) { - return new NotificationComposer() { - @Override - public MeterRemoved compose(TransactionId tXid) { - MeterRemovedBuilder meterRemoved = new MeterRemovedBuilder((Meter) input); - meterRemoved.setTransactionId(tXid); - meterRemoved.setMeterRef(input.getMeterRef()); - return meterRemoved.build(); - } - }; - } - - /** - * @param taskContext task context - * @param input get all statistics input - * @param cookie switch connection distinguisher cookie value - * @return task get all group statistics task - */ - public static OFRpcTask> createGetAllGroupStatisticsTask( - final OFRpcTaskContext taskContext, GetAllGroupStatisticsInput input, - SwitchConnectionDistinguisher cookie) { - - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetAllGroupStatisticsInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() { - final SettableFuture> result = SettableFuture.create(); - - if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) { - RpcResult rpcResult = RpcResultBuilder.success( - new GetAllGroupStatisticsOutputBuilder().build()).build(); - - return Futures.immediateFuture(rpcResult); - } else { - - // Generate xid to associate it with the request - final Long xid = taskContext.getSession().getNextXid(); - - // Create multipart request body for fetch all the group stats - MultipartRequestGroupCaseBuilder caseBuilder = new MultipartRequestGroupCaseBuilder(); - MultipartRequestGroupBuilder mprGroupBuild = new MultipartRequestGroupBuilder(); - mprGroupBuild.setGroupId(new GroupId(BinContent.intToUnsignedLong( - org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731 - .Group.OFPGALL.getIntValue()))); - caseBuilder.setMultipartRequestGroup(mprGroupBuild.build()); - - // Create multipart request header - MultipartRequestInputBuilder mprInput = createMultipartHeader(MultipartType.OFPMPGROUP, - taskContext, xid); - - // Set request body to main multipart request - mprInput.setMultipartRequestBody(caseBuilder.build()); - - // Send the request, no cookies associated, use any connection - - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetAllGroupStatisticsOutput createResult() { - GetAllGroupStatisticsOutputBuilder groupStatBuilder = new GetAllGroupStatisticsOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return groupStatBuilder.build(); - } - }); - - return result; - } - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input get group description input - * @param cookie switch connection distinguisher cookie value - * @return task get group description task - */ - public static OFRpcTask> createGetGroupDescriptionTask( - final OFRpcTaskContext taskContext, GetGroupDescriptionInput input, - SwitchConnectionDistinguisher cookie) { - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetGroupDescriptionInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() - throws Exception { - final SettableFuture> result = SettableFuture.create(); - - if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) { - RpcResult rpcResult = RpcResultBuilder.success( - new GetGroupDescriptionOutputBuilder().build()).build(); - return Futures.immediateFuture(rpcResult); - } else { - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestGroupDescCaseBuilder mprGroupDescCaseBuild = - new MultipartRequestGroupDescCaseBuilder(); - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPGROUPDESC, taskContext, xid); - mprInput.setMultipartRequestBody(mprGroupDescCaseBuild.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetGroupDescriptionOutput createResult() { - GetGroupDescriptionOutputBuilder groupStatBuilder = new GetGroupDescriptionOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return groupStatBuilder.build(); - } - }); - return result; - } - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input get group feature input - * @param cookie switch connection distinguisher cookie value - * @return task get group feature task - */ - public static OFRpcTask> createGetGroupFeaturesTask( - final OFRpcTaskContext taskContext, GetGroupFeaturesInput input, - SwitchConnectionDistinguisher cookie) { - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetGroupFeaturesInput input) { - super(taskContext, cookie, input); - // TODO Auto-generated constructor stub - } - - @Override - public ListenableFuture> call() - throws Exception { - final SettableFuture> result = SettableFuture.create(); - - if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) { - RpcResult rpcResult = RpcResultBuilder.success( - new GetGroupFeaturesOutputBuilder().build()).build(); - return Futures.immediateFuture(rpcResult); - } else { - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestGroupFeaturesCaseBuilder mprGroupFeaturesBuild = - new MultipartRequestGroupFeaturesCaseBuilder(); - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPGROUPFEATURES, taskContext, xid); - mprInput.setMultipartRequestBody(mprGroupFeaturesBuild.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetGroupFeaturesOutput createResult() { - GetGroupFeaturesOutputBuilder groupFeatureBuilder = new GetGroupFeaturesOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return groupFeatureBuilder.build(); - } - }); - return result; - } - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input get group statistics input - * @param cookie switch connection distinguisher cookie value - * @return task get group statistics task - */ - public static OFRpcTask> createGetGroupStatisticsTask( - final OFRpcTaskContext taskContext, final GetGroupStatisticsInput input, - SwitchConnectionDistinguisher cookie) { - - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetGroupStatisticsInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() - throws Exception { - final SettableFuture> result = SettableFuture.create(); - - if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) { - RpcResult rpcResult = RpcResultBuilder.success( - new GetGroupStatisticsOutputBuilder().build()).build(); - return Futures.immediateFuture(rpcResult); - } else { - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestGroupCaseBuilder caseBuilder = new MultipartRequestGroupCaseBuilder(); - MultipartRequestGroupBuilder mprGroupBuild = new MultipartRequestGroupBuilder(); - mprGroupBuild.setGroupId(new GroupId(input.getGroupId().getValue())); - caseBuilder.setMultipartRequestGroup(mprGroupBuild.build()); - - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPGROUP, taskContext, xid); - mprInput.setMultipartRequestBody(caseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetGroupStatisticsOutput createResult() { - GetGroupStatisticsOutputBuilder groupStatisticsBuilder = - new GetGroupStatisticsOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return groupStatisticsBuilder.build(); - } - }); - return result; - } - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input get meter config statistics input - * @param cookie switch connection distinguisher cookie value - * @return task get all mtere config statistics task - */ - public static OFRpcTask> createGetAllMeterConfigStatisticsTask( - final OFRpcTaskContext taskContext, final GetAllMeterConfigStatisticsInput input, - SwitchConnectionDistinguisher cookie) { - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetAllMeterConfigStatisticsInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() - throws Exception { - final SettableFuture> result = SettableFuture.create(); - - if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) { - RpcResult rpcResult = RpcResultBuilder.success( - new GetAllMeterConfigStatisticsOutputBuilder().build()).build(); - return Futures.immediateFuture(rpcResult); - } else { - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestMeterConfigCaseBuilder caseBuilder = - new MultipartRequestMeterConfigCaseBuilder(); - MultipartRequestMeterConfigBuilder mprMeterConfigBuild = - new MultipartRequestMeterConfigBuilder(); - mprMeterConfigBuild.setMeterId(new MeterId(BinContent.intToUnsignedLong( - org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common - .types.rev130731.Meter.OFPMALL.getIntValue()))); - caseBuilder.setMultipartRequestMeterConfig(mprMeterConfigBuild.build()); - - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPMETERCONFIG, taskContext, xid); - mprInput.setMultipartRequestBody(caseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetAllMeterConfigStatisticsOutput createResult() { - GetAllMeterConfigStatisticsOutputBuilder allMeterConfStatBuilder = - new GetAllMeterConfigStatisticsOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return allMeterConfStatBuilder.build(); - } - }); - return result; - } - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input get all meter statistics input - * @param cookie switch connection distinguisher cookie value - * @return task get all meter statistics task - */ - public static OFRpcTask> createGetAllMeterStatisticsTask( - final OFRpcTaskContext taskContext, final GetAllMeterStatisticsInput input, - SwitchConnectionDistinguisher cookie) { - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetAllMeterStatisticsInput input) { - super(taskContext, cookie, input); - // TODO Auto-generated constructor stub - } - - @Override - public ListenableFuture> call() - throws Exception { - final SettableFuture> result = SettableFuture.create(); - - if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) { - RpcResult rpcResult = RpcResultBuilder.success( - new GetAllMeterStatisticsOutputBuilder().build()).build(); - return Futures.immediateFuture(rpcResult); - } else { - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestMeterCaseBuilder caseBuilder = - new MultipartRequestMeterCaseBuilder(); - MultipartRequestMeterBuilder mprMeterBuild = - new MultipartRequestMeterBuilder(); - mprMeterBuild.setMeterId(new MeterId(BinContent.intToUnsignedLong( - org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common - .types.rev130731.Meter.OFPMALL.getIntValue()))); - caseBuilder.setMultipartRequestMeter(mprMeterBuild.build()); - - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPMETER, taskContext, xid); - mprInput.setMultipartRequestBody(caseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetAllMeterStatisticsOutput createResult() { - GetAllMeterStatisticsOutputBuilder allMeterStatBuilder = - new GetAllMeterStatisticsOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return allMeterStatBuilder.build(); - } - }); - return result; - } - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input get meter features input - * @param cookie switch connection distinguisher cookie value - * @return task get meter feature task - */ - public static OFRpcTask> createGetMeterFeaturesTask( - final OFRpcTaskContext taskContext, final GetMeterFeaturesInput input, - SwitchConnectionDistinguisher cookie) { - - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetMeterFeaturesInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() - throws Exception { - final SettableFuture> result = SettableFuture.create(); - - if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) { - RpcResult rpcResult = RpcResultBuilder.success( - new GetMeterFeaturesOutputBuilder().build()).build(); - return Futures.immediateFuture(rpcResult); - } else { - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestMeterFeaturesCaseBuilder mprMeterFeaturesBuild = - new MultipartRequestMeterFeaturesCaseBuilder(); - - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPMETERFEATURES, taskContext, xid); - mprInput.setMultipartRequestBody(mprMeterFeaturesBuild.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetMeterFeaturesOutput createResult() { - GetMeterFeaturesOutputBuilder meterFeaturesBuilder = - new GetMeterFeaturesOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return meterFeaturesBuilder.build(); - } - }); - return result; - } - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input get meter statistics input - * @param cookie switch connection distinguisher cookie value - * @return task get meter statistics task - */ - public static OFRpcTask> createGetMeterStatisticsTask( - final OFRpcTaskContext taskContext, final GetMeterStatisticsInput input, - SwitchConnectionDistinguisher cookie) { - - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetMeterStatisticsInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() - throws Exception { - final SettableFuture> result = SettableFuture.create(); - - if (taskContext.getSession().getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) { - RpcResult rpcResult = RpcResultBuilder.success( - new GetMeterStatisticsOutputBuilder().build()).build(); - return Futures.immediateFuture(rpcResult); - } else { - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestMeterCaseBuilder caseBuilder = - new MultipartRequestMeterCaseBuilder(); - MultipartRequestMeterBuilder mprMeterBuild = - new MultipartRequestMeterBuilder(); - mprMeterBuild.setMeterId(new MeterId(input.getMeterId().getValue())); - caseBuilder.setMultipartRequestMeter(mprMeterBuild.build()); - - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPMETER, taskContext, xid); - mprInput.setMultipartRequestBody(caseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetMeterStatisticsOutput createResult() { - GetMeterStatisticsOutputBuilder meterStatBuilder = - new GetMeterStatisticsOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return meterStatBuilder.build(); - } - }); - return result; - } - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input get all node connector statistics input - * @param cookie switch connection distinguisher cookie value - * @return task get all node connector statistics task - */ - public static OFRpcTask> - createGetAllNodeConnectorsStatisticsTask( - final OFRpcTaskContext taskContext, final GetAllNodeConnectorsStatisticsInput input, - SwitchConnectionDistinguisher cookie) { - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetAllNodeConnectorsStatisticsInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() - throws Exception { - final SettableFuture> result = SettableFuture.create(); - - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestPortStatsCaseBuilder caseBuilder = - new MultipartRequestPortStatsCaseBuilder(); - MultipartRequestPortStatsBuilder mprPortStatsBuilder = - new MultipartRequestPortStatsBuilder(); - // Select all ports - mprPortStatsBuilder.setPortNo(OFConstants.OFPP_ANY); - caseBuilder.setMultipartRequestPortStats(mprPortStatsBuilder.build()); - - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPPORTSTATS, taskContext, xid); - mprInput.setMultipartRequestBody(caseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetAllNodeConnectorsStatisticsOutput createResult() { - GetAllNodeConnectorsStatisticsOutputBuilder allNodeConnectorStatBuilder = - new GetAllNodeConnectorsStatisticsOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return allNodeConnectorStatBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input get node connector statistics input - * @param cookie switch connection distinguisher cookie value - * @return task get node connector statistics task - */ - public static OFRpcTask> - createGetNodeConnectorStatisticsTask( - final OFRpcTaskContext taskContext, final GetNodeConnectorStatisticsInput input, - SwitchConnectionDistinguisher cookie) { - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetNodeConnectorStatisticsInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() - throws Exception { - final SettableFuture> result = SettableFuture.create(); - - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestPortStatsCaseBuilder caseBuilder = - new MultipartRequestPortStatsCaseBuilder(); - MultipartRequestPortStatsBuilder mprPortStatsBuilder = - new MultipartRequestPortStatsBuilder(); - // Set specific port - mprPortStatsBuilder - .setPortNo(InventoryDataServiceUtil.portNumberfromNodeConnectorId( - OpenflowVersion.get(taskContext.getSession().getFeatures().getVersion()), - input.getNodeConnectorId())); - caseBuilder.setMultipartRequestPortStats(mprPortStatsBuilder.build()); - - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPPORTSTATS, taskContext, xid); - mprInput.setMultipartRequestBody(caseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetNodeConnectorStatisticsOutput createResult() { - GetNodeConnectorStatisticsOutputBuilder allNodeConnectorStatBuilder = - new GetNodeConnectorStatisticsOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return allNodeConnectorStatBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input get all flow statistics from flow table - * @param cookie switch connection distinguisher cookie value - * @return task get all flow statistics from flow table task - */ - public static OFRpcTask> - createGetAllFlowStatisticsFromFlowTableTask( - final OFRpcTaskContext taskContext, - final GetAllFlowStatisticsFromFlowTableInput input, - SwitchConnectionDistinguisher cookie) { - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetAllFlowStatisticsFromFlowTableInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() throws Exception { - final SettableFuture> result = SettableFuture.create(); - - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestFlowBuilder mprFlowRequestBuilder = new MultipartRequestFlowBuilder(); - mprFlowRequestBuilder.setTableId(input.getTableId().getValue()); - mprFlowRequestBuilder.setOutPort(OFConstants.OFPP_ANY); - mprFlowRequestBuilder.setOutGroup(OFConstants.OFPG_ANY); - mprFlowRequestBuilder.setCookie(OFConstants.DEFAULT_COOKIE); - mprFlowRequestBuilder.setCookieMask(OFConstants.DEFAULT_COOKIE_MASK); - FlowCreatorUtil.setWildcardedFlowMatch(taskContext.getSession() - .getPrimaryConductor().getVersion(), mprFlowRequestBuilder); - - MultipartRequestFlowCaseBuilder multipartRequestFlowCaseBuilder = new MultipartRequestFlowCaseBuilder(); - multipartRequestFlowCaseBuilder.setMultipartRequestFlow(mprFlowRequestBuilder.build()); - - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPFLOW, taskContext, xid); - mprInput.setMultipartRequestBody(multipartRequestFlowCaseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetAllFlowStatisticsFromFlowTableOutput createResult() { - GetAllFlowStatisticsFromFlowTableOutputBuilder allFlowStatsFromFlowTableBuilder = - new GetAllFlowStatisticsFromFlowTableOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return allFlowStatsFromFlowTableBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input get all flow statistics from all flow table - * @param cookie switch connection distinguisher cookie value - * @return task get all flow statistics from all flow table task - */ - public static OFRpcTask> - createGetAllFlowsStatisticsFromAllFlowTablesTask( - final OFRpcTaskContext taskContext, - final GetAllFlowsStatisticsFromAllFlowTablesInput input, - SwitchConnectionDistinguisher cookie) { - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetAllFlowsStatisticsFromAllFlowTablesInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() throws Exception { - final SettableFuture> result = SettableFuture.create(); - - final Long xid = taskContext.getSession().getNextXid(); - - // Create multipart request body for fetch all the group stats - MultipartRequestFlowCaseBuilder multipartRequestFlowCaseBuilder = - new MultipartRequestFlowCaseBuilder(); - MultipartRequestFlowBuilder mprFlowRequestBuilder = - new MultipartRequestFlowBuilder(); - mprFlowRequestBuilder.setTableId(OFConstants.OFPTT_ALL); - mprFlowRequestBuilder.setOutPort(OFConstants.OFPP_ANY); - mprFlowRequestBuilder.setOutGroup(OFConstants.OFPG_ANY); - mprFlowRequestBuilder.setCookie(OFConstants.DEFAULT_COOKIE); - mprFlowRequestBuilder.setCookieMask(OFConstants.DEFAULT_COOKIE_MASK); - FlowCreatorUtil.setWildcardedFlowMatch(taskContext.getSession() - .getPrimaryConductor().getVersion(), mprFlowRequestBuilder); - - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPFLOW, taskContext, xid); - multipartRequestFlowCaseBuilder.setMultipartRequestFlow(mprFlowRequestBuilder.build()); - mprInput.setMultipartRequestBody(multipartRequestFlowCaseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetAllFlowsStatisticsFromAllFlowTablesOutput createResult() { - GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder allFlowStatsFromAllFlowTableBuilder = - new GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return allFlowStatsFromAllFlowTableBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input get flow statistics from flow table - * @param cookie switch connection distinguisher cookie value - * @param convertorExecutor - * @return task get flow statistics from flow table task - */ - public static OFRpcTask> - createGetFlowStatisticsFromFlowTableTask( - final OFRpcTaskContext taskContext, - final GetFlowStatisticsFromFlowTableInput input, SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) { - - class OFRpcTaskImpl extends OFRpcTask> { - - private final ConvertorExecutor convertorExecutor; - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetFlowStatisticsFromFlowTableInput input, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, input); - this.convertorExecutor = convertorExecutor; - } - - @Override - public ListenableFuture> call() throws Exception { - final SettableFuture> result = SettableFuture.create(); - - final Long xid = taskContext.getSession().getNextXid(); - - // Create multipart request body for fetch all the group stats - MultipartRequestFlowCaseBuilder multipartRequestFlowCaseBuilder = new MultipartRequestFlowCaseBuilder(); - MultipartRequestFlowBuilder mprFlowRequestBuilder = new MultipartRequestFlowBuilder(); - mprFlowRequestBuilder.setTableId(input.getTableId()); - - if (input.getOutPort() != null) { - mprFlowRequestBuilder.setOutPort(input.getOutPort().longValue()); - } else { - mprFlowRequestBuilder.setOutPort(OFConstants.OFPP_ANY); - } - - if (input.getOutGroup() != null) { - mprFlowRequestBuilder.setOutGroup(input.getOutGroup()); - } else { - mprFlowRequestBuilder.setOutGroup(OFConstants.OFPG_ANY); - } - - if (input.getCookie() != null) { - mprFlowRequestBuilder.setCookie(input.getCookie().getValue()); - } else { - mprFlowRequestBuilder.setCookie(OFConstants.DEFAULT_COOKIE); - } - - if (input.getCookieMask() != null) { - mprFlowRequestBuilder.setCookieMask(input.getCookieMask().getValue()); - } else { - mprFlowRequestBuilder.setCookieMask(OFConstants.DEFAULT_COOKIE_MASK); - } - - // convert and inject match - MatchReactor.getInstance().convert(input.getMatch(), taskContext.getSession() - .getPrimaryConductor().getVersion(), mprFlowRequestBuilder, convertorExecutor); - - // Set request body to main multipart request - multipartRequestFlowCaseBuilder.setMultipartRequestFlow(mprFlowRequestBuilder.build()); - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPFLOW, taskContext, xid); - mprInput.setMultipartRequestBody(multipartRequestFlowCaseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetFlowStatisticsFromFlowTableOutput createResult() { - GetFlowStatisticsFromFlowTableOutputBuilder flowStatsFromFlowTableBuilder = - new GetFlowStatisticsFromFlowTableOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return flowStatsFromFlowTableBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor); - } - - /** - * @param taskContext task context - * @param input get aggregate flow statistics from flow table for all flow input - * @param cookie switch connection distinguisher cookie value - * @return task get aggregate flow stats from flow table for all flow task - */ - public static OFRpcTask> - createGetAggregateFlowStatisticsFromFlowTableForAllFlowsTask( - final OFRpcTaskContext taskContext, - final GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput input, SwitchConnectionDistinguisher cookie) { - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() throws Exception { - final SettableFuture> result = SettableFuture.create(); - - final Long xid = taskContext.getSession().getNextXid(); - - // Create multipart request body for fetch all the group stats - MultipartRequestAggregateCaseBuilder multipartRequestAggregateCaseBuilder = new MultipartRequestAggregateCaseBuilder(); - MultipartRequestAggregateBuilder mprAggregateRequestBuilder = new MultipartRequestAggregateBuilder(); - mprAggregateRequestBuilder.setTableId(input.getTableId().getValue()); - mprAggregateRequestBuilder.setOutPort(OFConstants.OFPP_ANY); - mprAggregateRequestBuilder.setOutGroup(OFConstants.OFPG_ANY); - mprAggregateRequestBuilder.setCookie(OFConstants.DEFAULT_COOKIE); - mprAggregateRequestBuilder.setCookieMask(OFConstants.DEFAULT_COOKIE_MASK); - - FlowCreatorUtil.setWildcardedFlowMatch(taskContext.getSession() - .getPrimaryConductor().getVersion(), mprAggregateRequestBuilder); - - // Set request body to main multipart request - multipartRequestAggregateCaseBuilder.setMultipartRequestAggregate(mprAggregateRequestBuilder.build()); - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPAGGREGATE, taskContext, xid); - mprInput.setMultipartRequestBody(multipartRequestAggregateCaseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutput createResult() { - GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder flowStatsFromFlowTableBuilder = - new GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return flowStatsFromFlowTableBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input aggregate flow statistics input - * @param cookie switch connection distinguisher cookie value - * @param convertorExecutor - * @return task task to fetch the statistics - */ - public static OFRpcTask> - createGetAggregateFlowStatisticsFromFlowTableForGivenMatchTask( - final OFRpcTaskContext taskContext, - final GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput input, SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) { - class OFRpcTaskImpl extends OFRpcTask> { - - private final ConvertorExecutor convertorExecutor; - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput input, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, input); - this.convertorExecutor = convertorExecutor; - } - - @Override - public ListenableFuture> call() throws Exception { - final SettableFuture> result = SettableFuture.create(); - - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestAggregateCaseBuilder multipartRequestAggregateCaseBuilder = new MultipartRequestAggregateCaseBuilder(); - MultipartRequestAggregateBuilder mprAggregateRequestBuilder = new MultipartRequestAggregateBuilder(); - mprAggregateRequestBuilder.setTableId(input.getTableId()); - mprAggregateRequestBuilder.setOutPort(input.getOutPort().longValue()); - // TODO: repeating code - if (taskContext.getSession().getPrimaryConductor().getVersion() == - OFConstants.OFP_VERSION_1_3) { - mprAggregateRequestBuilder.setCookie(input.getCookie().getValue()); - mprAggregateRequestBuilder.setCookieMask(input.getCookieMask().getValue()); - mprAggregateRequestBuilder.setOutGroup(input.getOutGroup()); - } else { - mprAggregateRequestBuilder.setOutGroup(OFConstants.OFPG_ANY); - mprAggregateRequestBuilder.setCookie(OFConstants.DEFAULT_COOKIE); - mprAggregateRequestBuilder.setCookieMask(OFConstants.DEFAULT_COOKIE_MASK); - } - - MatchReactor.getInstance().convert(input.getMatch(), taskContext.getSession() - .getPrimaryConductor().getVersion(), mprAggregateRequestBuilder, convertorExecutor); - - FlowCreatorUtil.setWildcardedFlowMatch(taskContext.getSession() - .getPrimaryConductor().getVersion(), mprAggregateRequestBuilder); - - // Set request body to main multipart request - multipartRequestAggregateCaseBuilder.setMultipartRequestAggregate(mprAggregateRequestBuilder.build()); - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPAGGREGATE, taskContext, xid); - mprInput.setMultipartRequestBody(multipartRequestAggregateCaseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutput createResult() { - GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder aggregFlowStatsFromFlowTableBuilder = - new GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return aggregFlowStatsFromFlowTableBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor); - } - - /** - * @param taskContext task context - * @param input flow table statistics input - * @param cookie switch connection distinguisher cookie value - * @return task task to fetch table statistics - */ - public static OFRpcTask> createGetFlowTablesStatisticsTask( - final OFRpcTaskContext taskContext, final GetFlowTablesStatisticsInput input, SwitchConnectionDistinguisher cookie) { - - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetFlowTablesStatisticsInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() throws Exception { - final SettableFuture> result = SettableFuture.create(); - - final Long xid = taskContext.getSession().getNextXid(); - - // Create multipart request body for fetch all the group stats - MultipartRequestTableCaseBuilder multipartRequestTableCaseBuilder = new MultipartRequestTableCaseBuilder(); - MultipartRequestTableBuilder multipartRequestTableBuilder = new MultipartRequestTableBuilder(); - multipartRequestTableBuilder.setEmpty(true); - multipartRequestTableCaseBuilder.setMultipartRequestTable(multipartRequestTableBuilder.build()); - - // Set request body to main multipart request - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPTABLE, taskContext, xid); - mprInput.setMultipartRequestBody(multipartRequestTableCaseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetFlowTablesStatisticsOutput createResult() { - GetFlowTablesStatisticsOutputBuilder flowTableStatsBuilder = - new GetFlowTablesStatisticsOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return flowTableStatsBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input queue statistics input - * @param cookie switch connection distinguisher cookie value - * @return task task to fetch all queue statistics - */ - public static OFRpcTask> createGetAllQueuesStatisticsFromAllPortsTask( - final OFRpcTaskContext taskContext, final GetAllQueuesStatisticsFromAllPortsInput input, SwitchConnectionDistinguisher cookie) { - - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetAllQueuesStatisticsFromAllPortsInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() throws Exception { - final SettableFuture> result = SettableFuture.create(); - - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestQueueCaseBuilder caseBuilder = new MultipartRequestQueueCaseBuilder(); - MultipartRequestQueueBuilder mprQueueBuilder = new MultipartRequestQueueBuilder(); - // Select all ports - mprQueueBuilder.setPortNo(OFConstants.OFPP_ANY); - // Select all the queues - mprQueueBuilder.setQueueId(OFConstants.OFPQ_ALL); - caseBuilder.setMultipartRequestQueue(mprQueueBuilder.build()); - - // Set request body to main multipart request - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPQUEUE, taskContext, xid); - mprInput.setMultipartRequestBody(caseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetAllQueuesStatisticsFromAllPortsOutput createResult() { - GetAllQueuesStatisticsFromAllPortsOutputBuilder allQueueStatsBuilder = - new GetAllQueuesStatisticsFromAllPortsOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return allQueueStatsBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input queue statist from specific port input - * @param cookie switch connection distinguisher cookie value - * @return task task to get queue statistics from specific port - */ - public static OFRpcTask> createGetAllQueuesStatisticsFromGivenPortTask( - final OFRpcTaskContext taskContext, final GetAllQueuesStatisticsFromGivenPortInput input, SwitchConnectionDistinguisher cookie) { - - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetAllQueuesStatisticsFromGivenPortInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() throws Exception { - final SettableFuture> result = SettableFuture.create(); - - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestQueueCaseBuilder caseBuilder = new MultipartRequestQueueCaseBuilder(); - MultipartRequestQueueBuilder mprQueueBuilder = new MultipartRequestQueueBuilder(); - // Select all queues - mprQueueBuilder.setQueueId(OFConstants.OFPQ_ALL); - // Select specific port - mprQueueBuilder.setPortNo(InventoryDataServiceUtil.portNumberfromNodeConnectorId( - OpenflowVersion.get(taskContext.getSession().getFeatures().getVersion()), - input.getNodeConnectorId())); - caseBuilder.setMultipartRequestQueue(mprQueueBuilder.build()); - - // Set request body to main multipart request - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPQUEUE, taskContext, xid); - mprInput.setMultipartRequestBody(caseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetAllQueuesStatisticsFromGivenPortOutput createResult() { - GetAllQueuesStatisticsFromGivenPortOutputBuilder allQueueStatsBuilder = - new GetAllQueuesStatisticsFromGivenPortOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return allQueueStatsBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - /** - * @param taskContext task context - * @param input queue statistics from given port - * @param cookie switch connection distinguisher cookie value - * @return task task to get queue statistics from given port - */ - public static OFRpcTask> createGetQueueStatisticsFromGivenPortTask( - final OFRpcTaskContext taskContext, final GetQueueStatisticsFromGivenPortInput input, SwitchConnectionDistinguisher cookie) { - - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - GetQueueStatisticsFromGivenPortInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() throws Exception { - final SettableFuture> result = SettableFuture.create(); - - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestQueueCaseBuilder caseBuilder = new MultipartRequestQueueCaseBuilder(); - MultipartRequestQueueBuilder mprQueueBuilder = new MultipartRequestQueueBuilder(); - // Select specific queue - mprQueueBuilder.setQueueId(input.getQueueId().getValue()); - // Select specific port - mprQueueBuilder.setPortNo(InventoryDataServiceUtil.portNumberfromNodeConnectorId( - OpenflowVersion.get(taskContext.getSession().getFeatures().getVersion()), - input.getNodeConnectorId())); - caseBuilder.setMultipartRequestQueue(mprQueueBuilder.build()); - - // Set request body to main multipart request - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPQUEUE, taskContext, xid); - mprInput.setMultipartRequestBody(caseBuilder.build()); - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public GetQueueStatisticsFromGivenPortOutput createResult() { - GetQueueStatisticsFromGivenPortOutputBuilder queueStatsFromPortBuilder = - new GetQueueStatisticsFromGivenPortOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return queueStatsFromPortBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } - - static MultipartRequestInputBuilder createMultipartHeader(MultipartType multipart, - OFRpcTaskContext taskContext, Long xid) { - MultipartRequestInputBuilder mprInput = new MultipartRequestInputBuilder(); - mprInput.setType(multipart); - mprInput.setVersion(taskContext.getSession().getPrimaryConductor().getVersion()); - mprInput.setXid(xid); - mprInput.setFlags(new MultipartRequestFlags(false)); - return mprInput; - } - - private abstract static class ResultCallback implements FutureCallback> { - - private SettableFuture> result; - - /** - * @param result result - */ - public ResultCallback(SettableFuture> result) { - this.result = result; - } - - public abstract T createResult(); - - @Override - public void onSuccess(RpcResult resultArg) { - result.set(RpcResultBuilder.success(createResult()).build()); - } - - @Override - public void onFailure(Throwable t) { - result.set(RpcResultBuilder.failed().withWarning( - ErrorType.RPC, - OFConstants.ERROR_TAG_TIMEOUT, - "something wrong happened", - OFConstants.APPLICATION_TAG, - "", t).build()); - } - } - - /** - * @param taskContext task context - * @param input update port input - * @param cookie switch connection distinguisher cookie value - * @param convertorExecutor - * @return task task to update port - */ - public static OFRpcTask> createUpdatePortTask( - final OFRpcTaskContext taskContext, final UpdatePortInput input, - final SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) { - - class OFRpcTaskImpl extends OFRpcTask> { - - private final ConvertorExecutor convertorExecutor; - private final VersionConvertorData data; - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - UpdatePortInput input, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, input); - this.convertorExecutor = convertorExecutor; - data = new VersionConvertorData(getVersion()); - } - - @Override - public ListenableFuture> call() { - ListenableFuture> result = SettableFuture.create(); - final Port inputPort = input.getUpdatedPort().getPort().getPort().get(0); - - final java.util.Optional ofPortModInput = convertorExecutor.convert(inputPort, data); - - PortModInputBuilder mdInput = new PortModInputBuilder(ofPortModInput - .orElse(PortConvertor.defaultResult(getVersion()))) - .setXid(taskContext.getSession().getNextXid()); - - Future> resultFromOFLib = getMessageService() - .portMod(mdInput.build(), cookie); - result = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor); - } - - /** - * @param taskContext task context - * @param input update table input - * @param cookie switch connection distinguisher cookie value - * @param convertorExecutor - * @return task task to udpate table input - */ - public static OFRpcTask> createUpdateTableTask( - final OFRpcTaskContext taskContext, final UpdateTableInput input, - final SwitchConnectionDistinguisher cookie, ConvertorExecutor convertorExecutor) { - - class OFRpcTaskImpl extends OFRpcTask> { - - private final ConvertorExecutor convertorExecutor; - private final VersionConvertorData data; - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - UpdateTableInput input, ConvertorExecutor convertorExecutor) { - super(taskContext, cookie, input); - this.convertorExecutor = convertorExecutor; - data = new VersionConvertorData(getVersion()); - } - - @Override - public ListenableFuture> call() { - final SettableFuture> result = SettableFuture.create(); - - final Long xid = taskContext.getSession().getNextXid(); - - MultipartRequestTableFeaturesCaseBuilder caseBuilder = new MultipartRequestTableFeaturesCaseBuilder(); - MultipartRequestTableFeaturesBuilder requestBuilder = new MultipartRequestTableFeaturesBuilder(); - - final java.util.Optional> ofTableFeatureList = convertorExecutor.convert(input.getUpdatedTable(), data); - requestBuilder.setTableFeatures(ofTableFeatureList.orElse(Collections.emptyList())); - caseBuilder.setMultipartRequestTableFeatures(requestBuilder.build()); - - // Set request body to main multipart request - MultipartRequestInputBuilder mprInput = - createMultipartHeader(MultipartType.OFPMPTABLEFEATURES, taskContext, xid); - mprInput.setMultipartRequestBody(caseBuilder.build()); - - Future> resultFromOFLib = getMessageService() - .multipartRequest(mprInput.build(), getCookie()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(resultFromOFLib); - - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public UpdateTableOutput createResult() { - UpdateTableOutputBuilder queueStatsFromPortBuilder = - new UpdateTableOutputBuilder() - .setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return queueStatsFromPortBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input, convertorExecutor); - } - - public static OFRpcTask> createSetNodeConfigTask(final OFRpcTaskContext taskContext, - final SetConfigInput input, - final SwitchConnectionDistinguisher cookie) { - class OFRpcTaskImpl extends OFRpcTask> { - - public OFRpcTaskImpl(OFRpcTaskContext taskContext, SwitchConnectionDistinguisher cookie, - SetConfigInput input) { - super(taskContext, cookie, input); - } - - @Override - public ListenableFuture> call() throws Exception { - - final SettableFuture> result = SettableFuture.create(); - final Long xid = taskContext.getSession().getNextXid(); - - SetConfigInputBuilder builder = new SetConfigInputBuilder(); - SwitchConfigFlag flag = SwitchConfigFlag.valueOf(input.getFlag()); - builder.setXid(xid); - builder.setFlags(flag); - builder.setMissSendLen(input.getMissSearchLength()); - builder.setVersion(getVersion()); - ListenableFuture> resultLib = JdkFutureAdapters.listenInPoolThread(taskContext.getSession().getPrimaryConductor().getConnectionAdapter().setConfig(builder.build())); - Futures.addCallback(resultLib, new ResultCallback(result) { - @Override - public SetConfigOutput createResult() { - SetConfigOutputBuilder setConfigOutputBuilder = new SetConfigOutputBuilder(); - setConfigOutputBuilder.setTransactionId(new TransactionId(BigInteger.valueOf(xid))); - return setConfigOutputBuilder.build(); - } - }); - return result; - } - } - - return new OFRpcTaskImpl(taskContext, cookie, input); - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskUtil.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskUtil.java deleted file mode 100644 index 131e37dfd0..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskUtil.java +++ /dev/null @@ -1,205 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.sal; - -import com.google.common.base.Function; -import com.google.common.base.MoreObjects; -import com.google.common.collect.Lists; -import com.google.common.util.concurrent.AsyncFunction; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.Future; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.sal.NotificationComposer; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.openflowplugin.openflow.md.util.RpcInputOutputTuple; -import org.opendaylight.openflowplugin.openflow.md.util.TaskUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionAware; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.binding.Notification; -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcError.ErrorType; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public abstract class OFRpcTaskUtil { - protected static final Logger LOG = LoggerFactory.getLogger(OFRpcTaskUtil.class); - private OFRpcTaskUtil() { - //hiding implicit constructor - } - - public static Collection manageBarrier(final OFRpcTaskContext taskContext, final Boolean isBarrier, - final SwitchConnectionDistinguisher cookie) { - Collection errors = null; - if (MoreObjects.firstNonNull(isBarrier, Boolean.FALSE)) { - RpcInputOutputTuple>> sendBarrierRpc = - TaskUtil.sendBarrier(taskContext.getSession(), cookie, taskContext.getMessageService()); - Future> barrierFuture = sendBarrierRpc.getOutput(); - try { - RpcResult barrierResult = barrierFuture.get( - taskContext.getMaxTimeout(), taskContext.getMaxTimeoutUnit()); - if (!barrierResult.isSuccessful()) { - errors = barrierResult.getErrors(); - } - } catch (Exception e) { - RpcError rpcError = RpcResultBuilder.newWarning( - ErrorType.RPC, - OFConstants.ERROR_TAG_TIMEOUT, - "barrier sending failed", - OFConstants.APPLICATION_TAG, - "switch failed to respond on barrier request - message ordering is not preserved", - e); - errors = Lists.newArrayList(rpcError); - } - } - - if (errors == null) { - errors = Collections.emptyList(); - } - - return errors; - } - - /** - * @param task task - * @param originalResult original result - * @param notificationProviderService notification provider service - * @param notificationComposer lazy notification composer - * @param data container - * @param notification - * @param R - */ - public static , N extends Notification, I extends DataContainer> - void hookFutureNotification( - final OFRpcTask task, - final ListenableFuture originalResult, - final NotificationProviderService notificationProviderService, - final NotificationComposer notificationComposer) { - - class FutureCallbackImpl implements FutureCallback { - @Override - public void onSuccess(final R result) { - if(null == notificationProviderService) { - LOG.warn("onSuccess(): notificationServiceProvider is null, could not publish result {}",result); - } else if (notificationComposer == null) { - LOG.warn("onSuccess(): notificationComposer is null, could not publish result {}",result); - } else if(result == null) { - LOG.warn("onSuccess(): result is null, could not publish result {}",result); - } else if (result.getResult() == null) { - LOG.warn("onSuccess(): result.getResult() is null, could not publish result {}",result); - } else if (result.getResult().getTransactionId() == null) { - LOG.warn("onSuccess(): result.getResult().getTransactionId() is null, could not publish result {}",result); - } else { - notificationProviderService.publish(notificationComposer.compose(result.getResult().getTransactionId())); - task.getTaskContext().getMessageSpy().spyMessage( - task.getInput(), MessageSpy.StatisticsGroup.TO_SWITCH_SUBMITTED_SUCCESS); - } - } - - @Override - public void onFailure(final Throwable t) { - //TODO: good place to notify MD-SAL about errors - task.getTaskContext().getMessageSpy().spyMessage( - task.getInput(), MessageSpy.StatisticsGroup.TO_SWITCH_SUBMITTED_FAILURE); - } - } - - Futures.addCallback(originalResult, new FutureCallbackImpl()); - } - - /** - * @param task of rpc - * @param originalResult original result - * @param R - * @param I - * @return chained result with barrier - */ - public static - ListenableFuture> chainFutureBarrier( - final OFRpcTask> task, - final ListenableFuture> originalResult) { - - ListenableFuture> chainResult = originalResult; - if (MoreObjects.firstNonNull(task.isBarrier(), Boolean.FALSE)) { - - chainResult = Futures.transformAsync(originalResult, new AsyncFunction, RpcResult>() { - - @Override - public ListenableFuture> apply(final RpcResult input) throws Exception { - if (input.isSuccessful()) { - RpcInputOutputTuple>> sendBarrierRpc = TaskUtil.sendBarrier( - task.getSession(), task.getCookie(), task.getMessageService()); - ListenableFuture> barrierTxResult = Futures.transform( - sendBarrierRpc.getOutput(), - transformBarrierToTransactionAware(input, sendBarrierRpc.getInput())); - return barrierTxResult; - } else { - return Futures.immediateFuture(input); - } - } - - }); - } - - return chainResult; - } - - /** - * @param originalInput original input - * @param barrierInput barrier input - * @param T - * @return result - */ - protected static Function, RpcResult> transformBarrierToTransactionAware( - final RpcResult originalInput, final BarrierInput barrierInput) { - - class FunctionImpl implements Function, RpcResult> { - - @Override - public RpcResult apply(final RpcResult barrierResult) { - RpcResultBuilder rpcBuilder = null; - if (barrierResult.isSuccessful()) { - rpcBuilder = RpcResultBuilder.success(); - } else { - rpcBuilder = RpcResultBuilder.failed(); - RpcError rpcError = RpcResultBuilder.newWarning( - ErrorType.RPC, - OFConstants.ERROR_TAG_TIMEOUT, - "barrier sending failed", - OFConstants.APPLICATION_TAG, - "switch failed to respond on barrier request, barrier.xid = "+barrierInput.getXid(), - null); - List chainedErrors = new ArrayList<>(); - chainedErrors.add(rpcError); - chainedErrors.addAll(barrierResult.getErrors()); - rpcBuilder.withRpcErrors(chainedErrors); - } - - rpcBuilder.withResult(originalInput.getResult()); - - return rpcBuilder.build(); - } - } - - return new FunctionImpl(); - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OpenflowPluginConfig.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OpenflowPluginConfig.java deleted file mode 100644 index 1cda22ea86..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OpenflowPluginConfig.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2016 Ericsson 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.openflow.md.core.sal; - -/** - * Created by eshuvka on 5/16/2016. - */ -public class OpenflowPluginConfig { - - private final boolean skipTableFeatures; - - private OpenflowPluginConfig (OpenflowPluginConfigBuilder builder){ - skipTableFeatures = builder.skipTableFeatures(); - } - - public boolean skipTableFeatures(){ - return skipTableFeatures; - } - - public static OpenflowPluginConfigBuilder builder(){ - return new OpenflowPluginConfigBuilder(); - } - - public static class OpenflowPluginConfigBuilder{ - private boolean skipTableFeatures; - - public boolean skipTableFeatures(){ - return skipTableFeatures; - } - - public void setSkipTableFeatures(boolean skip){ - skipTableFeatures = skip; - } - - public OpenflowPluginConfig build() {return new OpenflowPluginConfig(this);} - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OpenflowPluginProvider.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OpenflowPluginProvider.java deleted file mode 100644 index dd88be1c5e..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OpenflowPluginProvider.java +++ /dev/null @@ -1,219 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.sal; - -import com.google.common.annotations.VisibleForTesting; -import java.util.Collection; -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.RpcProviderRegistry; -import org.opendaylight.openflowjava.protocol.spi.connection.SwitchConnectionProvider; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageCountDumper; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageObservatory; -import org.opendaylight.openflowplugin.extension.api.ExtensionConverterRegistrator; -import org.opendaylight.openflowplugin.extension.api.OpenFlowPluginExtensionRegistratorProvider; -import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterManager; -import org.opendaylight.openflowplugin.openflow.md.core.MDController; -import org.opendaylight.openflowplugin.openflow.md.core.extension.ExtensionConverterManagerImpl; -import org.opendaylight.openflowplugin.openflow.md.core.role.OfEntityManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil; -import org.opendaylight.openflowplugin.statistics.MessageSpyCounterImpl; -import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * OFPlugin provider implementation - */ -public class OpenflowPluginProvider implements AutoCloseable, OpenFlowPluginExtensionRegistratorProvider { - - private static final Logger LOG = LoggerFactory.getLogger(OpenflowPluginProvider.class); - - private static final boolean SKIP_TABLE_FEATURES = false; - - private Collection switchConnectionProviders; - - private MDController mdController; - - private MessageObservatory messageCountProvider; - - private SalRegistrationManager registrationManager; - - private ExtensionConverterManager extensionConverterManager; - - private OfpRole role; - private Boolean skipTableFeatures; - - private OFRoleManager roleManager; - private OfEntityManager entManager; - private DataBroker dataBroker; - private NotificationProviderService notificationService; - private RpcProviderRegistry rpcRegistry; - private EntityOwnershipService entityOwnershipService; - - private OpenflowPluginConfig openflowPluginConfig; - - - - /** - * Initialization of services and msgSpy counter - */ - public void initialization() { - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - - messageCountProvider = new MessageSpyCounterImpl(); - extensionConverterManager = new ExtensionConverterManagerImpl(); - roleManager = new OFRoleManager(OFSessionUtil.getSessionManager()); - openflowPluginConfig = readConfig(skipTableFeatures); - entManager = new OfEntityManager(entityOwnershipService,getOpenflowPluginConfig()); - entManager.setDataBroker(dataBroker); - entManager.init(); - - LOG.debug("dependencies gathered.."); - registrationManager = new SalRegistrationManager(convertorManager); - registrationManager.setDataService(dataBroker); - registrationManager.setPublishService(notificationService); - registrationManager.setRpcProviderRegistry(rpcRegistry); - registrationManager.setOfEntityManager(entManager); - registrationManager.init(); - - mdController = new MDController(convertorManager); - mdController.setSwitchConnectionProviders(switchConnectionProviders); - mdController.setMessageSpyCounter(messageCountProvider); - mdController.setExtensionConverterProvider(extensionConverterManager); - mdController.init(); - mdController.start(); - } - - /** - * @param switchConnectionProvider switch connection provider - */ - public void setSwitchConnectionProviders(Collection switchConnectionProvider) { - this.switchConnectionProviders = switchConnectionProvider; - } - - @Override - public void close() { - LOG.debug("close"); - - if(mdController != null) { - mdController.stop(); - mdController = null; - } - - if(registrationManager != null) { - registrationManager.close(); - registrationManager = null; - } - } - - public MessageCountDumper getMessageCountDumper() { - return messageCountProvider; - } - - /** - * @return the extensionConverterRegistry - */ - @Override - public ExtensionConverterRegistrator getExtensionConverterRegistrator() { - return extensionConverterManager; - } - - /** - * @param role of instance - */ - public void setRole(OfpRole role) { - this.role = role; - } - - /** - * @param newRole new controller role - */ - public void fireRoleChange(OfpRole newRole) { - if (!role.equals(newRole)) { - LOG.debug("Controller role was changed from {} to {}", role, newRole); - role = newRole; - switch (role) { - case BECOMEMASTER: - //TODO: implement appropriate action - roleManager.manageRoleChange(role); - break; - case BECOMESLAVE: - //TODO: implement appropriate action - roleManager.manageRoleChange(role); - break; - case NOCHANGE: - //TODO: implement appropriate action - roleManager.manageRoleChange(role); - break; - default: - LOG.warn("role not supported: {}", role); - break; - } - } - } - - private OpenflowPluginConfig readConfig(Boolean skipTableFeatures){ - - final OpenflowPluginConfig.OpenflowPluginConfigBuilder openflowCfgBuilder = OpenflowPluginConfig.builder(); - - if(skipTableFeatures !=null){ - openflowCfgBuilder.setSkipTableFeatures(skipTableFeatures.booleanValue()); - } else{ - LOG.warn("Could not load XML configuration file via ConfigSubsystem! Fallback to default config value(s)"); - openflowCfgBuilder.setSkipTableFeatures(SKIP_TABLE_FEATURES); - } - - return openflowCfgBuilder.build(); - } - - public void setDataBroker(DataBroker dataBroker) { - this.dataBroker = dataBroker; - } - - public void setNotificationService(NotificationProviderService notificationService) { - this.notificationService = notificationService; - } - - public void setRpcRegistry(RpcProviderRegistry rpcRegistry) { - this.rpcRegistry = rpcRegistry; - } - - public void setEntityOwnershipService(EntityOwnershipService entityOwnershipService) { - this.entityOwnershipService = entityOwnershipService; - } - - public void setSkipTableFeatures(Boolean skipTableFeatures) { - this.skipTableFeatures = skipTableFeatures; - } - - @VisibleForTesting - public OpenflowPluginConfig getOpenflowPluginConfig() { - return openflowPluginConfig; - } - - @VisibleForTesting - protected RpcProviderRegistry getRpcRegistry() { - return rpcRegistry; - } - - @VisibleForTesting - protected NotificationProviderService getNotificationService() { - return notificationService; - } - - @VisibleForTesting - protected DataBroker getDataBroker() { - return dataBroker; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/SalRegistrationManager.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/SalRegistrationManager.java deleted file mode 100644 index 7f3ce58b63..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/SalRegistrationManager.java +++ /dev/null @@ -1,260 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.sal; - -import com.google.common.base.Preconditions; -import java.math.BigInteger; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitch; -import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionListener; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF; -import org.opendaylight.openflowplugin.openflow.md.core.role.OfEntityManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6Address; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdatedBuilder; -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.NodeRemoved; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRemovedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdated; -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.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * session and inventory listener implementation - */ -public class SalRegistrationManager implements SessionListener, AutoCloseable { - - private static final Logger LOG = LoggerFactory.getLogger(SalRegistrationManager.class); - private final ConvertorExecutor convertorExecutor; - - private NotificationProviderService publishService; - - private DataBroker dataService; - - private RpcProviderRegistry rpcProviderRegistry; - - private final SwitchFeaturesUtil swFeaturesUtil; - - private ListenerRegistration sessionListenerRegistration; - - private OfEntityManager entManager; - - public SalRegistrationManager(ConvertorExecutor convertorExecutor) { - this.convertorExecutor = convertorExecutor; - swFeaturesUtil = SwitchFeaturesUtil.getInstance(); - } - - public NotificationProviderService getPublishService() { - return publishService; - } - - public void setPublishService(final NotificationProviderService publishService) { - this.publishService = publishService; - } - - public void setDataService(final DataBroker dataService) { - this.dataService = dataService; - } - - public void setRpcProviderRegistry(final RpcProviderRegistry rpcProviderRegistry) { - this.rpcProviderRegistry = rpcProviderRegistry; - } - - public void setOfEntityManager(OfEntityManager entManager) { - this.entManager = entManager; - } - - public void init() { - LOG.debug("init.."); - sessionListenerRegistration = getSessionManager().registerSessionListener(this); - getSessionManager().setNotificationProviderService(publishService); - getSessionManager().setDataBroker(dataService); - LOG.debug("SalRegistrationManager initialized"); - } - - @Override - public void onSessionAdded(final SwitchSessionKeyOF sessionKey, final SessionContext context) { - GetFeaturesOutput features = context.getFeatures(); - BigInteger datapathId = features.getDatapathId(); - InstanceIdentifier identifier = identifierFromDatapathId(datapathId); - NodeRef nodeRef = new NodeRef(identifier); - NodeId nodeId = nodeIdFromDatapathId(datapathId); - ModelDrivenSwitch ofSwitch = new ModelDrivenSwitchImpl(nodeId, identifier, context, convertorExecutor); - - NotificationQueueWrapper wrappedNotification = new NotificationQueueWrapper( - nodeAdded(ofSwitch, features, nodeRef), - context.getFeatures().getVersion()); - - reqOpenflowEntityOwnership(ofSwitch, context, wrappedNotification, rpcProviderRegistry); - } - - @Override - public void setRole (SessionContext context) { - entManager.setSlaveRole(context); - } - - @Override - public void onSessionRemoved(final SessionContext context) { - GetFeaturesOutput features = context.getFeatures(); - BigInteger datapathId = features.getDatapathId(); - InstanceIdentifier identifier = identifierFromDatapathId(datapathId); - NodeRef nodeRef = new NodeRef(identifier); - NodeId nodeId = nodeIdFromDatapathId(datapathId); - unregOpenflowEntityOwnership(nodeId); - NodeRemoved nodeRemoved = nodeRemoved(nodeRef); - - ModelDrivenSwitchRegistration registration = context.getProviderRegistration(); - if (null != registration) { - registration.close(); - context.setProviderRegistration(null); - } - LOG.debug("ModelDrivenSwitch for {} unregistered from MD-SAL.", datapathId); - - NotificationQueueWrapper wrappedNotification = new NotificationQueueWrapper( - nodeRemoved, context.getFeatures().getVersion()); - context.getNotificationEnqueuer().enqueueNotification(wrappedNotification); - } - - private NodeUpdated nodeAdded(final ModelDrivenSwitch sw, final GetFeaturesOutput features, final NodeRef nodeRef) { - NodeUpdatedBuilder builder = new NodeUpdatedBuilder(); - builder.setId(sw.getNodeId()); - builder.setNodeRef(nodeRef); - - FlowCapableNodeUpdatedBuilder builder2 = new FlowCapableNodeUpdatedBuilder(); - try { - builder2.setIpAddress(getIpAddressOf(sw)); - builder2.setPortNumber(getPortNumberOf(sw)); - } catch (Exception e) { - LOG.warn("IP address/Port Number of the node {} cannot be obtained.", sw.getNodeId(), e); - } - builder2.setSwitchFeatures(swFeaturesUtil.buildSwitchFeatures(features)); - builder.addAugmentation(FlowCapableNodeUpdated.class, builder2.build()); - - return builder.build(); - } - - private static IpAddress getIpAddressOf(final ModelDrivenSwitch sw) { - SessionContext sessionContext = sw.getSessionContext(); - Preconditions.checkNotNull(sessionContext.getPrimaryConductor(), - "primary conductor must not be NULL -> " + sw.getNodeId()); - Preconditions.checkNotNull(sessionContext.getPrimaryConductor().getConnectionAdapter(), - "connection adapter of primary conductor must not be NULL -> " + sw.getNodeId()); - InetSocketAddress remoteAddress = sessionContext.getPrimaryConductor().getConnectionAdapter() - .getRemoteAddress(); - if (remoteAddress == null) { - LOG.warn("IP address of the node {} cannot be obtained. No connection with switch.", sw.getNodeId()); - return null; - } - return resolveIpAddress(remoteAddress.getAddress()); - } - - private static IpAddress resolveIpAddress(final InetAddress address) { - String hostAddress = address.getHostAddress(); - if (address instanceof Inet4Address) { - return new IpAddress(new Ipv4Address(hostAddress)); - } - if (address instanceof Inet6Address) { - return new IpAddress(new Ipv6Address(hostAddress)); - } - throw new IllegalArgumentException("Unsupported IP address type!"); - } - - private static PortNumber getPortNumberOf(ModelDrivenSwitch sw) { - SessionContext sessionContext = sw.getSessionContext(); - - Preconditions.checkNotNull(sessionContext.getPrimaryConductor(), - "primary conductor must not be NULL -> " + sw.getNodeId()); - Preconditions.checkNotNull(sessionContext.getPrimaryConductor().getConnectionAdapter(), - "connection adapter of primary conductor must not be NULL -> " + sw.getNodeId()); - InetSocketAddress remoteAddress = sessionContext.getPrimaryConductor().getConnectionAdapter() - .getRemoteAddress(); - if (remoteAddress == null) { - LOG.warn("Port Number of the node {} cannot be obtained. No connection with switch.", sw.getNodeId()); - return null; - } - return resolvePortNumber(remoteAddress.getPort()); - } - - private static PortNumber resolvePortNumber(int port) { - PortNumber portNo = new PortNumber(port); - return portNo; - } - - private static NodeRemoved nodeRemoved(final NodeRef nodeRef) { - NodeRemovedBuilder builder = new NodeRemovedBuilder(); - builder.setNodeRef(nodeRef); - return builder.build(); - } - - public static InstanceIdentifier identifierFromDatapathId(final BigInteger datapathId) { - NodeKey nodeKey = nodeKeyFromDatapathId(datapathId); - InstanceIdentifierBuilder builder = InstanceIdentifier.builder(Nodes.class).child(Node.class, nodeKey); - return builder.build(); - } - - public static NodeKey nodeKeyFromDatapathId(final BigInteger datapathId) { - return new NodeKey(nodeIdFromDatapathId(datapathId)); - } - - public static NodeId nodeIdFromDatapathId(final BigInteger datapathId) { - // FIXME: Convert to textual representation of datapathID - String current = String.valueOf(datapathId); - return new NodeId("openflow:" + current); - } - - public SessionManager getSessionManager() { - return OFSessionUtil.getSessionManager(); - } - - @Override - public void close() { - dataService = null; - rpcProviderRegistry = null; - publishService = null; - if (sessionListenerRegistration != null) { - sessionListenerRegistration.close(); - } - } - - private void reqOpenflowEntityOwnership(ModelDrivenSwitch ofSwitch, - SessionContext context, - NotificationQueueWrapper wrappedNotification, - RpcProviderRegistry rpcProviderRegistry) { - context.setValid(true); - entManager.requestOpenflowEntityOwnership(ofSwitch, context, wrappedNotification, rpcProviderRegistry); - } - - private void unregOpenflowEntityOwnership(NodeId nodeId) { - entManager.unregisterEntityOwnershipRequest(nodeId); - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/SwitchFeaturesUtil.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/SwitchFeaturesUtil.java index 766b426e38..8a542190b1 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/SwitchFeaturesUtil.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/sal/SwitchFeaturesUtil.java @@ -18,10 +18,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731 import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * @author jsebin - * - */ public final class SwitchFeaturesUtil { private static final Logger LOG = LoggerFactory.getLogger(SwitchFeaturesUtil.class); diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/ConjunctSessionManager.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/ConjunctSessionManager.java deleted file mode 100644 index acdbd14841..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/ConjunctSessionManager.java +++ /dev/null @@ -1,18 +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.openflow.md.core.session; - -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager; -import org.opendaylight.openflowplugin.extension.api.core.session.ExtensionSessionManager; - -/** - * Created by Martin Bobak mbobak@cisco.com on 10/16/14. - */ -public interface ConjunctSessionManager extends SessionManager, ExtensionSessionManager { -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/ExtensionSessionManagerImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/ExtensionSessionManagerImpl.java new file mode 100644 index 0000000000..5a0b62f8b4 --- /dev/null +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/ExtensionSessionManagerImpl.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.openflowplugin.openflow.md.core.session; + +import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider; +import org.opendaylight.openflowplugin.extension.api.core.session.ExtensionSessionManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ExtensionSessionManagerImpl implements ExtensionSessionManager { + + protected static final Logger LOG = LoggerFactory.getLogger(ExtensionSessionManagerImpl.class); + private static ExtensionSessionManagerImpl INSTANCE; + private ExtensionConverterProvider extensionConverterProvider; + + + /** + * @return singleton instance + */ + public static ExtensionSessionManager getInstance() { + if (INSTANCE == null) { + INSTANCE = new ExtensionSessionManagerImpl(); + } + + return INSTANCE; + } + + private ExtensionSessionManagerImpl() { + } + + @Override + public void setExtensionConverterProvider( + ExtensionConverterProvider extensionConverterProvider) { + this.extensionConverterProvider = extensionConverterProvider; + } + + @Override + public ExtensionConverterProvider getExtensionConverterProvider() { + return extensionConverterProvider; + } +} \ No newline at end of file diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/FeaturesV10Bandwidth.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/FeaturesV10Bandwidth.java deleted file mode 100644 index e27ab4ef9f..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/FeaturesV10Bandwidth.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.session; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping; - -/** - * - * @author jsebin - * - * Singleton for extracting port features for OF 1.0 - */ -public class FeaturesV10Bandwidth implements IGetBandwith { - - private static FeaturesV10Bandwidth instance = new FeaturesV10Bandwidth(); - - private FeaturesV10Bandwidth() {} - - /** - * - * @return instance of class - */ - public static FeaturesV10Bandwidth getInstance(){ - return instance; - } - - @Override - public boolean getBandwidth(PortGrouping port) { - return (port.getCurrentFeaturesV10().is_100mbFd() | port.getCurrentFeaturesV10().is_100mbHd() | port.getCurrentFeaturesV10().is_10gbFd() | - port.getCurrentFeaturesV10().is_10mbFd() | port.getCurrentFeaturesV10().is_10mbHd() | port.getCurrentFeaturesV10().is_1gbFd() | - port.getCurrentFeaturesV10().is_1gbHd() | port.getCurrentFeaturesV10().isAutoneg() | port.getCurrentFeaturesV10().isCopper() | - port.getCurrentFeaturesV10().isFiber() | port.getCurrentFeaturesV10().isPause() | port.getCurrentFeaturesV10().isPauseAsym()); - } - - - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/FeaturesV13Bandwidth.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/FeaturesV13Bandwidth.java deleted file mode 100644 index ff8efd4609..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/FeaturesV13Bandwidth.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.session; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping; - -/** - * - * @author jsebin - * - * Singleton for extracting port features for OF 1.3 - */ -public class FeaturesV13Bandwidth implements IGetBandwith { - - private static FeaturesV13Bandwidth instance = new FeaturesV13Bandwidth(); - - private FeaturesV13Bandwidth() {} - - /** - * - * @return instance of class - */ - public static FeaturesV13Bandwidth getInstance(){ - return instance; - } - - @Override - public boolean getBandwidth(PortGrouping port) { - return (port.getCurrentFeatures().is_100gbFd() | port.getCurrentFeatures().is_100mbFd() | port.getCurrentFeatures().is_100mbHd() | - port.getCurrentFeatures().is_10gbFd() | port.getCurrentFeatures().is_10mbFd() | port.getCurrentFeatures().is_10mbHd() | - port.getCurrentFeatures().is_1gbFd() | port.getCurrentFeatures().is_1gbHd() | port.getCurrentFeatures().is_1tbFd() | - port.getCurrentFeatures().is_40gbFd() | port.getCurrentFeatures().isAutoneg() | port.getCurrentFeatures().isCopper() | - port.getCurrentFeatures().isFiber() | port.getCurrentFeatures().isOther() | port.getCurrentFeatures().isPause() | - port.getCurrentFeatures().isPauseAsym()); - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/IGetBandwith.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/IGetBandwith.java deleted file mode 100644 index 94b32cd256..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/IGetBandwith.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.session; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping; - -/** - * Utility for extracting bandwith from port according to port version - * - * @author jsebin - * - */ -public interface IGetBandwith { - - /** - * - * @param port port group - * @return port bandwidth - */ - public boolean getBandwidth(PortGrouping port); -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/MessageDispatchServiceImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/MessageDispatchServiceImpl.java deleted file mode 100644 index c70130c89e..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/MessageDispatchServiceImpl.java +++ /dev/null @@ -1,327 +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.openflow.md.core.session; - -import com.google.common.base.Function; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.JdkFutureAdapters; -import com.google.common.util.concurrent.ListenableFuture; - -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowplugin.api.ConnectionException; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.util.RpcResultUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.*; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutputBuilder; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.math.BigInteger; -import java.util.concurrent.Future; - -/** - * message dispatch service to send the message to switch. - * - * @author AnilGujele - */ -public class MessageDispatchServiceImpl implements IMessageDispatchService { - - private static final Logger LOG = LoggerFactory.getLogger(MessageDispatchServiceImpl.class); - private SessionContext session; - - /** - * constructor - * - * @param session - MessageDispatchService for this session - */ - public MessageDispatchServiceImpl(SessionContext session) { - this.session = session; - } - - /** - * get proper connection adapter to send the message to switch. - * - * @param cookie to identify the right connection, it can be null also. - * @return connectionAdapter associated with cookie, otherwise return best - * suitable connection. - */ - - private ConnectionAdapter getConnectionAdapter(SwitchConnectionDistinguisher cookie) throws ConnectionException { - - if (!session.isValid()) { - LOG.warn("No valid connection found for the node [datapath-id : {}]", session.getSessionKey().getId()); - throw new ConnectionException(CONNECTION_ERROR_MESSAGE); - } - LOG.debug("finding connecton for cookie value {}. ", cookie); - // set main connection as default - ConnectionAdapter connectionAdapter = session.getPrimaryConductor().getConnectionAdapter(); - if (null != cookie) { - ConnectionConductor conductor = session.getAuxiliaryConductor(cookie); - // check if auxiliary connection exist - if (null != conductor) { - LOG.debug("found auxiliary connection for the cookie."); - connectionAdapter = conductor.getConnectionAdapter(); - } - } else { - // TODO: pick connection to utilize all the available connection. - } - return connectionAdapter; - } - - @Override - public Future> barrier(BarrierInput input, SwitchConnectionDistinguisher cookie) { - try { - return getConnectionAdapter(cookie).barrier(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - } - - @Override - public Future> experimenter(ExperimenterInput input, SwitchConnectionDistinguisher cookie) { - try { - return getConnectionAdapter(cookie).experimenter(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - } - - @Override - public Future> flowMod(final FlowModInput input, SwitchConnectionDistinguisher cookie) { - LOG.debug("Calling OFLibrary flowMod"); - Future> response = null; - try { - response = getConnectionAdapter(cookie).flowMod(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - - // appending xid - ListenableFuture> xidResult = Futures.transform( - JdkFutureAdapters.listenInPoolThread(response), - new Function, RpcResult>() { - - @Override - public RpcResult apply(final RpcResult inputArg) { - UpdateFlowOutputBuilder flowModOutput = new UpdateFlowOutputBuilder(); - BigInteger bigIntXid = BigInteger.valueOf(input.getXid()); - flowModOutput.setTransactionId(new TransactionId(bigIntXid)); - - UpdateFlowOutput result = flowModOutput.build(); - RpcResult rpcResult = RpcResultBuilder - .status(inputArg.isSuccessful()) - .withResult(result).withRpcErrors(inputArg.getErrors()) - .build(); - return rpcResult; - } - }); - - return xidResult; - } - - @Override - public Future> getAsync(GetAsyncInput input, SwitchConnectionDistinguisher cookie) { - try { - return getConnectionAdapter(cookie).getAsync(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - } - - @Override - public Future> getConfig(GetConfigInput input, SwitchConnectionDistinguisher cookie) { - try { - return getConnectionAdapter(cookie).getConfig(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - } - - @Override - public Future> getFeatures(GetFeaturesInput input, SwitchConnectionDistinguisher cookie) { - try { - return getConnectionAdapter(cookie).getFeatures(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - } - - @Override - public Future> getQueueConfig(GetQueueConfigInput input, - SwitchConnectionDistinguisher cookie) { - try { - return getConnectionAdapter(cookie).getQueueConfig(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - } - - @Override - public Future> groupMod(final GroupModInput input, SwitchConnectionDistinguisher cookie) { - LOG.debug("Calling OFLibrary groupMod"); - Future> response = null; - try { - response = getConnectionAdapter(cookie).groupMod(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - - // appending xid - ListenableFuture> xidResult = Futures.transform( - JdkFutureAdapters.listenInPoolThread(response), - new Function, RpcResult>() { - - @Override - public RpcResult apply(final RpcResult inputArg) { - UpdateGroupOutputBuilder groupModOutput = new UpdateGroupOutputBuilder(); - BigInteger bigIntXid = BigInteger.valueOf(input.getXid()); - groupModOutput.setTransactionId(new TransactionId(bigIntXid)); - - UpdateGroupOutput result = groupModOutput.build(); - RpcResult rpcResult = RpcResultBuilder - .status(inputArg.isSuccessful()).withResult(result) - .withRpcErrors(inputArg.getErrors()).build(); - return rpcResult; - } - }); - - return xidResult; - } - - @Override - public Future> meterMod(final MeterModInput input, SwitchConnectionDistinguisher cookie) { - LOG.debug("Calling OFLibrary meterMod"); - Future> response = null; - try { - response = getConnectionAdapter(cookie).meterMod(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - - // appending xid - ListenableFuture> xidResult = Futures.transform( - JdkFutureAdapters.listenInPoolThread(response), - new Function, RpcResult>() { - - @Override - public RpcResult apply(final RpcResult inputArg) { - UpdateMeterOutputBuilder meterModOutput = new UpdateMeterOutputBuilder(); - BigInteger bigIntXid = BigInteger.valueOf(input.getXid()); - meterModOutput.setTransactionId(new TransactionId(bigIntXid)); - - UpdateMeterOutput result = meterModOutput.build(); - RpcResult rpcResult = RpcResultBuilder - .status(inputArg.isSuccessful()).withResult(result) - .withRpcErrors(inputArg.getErrors()).build(); - return rpcResult; - } - }); - - return xidResult; - } - - @Override - public Future> multipartRequest(MultipartRequestInput input, SwitchConnectionDistinguisher cookie) { - try { - return getConnectionAdapter(cookie).multipartRequest(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - } - - @Override - public Future> packetOut(PacketOutInput input, SwitchConnectionDistinguisher cookie) { - try { - return getConnectionAdapter(cookie).packetOut(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - } - - @Override - public Future> portMod(final PortModInput input, SwitchConnectionDistinguisher cookie) { - LOG.debug("Calling OFLibrary portMod"); - Future> response = null; - try { - response = getConnectionAdapter(cookie).portMod(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - - // appending xid - ListenableFuture> xidResult = Futures.transform( - JdkFutureAdapters.listenInPoolThread(response), - new Function, RpcResult>() { - - @Override - public RpcResult apply(final RpcResult inputArg) { - UpdatePortOutputBuilder portModOutput = new UpdatePortOutputBuilder(); - BigInteger bigIntXid = BigInteger.valueOf(input.getXid()); - portModOutput.setTransactionId(new TransactionId(bigIntXid)); - - UpdatePortOutput result = portModOutput.build(); - RpcResult rpcResult = RpcResultBuilder - .status(inputArg.isSuccessful()).withResult(result) - .withRpcErrors(inputArg.getErrors()).build(); - return rpcResult; - } - }); - - return xidResult; - } - - @Override - public Future> roleRequest(RoleRequestInput input, SwitchConnectionDistinguisher cookie) { - try { - return getConnectionAdapter(cookie).roleRequest(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - } - - @Override - public Future> setAsync(SetAsyncInput input, SwitchConnectionDistinguisher cookie) { - try { - return getConnectionAdapter(cookie).setAsync(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - } - - @Override - public Future> setConfig(SetConfigInput input, SwitchConnectionDistinguisher cookie) { - try { - return getConnectionAdapter(cookie).setConfig(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - } - - @Override - public Future> tableMod(TableModInput input, SwitchConnectionDistinguisher cookie) { - try { - return getConnectionAdapter(cookie).tableMod(input); - } catch (ConnectionException e) { - return RpcResultUtil.getRpcErrorFuture(e); - } - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/OFRoleManager.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/OFRoleManager.java deleted file mode 100644 index fa5f7a519b..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/OFRoleManager.java +++ /dev/null @@ -1,109 +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.openflow.md.core.session; - -import com.google.common.base.MoreObjects; -import com.google.common.base.Preconditions; -import com.google.common.util.concurrent.CheckedFuture; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.MoreExecutors; -import java.math.BigInteger; -import java.util.Comparator; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.PriorityBlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager; -import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor; -import org.opendaylight.openflowplugin.openflow.md.util.RoleUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * manage OF-role propagation to devices - */ -public class OFRoleManager implements AutoCloseable { - - /** - * starting value of generationId - */ - public static final BigInteger MAX_GENERATION_ID = new BigInteger("ffffffffffffffff", 16); - - private static final Logger LOG = LoggerFactory.getLogger(OFRoleManager.class); - - private static final long TIMEOUT = 2000; - - private static final TimeUnit TIMEOUT_UNIT = TimeUnit.MILLISECONDS; - - private static final int RETRY_LIMIT = 42; - - private final ListeningExecutorService broadcastPool; - - private final BlockingQueue workQueue; - - private final SessionManager sessionManager; - - /** - * @param sessionManager switch connection session manager - */ - public OFRoleManager(final SessionManager sessionManager) { - Preconditions.checkNotNull("Session manager can not be empty.", sessionManager); - this.sessionManager = sessionManager; - workQueue = new PriorityBlockingQueue<>(500, new Comparator() { - @Override - public int compare(final RolePushTask o1, final RolePushTask o2) { - return Integer.compare(o1.getPriority(), o2.getPriority()); - } - }); - ThreadPoolLoggingExecutor delegate = new ThreadPoolLoggingExecutor( - 1, 1, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), "ofRoleBroadcast"); - broadcastPool = MoreExecutors.listeningDecorator( - delegate); - } - - /** - * change role on each connected device - * - * @param role openflow role - */ - public void manageRoleChange(final OfpRole role) { - for (final SessionContext session : sessionManager.getAllSessions()) { - try { - workQueue.put(new RolePushTask(role, session)); - } catch (InterruptedException e) { - LOG.warn("Processing of role request failed while enqueueing role task: {}", e.getMessage()); - } - } - - while (!workQueue.isEmpty()) { - RolePushTask task = workQueue.poll(); - ListenableFuture rolePushResult = broadcastPool.submit(task); - CheckedFuture rolePushResultChecked = - RoleUtil.makeCheckedRuleRequestFxResult(rolePushResult); - try { - Boolean succeeded = rolePushResultChecked.checkedGet(TIMEOUT, TIMEOUT_UNIT); - if (!MoreObjects.firstNonNull(succeeded, Boolean.FALSE)) { - if (task.getRetryCounter() < RETRY_LIMIT) { - workQueue.offer(task); - } - } - } catch (RolePushException | TimeoutException e) { - LOG.warn("failed to process role request: {}", e); - } - } - } - - @Override - public void close() throws Exception { - broadcastPool.shutdown(); - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/OFSessionUtil.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/OFSessionUtil.java index 716f986c66..85ad97f334 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/OFSessionUtil.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/OFSessionUtil.java @@ -8,178 +8,16 @@ package org.opendaylight.openflowplugin.openflow.md.core.session; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF; -import org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey; import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider; -import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.opendaylight.openflowplugin.extension.api.core.session.ExtensionSessionManager; -/** - * @author mirehak - */ public abstract class OFSessionUtil { - private static final Logger LOG = LoggerFactory - .getLogger(OFSessionUtil.class); - - /** - * @param connectionConductor switch connection conductor - * @param features switch feature output - * @param version openflow version - */ - // public static void registerSession(ConnectionConductorImpl connectionConductor, - public static SessionContext registerSession(ConnectionConductorImpl connectionConductor, - GetFeaturesOutput features, short version) { - SwitchSessionKeyOF sessionKey = createSwitchSessionKey(features - .getDatapathId()); - SessionContext sessionContext = getSessionManager().getSessionContext(sessionKey); - if (LOG.isDebugEnabled()) { - LOG.debug("registering sessionKey: {}", Arrays.toString(sessionKey.getId())); - } - - if (features.getAuxiliaryId() == null || features.getAuxiliaryId() == 0) { - // handle primary - if (sessionContext != null) { - LOG.warn("duplicate datapathId occured while registering new switch session: " - + dumpDataPathId(features.getDatapathId())); - getSessionManager().invalidateSessionContext(sessionKey); - } - // register new session context (based primary conductor) - SessionContextOFImpl context = new SessionContextOFImpl(); - context.setPrimaryConductor(connectionConductor); - context.setNotificationEnqueuer(connectionConductor); - context.setFeatures(features); - context.setSessionKey(sessionKey); - context.setSeed((int) System.currentTimeMillis()); - connectionConductor.setSessionContext(context); - getSessionManager().addSessionContext(sessionKey, context); - } else { - // handle auxiliary - if (sessionContext == null) { - throw new IllegalStateException("unexpected auxiliary connection - primary connection missing: " - + dumpDataPathId(features.getDatapathId())); - } else { - // register auxiliary conductor into existing sessionContext - SwitchConnectionDistinguisher auxiliaryKey = createConnectionCookie(features, sessionContext.getSeed()); - if (sessionContext.getAuxiliaryConductor(auxiliaryKey) != null) { - LOG.warn("duplicate datapathId+auxiliary occured while registering switch session: " - + dumpDataPathId(features.getDatapathId()) - + " | " - + features.getAuxiliaryId()); - getSessionManager().invalidateAuxiliary(sessionKey, - auxiliaryKey); - } - - sessionContext.addAuxiliaryConductor(auxiliaryKey, - connectionConductor); - connectionConductor.setSessionContext(sessionContext); - connectionConductor.setConnectionCookie(auxiliaryKey); - } - } - - // check registration result - SessionContext resulContext = getSessionManager().getSessionContext(sessionKey); - if (resulContext == null) { - throw new IllegalStateException("session context registration failed"); - } else { - if (!resulContext.isValid()) { - throw new IllegalStateException("registered session context is invalid"); - } - } - return(resulContext); - } - - public static void setRole(SessionContext sessionContext) - { - getSessionManager().setRole(sessionContext); - } - - /** - * @param datapathId switch datapath id - * @return readable version of datapathId (hex) - */ - public static String dumpDataPathId(BigInteger datapathId) { - return datapathId.toString(16); - } - - /** - * @param datapathId switch datapath id - * @return new session key - */ - public static SwitchSessionKeyOF createSwitchSessionKey( - BigInteger datapathId) { - SwitchSessionKeyOF key = new SwitchSessionKeyOF(); - key.setDatapathId(datapathId); - return key; - } - - /** - * @param features switch feature output - * @param seed seed value - * @return connection cookie key - * @see #createConnectionCookie(BigInteger,short, int) - */ - public static SwitchConnectionDistinguisher createConnectionCookie( - GetFeaturesOutput features, int seed) { - return createConnectionCookie(features.getDatapathId(), - features.getAuxiliaryId(), seed); - } - - /** - * @param datapathId switch datapath id - * @param auxiliaryId connection aux id - * @param seed seed value - * @return connection cookie key - */ - public static SwitchConnectionDistinguisher createConnectionCookie( - BigInteger datapathId, short auxiliaryId, int seed) { - SwitchConnectionCookieOFImpl cookie = null; - cookie = new SwitchConnectionCookieOFImpl(); - cookie.setAuxiliaryId(auxiliaryId); - cookie.init(datapathId.intValue() + seed); - return cookie; - } - /** * @return session manager singleton instance */ - public static ConjunctSessionManager getSessionManager() { - return SessionManagerOFImpl.getInstance(); - } - - /** - * release session manager singleton instance - */ - public static void releaseSessionManager() { - SessionManagerOFImpl.releaseInstance(); - } - - /** - * @return session manager listener Map - */ - public static Map>>> getTranslatorMap() { - return getSessionManager().getTranslatorMapping(); - } - - /** - * @return pop listener Map - */ - public static Map, Collection>> getPopListenerMapping() { - return getSessionManager().getPopListenerMapping(); + public static ExtensionSessionManager getSessionManager() { + return ExtensionSessionManagerImpl.getInstance(); } /** @@ -189,11 +27,4 @@ public abstract class OFSessionUtil { return getSessionManager().getExtensionConverterProvider(); } - /** - * @return collection of all sessions - */ - public static Collection getAllSessions() { - return getSessionManager().getAllSessions(); - } - } diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/PortFeaturesUtil.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/PortFeaturesUtil.java deleted file mode 100644 index 5a960e5802..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/PortFeaturesUtil.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.session; - -import java.util.HashMap; -import java.util.Map; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Wrapper for bandwidth extracting utilities - * - * @author jsebin - * - */ -public class PortFeaturesUtil { - - private static PortFeaturesUtil instance = new PortFeaturesUtil(); - - private final Map portVersionBandwidth; - private static final Logger LOG = LoggerFactory.getLogger(PortFeaturesUtil.class); - - private PortFeaturesUtil() { - this.portVersionBandwidth = new HashMap<>(); - - portVersionBandwidth.put((short) 1, FeaturesV10Bandwidth.getInstance()); - portVersionBandwidth.put((short) 4, FeaturesV13Bandwidth.getInstance()); - } - - /** - * - * @return instance - */ - public static PortFeaturesUtil getInstance() { - return instance; - } - - /** - * - * @param msg {@link org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatus} - * @return port bandwidth - */ - public Boolean getPortBandwidth(PortStatus msg) { - - if(portVersionBandwidth.containsKey(msg.getVersion()) == true) { - try { - return portVersionBandwidth.get(msg.getVersion()).getBandwidth(msg); - } catch (NullPointerException e) { - LOG.warn("error while getting port features: {}", e.getMessage()); - LOG.debug("error while getting port features.. ", e); - } - } - else { - LOG.warn("unknown port version: {}", msg.getVersion()); - } - - return null; - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/RolePushException.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/RolePushException.java deleted file mode 100644 index f00b2d7434..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/RolePushException.java +++ /dev/null @@ -1,33 +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.openflow.md.core.session; - -/** - * covers role pushing issues - */ -public class RolePushException extends Exception { - - private static final long serialVersionUID = -615991366447313972L; - - /** - * default ctor - * - * @param message exception message - */ - public RolePushException(String message) { - super(message); - } - - /** - * @param message exception message - * @param cause exception cause - */ - public RolePushException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/RolePushTask.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/RolePushTask.java deleted file mode 100644 index ed5cd2fe6e..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/RolePushTask.java +++ /dev/null @@ -1,164 +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.openflow.md.core.session; - -import com.google.common.base.Preconditions; -import java.math.BigInteger; -import java.util.concurrent.Callable; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.MessageFactory; -import org.opendaylight.openflowplugin.openflow.md.util.RoleUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.util.Date; - -/** - * push role to device - basic step: - *
    - *
  • here we read generationId from device and
  • - *
  • push role request with incremented generationId
  • - *
  • {@link #call()} returns true if role request was successful
  • - *
- */ -//final class RolePushTask implements Callable { -public class RolePushTask implements Callable { - - private static final Logger LOG = LoggerFactory - .getLogger(RolePushTask.class); - - public static final long TIMEOUT = 7000; - public static final TimeUnit TIMEOUT_UNIT = TimeUnit.MILLISECONDS; - private OfpRole role; - private SessionContext session; - private int priority; - private int retryCounter; - - /** - * @param role openflow controller role - * @param session switch session context - */ - public RolePushTask(OfpRole role, SessionContext session) { - Preconditions.checkNotNull("OfpRole can not be empty.", role); - Preconditions.checkNotNull("Session context can not be empty.", session); - this.role = role; - this.session = session; - } - - /** - * @return the retryCounter - */ - public int getRetryCounter() { - return retryCounter; - } - - /** - * @return the priority - */ - public int getPriority() { - return priority; - } - - /** - * @param priority the priority to set - */ - public void setPriority(int priority) { - this.priority = priority; - } - - @Override - public Boolean call() throws RolePushException { - if (session.getPrimaryConductor().getVersion() == OFConstants.OFP_VERSION_1_0) { - LOG.info("OpenFlow 1.0 devices don't support multi controller features, skipping role push."); - return true; - } - if (!session.isValid()) { - String msg = "Giving up role change: current session is invalid"; - LOG.error(msg); - throw new RolePushException(msg); - } - - // adopt actual generationId from device (first shot failed and this is retry) - BigInteger generationId = null; - String dpId = new BigInteger(session.getSessionKey().getId()).toString(); - LOG.info("Pushing {} role configuration to device openflow:{}", - role==OfpRole.BECOMEMASTER?"MASTER":"SLAVE", dpId); - try { - Date date = new Date(); - Future generationIdFuture = RoleUtil.readGenerationIdFromDevice(session); - // flush election result with barrier - BarrierInput barrierInput = MessageFactory.createBarrier( - session.getFeatures().getVersion(), session.getNextXid()); - Future> barrierResult = session.getPrimaryConductor().getConnectionAdapter().barrier(barrierInput); - try { - barrierResult.get(TIMEOUT, TIMEOUT_UNIT); - } catch (Exception e) { - String msg = String.format("Giving up role change: barrier after read generation-id failed : %s", e.getMessage()); - LOG.warn(msg); - throw new RolePushException(msg); - } - try { - generationId = generationIdFuture.get(0, TIMEOUT_UNIT); - } catch (Exception e) { - String msg = String.format("Giving up role change: read generation-id failed %s", e.getMessage()); - throw new RolePushException(msg); - } - - LOG.info("Received generation-id {} for role change request from device {}", - generationId, dpId); - } catch (Exception e) { - LOG.error("Role push request failed for device {}",session.getSessionKey().getId(), e); - } - - if (generationId == null) { - LOG.error("Generation ID is NULL for device {}",session.getSessionKey().getId()); - String msg = "Giving up role change: current generation-id can not be read"; - throw new RolePushException(msg); - } - - generationId = RoleUtil.getNextGenerationId(generationId); - LOG.info("Pushing role change {} config request with generation-id {} to device {}", - role==OfpRole.BECOMEMASTER?"MASTER":"SLAVE", generationId, dpId); - - - // try to possess role on device - Future> roleReply = RoleUtil.sendRoleChangeRequest(session, role, generationId); - // flush election result with barrier - BarrierInput barrierInput = MessageFactory.createBarrier( - session.getFeatures().getVersion(), session.getNextXid()); - Future> barrierResult = session.getPrimaryConductor().getConnectionAdapter().barrier(barrierInput); - try { - barrierResult.get(TIMEOUT, TIMEOUT_UNIT); - } catch (Exception e) { - String msg = String.format("Giving up role change: barrier after role change failed: %s", e.getMessage()); - LOG.warn(msg); - throw new RolePushException(msg); - } - // after barrier replied there must be election result or error - try { - roleReply.get(0, TimeUnit.MILLISECONDS); - } catch (Exception e) { - // no election result received - let's retry - retryCounter += 1; - return false; - } - - // here we expect that role on device is successfully possessed - LOG.info("Successfully pushing {} role to the device openflow:{}", - role==OfpRole.BECOMEMASTER?"MASTER":"SLAVE", dpId); - return true; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/SessionContextOFImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/SessionContextOFImpl.java deleted file mode 100644 index 803f41bd7d..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/SessionContextOFImpl.java +++ /dev/null @@ -1,257 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.session; - -import com.google.common.base.Preconditions; -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.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; - -import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ControllerRole; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping; - -/** - * @author mirehak - */ -public class SessionContextOFImpl implements SessionContext { - - private GetFeaturesOutput features; - private ConnectionConductor primaryConductor; - private NotificationEnqueuer notificationEnqueuer; - private ConcurrentHashMap auxiliaryConductors; - private boolean valid; - private SwitchSessionKeyOF sessionKey; - private IMessageDispatchService mdService; - private final AtomicLong xid; - private final Map physicalPorts; - private final Map portBandwidth; - private ModelDrivenSwitchRegistration providerRegistration; - private int seed; - private ControllerRole roleOnDevice = ControllerRole.OFPCRROLEEQUAL; - - - /** - * default ctor - */ - public SessionContextOFImpl() { - auxiliaryConductors = new ConcurrentHashMap<>(); - mdService = new MessageDispatchServiceImpl(this); - xid = new AtomicLong(); - this.physicalPorts = new HashMap(); - this.portBandwidth = new HashMap(); - } - - @Override - public ConnectionConductor getPrimaryConductor() { - return primaryConductor; - } - - @Override - public ConnectionConductor getAuxiliaryConductor( - SwitchConnectionDistinguisher auxiliaryKey) { - return auxiliaryConductors.get(auxiliaryKey); - } - - @Override - public void addAuxiliaryConductor( - SwitchConnectionDistinguisher auxiliaryKey, - ConnectionConductor conductor) { - auxiliaryConductors.put(auxiliaryKey, conductor); - } - - @Override - public Set> getAuxiliaryConductors() { - return Collections.unmodifiableSet(auxiliaryConductors.entrySet()); - } - - @Override - public GetFeaturesOutput getFeatures() { - return features; - } - - /** - * @param features - * the features to set - */ - public void setFeatures(GetFeaturesOutput features) { - this.features = features; - } - - /** - * @param primaryConductor - * the primaryConductor to set - */ - public void setPrimaryConductor(ConnectionConductor primaryConductor) { - this.primaryConductor = primaryConductor; - } - - @Override - public ConnectionConductor removeAuxiliaryConductor( - SwitchConnectionDistinguisher connectionCookie) { - return auxiliaryConductors.remove(connectionCookie); - } - - @Override - public boolean isValid() { - return valid; - } - - @Override - public void setValid(boolean valid) { - this.valid = valid; - } - - /** - * @param sessionKey the sessionKey to set - */ - public void setSessionKey(SwitchSessionKeyOF sessionKey) { - this.sessionKey = sessionKey; - } - - /** - * @param seed the seed to set - */ - public void setSeed(int seed) { - this.seed = seed; - } - - @Override - public SwitchSessionKeyOF getSessionKey() { - return sessionKey; - } - - @Override - public IMessageDispatchService getMessageDispatchService() { - return mdService; - } - - @Override - public Long getNextXid() { - return xid.incrementAndGet(); - } - - @Override - public Map getPhysicalPorts() { - return this.physicalPorts; - } - - @Override - public Map getPortsBandwidth() { - return this.portBandwidth; - } - - @Override - public Set getPorts() { - return this.physicalPorts.keySet(); - } - - @Override - public PortGrouping getPhysicalPort(Long portNumber) { - return this.physicalPorts.get(portNumber); - } - - @Override - public Boolean getPortBandwidth(Long portNumber) { - return this.portBandwidth.get(portNumber); - } - - @Override - public boolean isPortEnabled(long portNumber) { - return isPortEnabled(physicalPorts.get(portNumber)); - } - - @Override - public boolean isPortEnabled(PortGrouping port) { - if (port == null) { - return false; - } - if (port.getConfig().isPortDown()) { - return false; - } - if (port.getState().isLinkDown()) { - return false; - } - if (port.getState().isBlocked()) { - return false; - } - return true; - } - - @Override - public List getEnabledPorts() { - List result = new ArrayList(); - synchronized (this.physicalPorts) { - for (PortGrouping port : physicalPorts.values()) { - if (isPortEnabled(port)) { - result.add(port); - } - } - } - return result; - } - - @Override - public void setProviderRegistration(ModelDrivenSwitchRegistration providerRegistration) { - this.providerRegistration = providerRegistration; - } - - @Override - public ModelDrivenSwitchRegistration getProviderRegistration() { - return providerRegistration; - } - - @Override - public int getSeed() { - return seed; - } - - /** - * @param notificationEnqueuer the notificationEnqueuer to set - */ - public void setNotificationEnqueuer( - NotificationEnqueuer notificationEnqueuer) { - this.notificationEnqueuer = notificationEnqueuer; - } - - @Override - public NotificationEnqueuer getNotificationEnqueuer() { - return notificationEnqueuer; - } - - /** - * @return the roleOnDevice - */ - @Override - public ControllerRole getRoleOnDevice() { - return roleOnDevice; - } - - /** - * @param roleOnDevice the roleOnDevice to set - */ - @Override - public void setRoleOnDevice(ControllerRole roleOnDevice) { - Preconditions.checkNotNull("Proposed controller role can not be empty.", roleOnDevice); - this.roleOnDevice = roleOnDevice; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/SessionManagerOFImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/SessionManagerOFImpl.java deleted file mode 100644 index 67cc3efce7..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/SessionManagerOFImpl.java +++ /dev/null @@ -1,354 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.session; - -import com.google.common.util.concurrent.ListeningExecutorService; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentHashMap; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionListener; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF; -import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.concepts.ListenerRegistration; -import org.opendaylight.yangtools.util.ListenerRegistry; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author mirehak - */ -public class SessionManagerOFImpl implements ConjunctSessionManager { - - protected static final Logger LOG = LoggerFactory.getLogger(SessionManagerOFImpl.class); - private static SessionManagerOFImpl instance; - private ConcurrentHashMap sessionLot; - private Map>>> translatorMapping; - private Map, Collection>> popListenerMapping; - - protected ListenerRegistry sessionListeners; - private NotificationProviderService notificationProviderService; - - private DataBroker dataBroker; - private ListeningExecutorService rpcPool; - - - /** - * @return singleton instance - */ - public static ConjunctSessionManager getInstance() { - if (instance == null) { - synchronized (SessionContextOFImpl.class) { - if (instance == null) { - instance = new SessionManagerOFImpl(); - } - } - } - return instance; - } - - /** - * close and release singleton instance - */ - public static void releaseInstance() { - if (instance != null) { - synchronized (SessionManagerOFImpl.class) { - if (instance != null) { - instance.close(); - instance = null; - } - } - } - } - - private SessionManagerOFImpl() { - LOG.debug("singleton creating"); - sessionLot = new ConcurrentHashMap<>(); - sessionListeners = new ListenerRegistry<>(); - } - - @Override - public SessionContext getSessionContext(SwitchSessionKeyOF sessionKey) { - return sessionLot.get(sessionKey); - } - - @Override - public void invalidateSessionContext(SwitchSessionKeyOF sessionKey) { - SessionContext context = getSessionContext(sessionKey); - if (context == null) { - LOG.info("context for invalidation not found"); - } else { - synchronized (context) { - if (context.isValid()) { - for (Entry auxEntry : context.getAuxiliaryConductors()) { - invalidateAuxiliary(sessionKey, auxEntry.getKey()); - } - context.getPrimaryConductor().disconnect(); - context.setValid(false); - removeSessionContext(context); - // TODO:: notify listeners - } else { - LOG.warn("Ignore invalid session context: {}", - Arrays.toString(sessionKey.getId())); - } - } - } - } - - private void invalidateDeadSessionContext(SessionContext sessionContext) { - if (sessionContext == null) { - LOG.info("context for invalidation not found"); - } else { - synchronized (sessionContext) { - if (sessionContext.isValid()) { - for (Entry auxEntry : sessionContext - .getAuxiliaryConductors()) { - invalidateAuxiliary(sessionContext, auxEntry.getKey(), true); - } - sessionContext.setValid(false); - removeSessionContext(sessionContext); - // TODO:: notify listeners - } else { - LOG.warn("Ignore invalid dead session context: {}", - Arrays.toString( - sessionContext.getSessionKey().getId())); - } - } - } - } - - private void removeSessionContext(SessionContext sessionContext) { - if (LOG.isDebugEnabled()) { - LOG.debug("removing session: {}", Arrays.toString(sessionContext.getSessionKey().getId())); - } - if (sessionLot.remove(sessionContext.getSessionKey(), sessionContext)) { - sessionNotifier.onSessionRemoved(sessionContext); - } else { - // This should never happen. - LOG.warn("Ignore session context that was already removed: {}", - Arrays.toString(sessionContext.getSessionKey().getId())); - } - } - - @Override - public void addSessionContext(SwitchSessionKeyOF sessionKey, SessionContext context) { - synchronized (context) { - sessionLot.put(sessionKey, context); - sessionNotifier.onSessionAdded(sessionKey, context); - context.setValid(true); - } - } - - @Override - public void setRole(SessionContext context) { - sessionNotifier.setRole(context); - } - @Override - public void invalidateAuxiliary(SwitchSessionKeyOF sessionKey, - SwitchConnectionDistinguisher connectionCookie) { - SessionContext context = getSessionContext(sessionKey); - invalidateAuxiliary(context, connectionCookie, true); - } - - /** - * @param context - * @param connectionCookie - * @param disconnect true if auxiliary connection is to be disconnected - */ - private static void invalidateAuxiliary(SessionContext context, SwitchConnectionDistinguisher connectionCookie, - boolean disconnect) { - if (context == null) { - LOG.info("context for invalidation not found"); - } else { - ConnectionConductor auxiliaryConductor = context.removeAuxiliaryConductor(connectionCookie); - if (auxiliaryConductor == null) { - LOG.warn("auxiliary conductor not found"); - } else { - if (disconnect) { - auxiliaryConductor.disconnect(); - } - } - } - } - - @Override - public void invalidateOnDisconnect(ConnectionConductor conductor) { - if (conductor.getAuxiliaryKey() == null) { - invalidateDeadSessionContext(conductor.getSessionContext()); - // TODO:: notify listeners - } else { - invalidateAuxiliary(conductor.getSessionContext(), conductor.getAuxiliaryKey(), false); - } - } - - @Override - public void setTranslatorMapping(Map>>> translatorMapping) { - this.translatorMapping = translatorMapping; - } - - @Override - public ListenerRegistration registerSessionListener(SessionListener listener) { - LOG.debug("registerSessionListener"); - return sessionListeners.register(listener); - } - - private final SessionListener sessionNotifier = new SessionListener() { - - @Override - public void onSessionAdded(SwitchSessionKeyOF sessionKey, SessionContext context) { - for (ListenerRegistration listener : sessionListeners) { - try { - listener.getInstance().onSessionAdded(sessionKey, context); - } catch (Exception e) { - LOG.error("Unhandled exeption occured while invoking onSessionAdded on listener", e); - } - } - } - - @Override - public void setRole(SessionContext context) { - for (ListenerRegistration listener : sessionListeners) { - try { - listener.getInstance().setRole(context); - } catch (Exception e) { - LOG.error("Unhandled exeption occured while invoking setRole on listener", e); - } - } - } - - @Override - public void onSessionRemoved(SessionContext context) { - for (ListenerRegistration listener : sessionListeners) { - try { - listener.getInstance().onSessionRemoved(context); - } catch (Exception e) { - LOG.error("Unhandled exeption occured while invoking onSessionRemoved on listener", e); - } - } - } - }; - private MessageSpy messageSpy; - private ExtensionConverterProvider extensionConverterProvider; - - - @Override - public Map>>> getTranslatorMapping() { - return this.translatorMapping; - } - - @Override - public void setNotificationProviderService( - NotificationProviderService notificationProviderService) { - this.notificationProviderService = notificationProviderService; - - } - - @Override - public DataBroker getDataBroker() { - return dataBroker; - } - - @Override - public void setDataBroker(DataBroker dataBroker) { - this.dataBroker = dataBroker; - - } - - @Override - public NotificationProviderService getNotificationProviderService() { - return notificationProviderService; - } - - @Override - public Map, Collection>> getPopListenerMapping() { - return popListenerMapping; - } - - @Override - public void setPopListenerMapping( - Map, Collection>> popListenerMapping) { - this.popListenerMapping = popListenerMapping; - } - - @Override - public void close() { - LOG.debug("close"); - synchronized (sessionLot) { - for (SessionContext sessionContext : sessionLot.values()) { - sessionContext.getPrimaryConductor().disconnect(); - } - // TODO: handle timeouted shutdown - rpcPool.shutdown(); - } - - for (ListenerRegistration listenerRegistration : sessionListeners) { - SessionListener listener = listenerRegistration.getInstance(); - if (listener instanceof AutoCloseable) { - try { - ((AutoCloseable) listener).close(); - } catch (Exception e) { - LOG.warn("closing of sessionListenerRegistration failed", e); - } - } - } - } - - @Override - public void setRpcPool(ListeningExecutorService rpcPool) { - this.rpcPool = rpcPool; - } - - @Override - public ListeningExecutorService getRpcPool() { - return rpcPool; - } - - @Override - public void setMessageSpy(MessageSpy messageSpy) { - this.messageSpy = messageSpy; - } - - @Override - public MessageSpy getMessageSpy() { - return messageSpy; - } - - @Override - public void setExtensionConverterProvider( - ExtensionConverterProvider extensionConverterProvider) { - this.extensionConverterProvider = extensionConverterProvider; - } - - /** - * @return the extensionConverterProvider - */ - @Override - public ExtensionConverterProvider getExtensionConverterProvider() { - return extensionConverterProvider; - } - - @Override - public Collection getAllSessions() { - return sessionLot.values(); - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/SwitchConnectionCookieOFImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/SwitchConnectionCookieOFImpl.java deleted file mode 100644 index 17aec61063..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/session/SwitchConnectionCookieOFImpl.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.session; - -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; - -import com.google.common.hash.HashFunction; -import com.google.common.hash.Hasher; -import com.google.common.hash.Hashing; - -/** - * @author mirehak - */ -public class SwitchConnectionCookieOFImpl implements SwitchConnectionDistinguisher { - - private short auxiliaryId; - private long cookie; - - /** - * @param cookie switch connection cookie - */ - public SwitchConnectionCookieOFImpl(long cookie) { - this.cookie = cookie; - } - - /** - * default ctor - */ - public SwitchConnectionCookieOFImpl() { - // NOOP - } - - /** - * @param auxiliaryId the auxiliaryId to set - */ - public void setAuxiliaryId(short auxiliaryId) { - this.auxiliaryId = auxiliaryId; - } - - /** - * compute pseudorandom key unique for given seed and {@link #auxiliaryId} - * @param seed random int but fixed per session - */ - public void init(int seed) { - if (auxiliaryId <= 0) { - throw new IllegalStateException("auxiliaryId must be greater than 0"); - } - - HashFunction mm32Hf = Hashing.murmur3_32(seed); - Hasher hasher = mm32Hf.newHasher(8); - hasher.putInt(auxiliaryId); - long hash = 0xFFFFFFFFL & hasher.hash().asInt(); - cookie = (auxiliaryId << 24) | (hash >> 8); - } - - @Override - public long getCookie() { - return cookie; - } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + (int) (cookie ^ (cookie >>> 32)); - return result; - } - - /* (non-Javadoc) - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - SwitchConnectionCookieOFImpl other = (SwitchConnectionCookieOFImpl) obj; - if (cookie != other.cookie) - return false; - return true; - } - - - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/AbstractErrorTranslator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/AbstractErrorTranslator.java deleted file mode 100644 index a03c093b7c..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/AbstractErrorTranslator.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright (c) 2013, 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.openflow.md.core.translator; - -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.util.ByteUtil; -import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * general support for errorMessage OF-API to MD-SAL translation - */ -public abstract class AbstractErrorTranslator implements IMDMessageTranslator> { - - private static final Logger LOG = LoggerFactory.getLogger(AbstractErrorTranslator.class); - - @Override - public List translate(SwitchConnectionDistinguisher cookie, SessionContext sc, OfHeader msg) { - if (msg instanceof ErrorMessage) { - ErrorMessage message = (ErrorMessage) msg; - List list = new CopyOnWriteArrayList(); - if (LOG.isDebugEnabled()) { - String hexData = "n/a"; - if (message.getData() != null) { - hexData = ByteUtil.bytesToHexstring(message.getData(), " "); - } - LOG.debug(" Error Message received: type={}[{}], code={}[{}], data=[{}] ", message.getType(), - message.getTypeString(), message.getCode(), message.getCodeString(), - hexData); - - } - - // TODO -- Augmentation is not handled - ErrorType type = decodeErrorType(message.getType()); - NodeRef node = new NodeRef( - InventoryDataServiceUtil.identifierFromDatapathId( - sc.getFeatures().getDatapathId())); - list.add(getGranularNodeErrors(message, type, node)); - return list; - } else { - LOG.error("Message is not of Error Message "); - return Collections.emptyList(); - } - } - - /** - * @param message error message - * @param errorType error type - * @param node node ref - * @return error message - */ - protected abstract org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorMessage getGranularNodeErrors(ErrorMessage message, ErrorType errorType, NodeRef node); - - /** - * @param type error type in source message - * @return enum for errorType - */ - public abstract ErrorType decodeErrorType(int type); - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorTranslator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorTranslator.java deleted file mode 100644 index 9199d76c62..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorTranslator.java +++ /dev/null @@ -1,205 +0,0 @@ -/** - * Copyright (c) 2013, 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.openflow.md.core.translator; - -import java.math.BigInteger; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadActionErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadInstructionErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadMatchErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.BadRequestErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.ExperimenterErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.FlowModErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.GroupModErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.HelloFailedErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.MeterModErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.PortModErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.QueueOpErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.RoleRequestErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.SwitchConfigErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.TableFeaturesErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.node.error.service.rev140410.TableModErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage; - -/** - * OF-1.3 errorMessage support - */ -public class ErrorTranslator extends AbstractErrorTranslator { - - @Override - public ErrorType decodeErrorType(int type) { - return ErrorType.forValue(type); - } - - @Override - public org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorMessage getGranularNodeErrors(ErrorMessage message, ErrorType errorType, NodeRef node){ - org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorMessage outErrorMessage = null; - TransactionId txnId = new TransactionId(BigInteger.valueOf(message.getXid())); - - //currently in yang , generation of builders does not support an interface - //so each notification is put in a separate if-else - if (errorType == ErrorType.HelloFailed) { - HelloFailedErrorNotificationBuilder builder = new HelloFailedErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.BadRequest) { - BadRequestErrorNotificationBuilder builder = new BadRequestErrorNotificationBuilder (); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.BadAction) { - BadActionErrorNotificationBuilder builder = new BadActionErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.BadInstruction) { - BadInstructionErrorNotificationBuilder builder = new BadInstructionErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.BadMatch) { - BadMatchErrorNotificationBuilder builder = new BadMatchErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.FlowModFailed) { - FlowModErrorNotificationBuilder builder = new FlowModErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.GroupModFailed) { - GroupModErrorNotificationBuilder builder = new GroupModErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.PortModFailed) { - PortModErrorNotificationBuilder builder = new PortModErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.QueueOpFailed) { - QueueOpErrorNotificationBuilder builder = new QueueOpErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.SwitchConfigFailed) { - SwitchConfigErrorNotificationBuilder builder = new SwitchConfigErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.RoleRequestFailed) { - RoleRequestErrorNotificationBuilder builder = new RoleRequestErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.MeterModFailed) { - MeterModErrorNotificationBuilder builder = new MeterModErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.TableModFailed) { - TableModErrorNotificationBuilder builder = new TableModErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.TableFeaturesFailed) { - TableFeaturesErrorNotificationBuilder builder = new TableFeaturesErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } else if (errorType == ErrorType.Experimenter) { - ExperimenterErrorNotificationBuilder builder = new ExperimenterErrorNotificationBuilder(); - builder.setTransactionId(txnId); - builder.setType(errorType); - builder.setCode(message.getCode()); - builder.setNode(node); - if (message.getData() != null) { - builder.setData(new String(message.getData())); - } - outErrorMessage = builder.build(); - } - - return outErrorMessage; - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorV10Translator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorV10Translator.java deleted file mode 100644 index 3d65a844dd..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorV10Translator.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright (c) 2013, 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.openflow.md.core.translator; - -import java.math.BigInteger; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.NodeErrorNotificationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage; - -/** - * OF-1.0 errorMessage support - */ -public class ErrorV10Translator extends AbstractErrorTranslator { - - @Override - public ErrorType decodeErrorType(int typeArg) { - ErrorType type = ErrorType.forValue(typeArg); - switch (type.ordinal()) { - case 3: - type = ErrorType.FlowModFailed; - break; - case 4: - type = ErrorType.PortModFailed; - break; - case 5: - type = ErrorType.QueueOpFailed; - break; - } - return type; - } - - /** - * @param message error message - * @param errorType error type - * @param node reference to node, that sent the error message - * @return translated error message of general type (OF-1.0) - */ - @Override - public org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorMessage getGranularNodeErrors(ErrorMessage message, ErrorType errorType, NodeRef node){ - NodeErrorNotificationBuilder nodeErrBuilder = new NodeErrorNotificationBuilder(); - nodeErrBuilder.setTransactionId(new TransactionId(BigInteger.valueOf(message.getXid()))); - nodeErrBuilder.setType(errorType); - nodeErrBuilder.setCode(message.getCode()); - nodeErrBuilder.setNode(node); - - if (message.getData() != null) { - nodeErrBuilder.setData(new String(message.getData())); - } - return nodeErrBuilder.build(); - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ExperimenterTranslator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ExperimenterTranslator.java deleted file mode 100644 index e39cb0f407..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ExperimenterTranslator.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2014 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.translator; - -import java.util.Collections; -import java.util.List; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ExperimenterTranslator implements IMDMessageTranslator> { - - private static final Logger LOG = LoggerFactory.getLogger(ExperimenterTranslator.class); - - @Override - public List translate(SwitchConnectionDistinguisher cookie, - SessionContext sc, OfHeader msg) { - if( msg instanceof ExperimenterMessage) { - // TODO - implement functionality to fully support Experimenter framework - return null; - }else { - LOG.error( "Message is not of Experimenter Error Message " ) ; - return Collections.emptyList(); - } - } - - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FeaturesV10ToNodeConnectorUpdatedTranslator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FeaturesV10ToNodeConnectorUpdatedTranslator.java deleted file mode 100644 index a7f1395e0e..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FeaturesV10ToNodeConnectorUpdatedTranslator.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.translator; - -import java.math.BigInteger; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.util.PortTranslatorUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPort; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class FeaturesV10ToNodeConnectorUpdatedTranslator implements IMDMessageTranslator> { - private static final Logger LOG = LoggerFactory - .getLogger(FeaturesV10ToNodeConnectorUpdatedTranslator.class); - - @Override - public List translate(SwitchConnectionDistinguisher cookie, - SessionContext sc, OfHeader msg) { - if (msg instanceof GetFeaturesOutput) { - GetFeaturesOutput features = (GetFeaturesOutput) msg; - List list = new CopyOnWriteArrayList(); - BigInteger datapathId = sc.getFeatures().getDatapathId(); - if( features.getPhyPort() != null ) { - for (PhyPort port : features.getPhyPort()) { - list.add(PortTranslatorUtil.translatePort(msg.getVersion(), datapathId, port.getPortNo(), port)); - } - } - return list; - } else { - // TODO - Do something smarter than returning null if translation fails... what Exception should we throw here? - return Collections.emptyList(); - } - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FlowRemovedTranslator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FlowRemovedTranslator.java deleted file mode 100644 index 6a5298b258..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FlowRemovedTranslator.java +++ /dev/null @@ -1,639 +0,0 @@ -/** - * Copyright (c) 2014 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.translator; - -import java.math.BigInteger; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Objects; -import java.util.concurrent.CopyOnWriteArrayList; -import org.opendaylight.openflowjava.util.ByteBufUtils; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion; -import org.opendaylight.openflowplugin.extension.api.AugmentTuple; -import org.opendaylight.openflowplugin.extension.api.path.MatchPath; -import org.opendaylight.openflowplugin.openflow.md.core.extension.MatchExtensionHelper; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.common.IpConversionUtil; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.VersionDatapathIdConvertorData; -import org.opendaylight.openflowplugin.openflow.md.util.ByteUtil; -import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv6FlowLabel; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.SwitchFlowRemovedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.RemovedFlowReason; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.mod.removed.Match; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.mod.removed.MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpSourceHardwareAddressBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.arp.match.fields.ArpTargetHardwareAddressBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetDestinationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetSourceBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ethernet.match.fields.EthernetTypeBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ipv6.match.fields.Ipv6ExtHeaderBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ipv6.match.fields.Ipv6LabelBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv4MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv6MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.IpMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.MetadataBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.ProtocolMatchFieldsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.TunnelBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.VlanMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.ArpMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv4MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._3.match.Ipv6MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.SctpMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.TcpMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.UdpMatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.protocol.match.fields.PbbBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.vlan.match.fields.VlanIdBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Ipv6ExthdrFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpOp; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpSha; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpSpa; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpTha; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpTpa; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.EthDst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.EthSrc; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.EthType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv4Code; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv4Type; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv6Code; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv6Type; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.InPhyPort; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.InPort; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.IpDscp; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.IpEcn; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.IpProto; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv4Dst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv4Src; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Dst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Exthdr; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Flabel; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6NdSll; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6NdTarget; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6NdTll; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Src; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MatchField; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Metadata; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MplsBos; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MplsLabel; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MplsTc; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.PbbIsid; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.SctpDst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.SctpSrc; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.TcpDst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.TcpSrc; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.TunnelId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.UdpDst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.UdpSrc; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.VlanPcp; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.VlanVid; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntry; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpOpCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpShaCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpSpaCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpThaCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpTpaCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.EthDstCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.EthSrcCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.EthTypeCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv4CodeCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv4TypeCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv6CodeCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv6TypeCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.InPhyPortCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.InPortCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.IpDscpCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.IpEcnCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.IpProtoCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv4DstCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv4SrcCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6DstCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6ExthdrCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6FlabelCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6NdSllCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6NdTargetCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6NdTllCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6SrcCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MetadataCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MplsBosCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MplsLabelCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MplsTcCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.PbbIsidCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.SctpDstCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.SctpSrcCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.TcpDstCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.TcpSrcCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.TunnelIdCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.UdpDstCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.UdpSrcCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.VlanPcpCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.VlanVidCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TunnelIpv4Dst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TunnelIpv4Src; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class FlowRemovedTranslator implements IMDMessageTranslator> { - - private static final Logger LOG = LoggerFactory.getLogger(FlowRemovedTranslator.class); - private static final String PREFIX_SEPARATOR = "/"; - private final ConvertorExecutor convertorExecutor; - - public FlowRemovedTranslator(ConvertorExecutor convertorExecutor) { - this.convertorExecutor = convertorExecutor; - } - - @Override - public List translate(final SwitchConnectionDistinguisher cookie, final SessionContext sc, final OfHeader msg) { - if (msg instanceof FlowRemovedMessage) { - FlowRemovedMessage ofFlow = (FlowRemovedMessage) msg; - List list = new CopyOnWriteArrayList(); - LOG.debug("Flow Removed Message received: Table Id={}, Flow removed reason={} ", ofFlow.getTableId(), - ofFlow.getReason()); - - SwitchFlowRemovedBuilder salFlowRemoved = new SwitchFlowRemovedBuilder(); - - if (ofFlow.getCookie() != null) { - salFlowRemoved.setCookie(new FlowCookie(ofFlow.getCookie())); - } - salFlowRemoved.setPriority(ofFlow.getPriority()); - - if (ofFlow.getTableId() != null) { - salFlowRemoved.setTableId(ofFlow.getTableId().getValue().shortValue()); - } - - salFlowRemoved.setDurationSec(ofFlow.getDurationSec()); - salFlowRemoved.setDurationNsec(ofFlow.getDurationNsec()); - salFlowRemoved.setIdleTimeout(ofFlow.getIdleTimeout()); - salFlowRemoved.setHardTimeout(ofFlow.getHardTimeout()); - salFlowRemoved.setPacketCount(ofFlow.getPacketCount()); - salFlowRemoved.setByteCount(ofFlow.getByteCount()); - - if(Objects.nonNull(ofFlow.getReason())) { - salFlowRemoved.setRemovedReason(translateReason(ofFlow)); - } - - OpenflowVersion ofVersion = OpenflowVersion.get(sc.getPrimaryConductor().getVersion()); - org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.Match ofMatch = ofFlow - .getMatch(); - if (ofMatch != null) { - salFlowRemoved.setMatch(fromMatch(ofMatch, sc.getFeatures().getDatapathId(), ofVersion)); - } else if (ofFlow.getMatchV10() != null) { - final VersionDatapathIdConvertorData data = new VersionDatapathIdConvertorData(sc.getPrimaryConductor().getVersion()); - data.setDatapathId(sc.getFeatures().getDatapathId()); - - final Optional matchBuilderOptional = convertorExecutor.convert(ofFlow.getMatchV10(), data); - salFlowRemoved.setMatch(matchBuilderOptional.orElse(new MatchBuilder()).build()); - } - salFlowRemoved.setNode(new NodeRef(InventoryDataServiceUtil.identifierFromDatapathId(sc.getFeatures() - .getDatapathId()))); - list.add(salFlowRemoved.build()); - return list; - } else { - LOG.error("Message is not a flow removed message "); - return Collections.emptyList(); - } - } - private RemovedFlowReason translateReason(FlowRemoved removedFlow) { - LOG.debug("--Entering translateReason within FlowRemovedTranslator with reason:{} " + removedFlow.getReason()); - switch (removedFlow.getReason()) { - case OFPRRIDLETIMEOUT: - return RemovedFlowReason.OFPRRIDLETIMEOUT; - case OFPRRHARDTIMEOUT: - return RemovedFlowReason.OFPRRHARDTIMEOUT; - case OFPRRDELETE: - return RemovedFlowReason.OFPRRDELETE; - case OFPRRGROUPDELETE: - return RemovedFlowReason.OFPRRGROUPDELETE; - default: - LOG.debug("The flow being default and hence deleting it "); - return RemovedFlowReason.OFPRRDELETE; - } - } - - public Match fromMatch(final org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.Match ofMatch, - final BigInteger datapathid, final OpenflowVersion ofVersion) { - MatchBuilder matchBuilder = new MatchBuilder(); - EthernetMatchBuilder ethernetMatch = null; - VlanMatchBuilder vlanMatch = null; - IpMatchBuilder ipMatch = null; - TcpMatchBuilder tcpMatch = null; - UdpMatchBuilder udpMatch = null; - SctpMatchBuilder sctpMatch = null; - Icmpv4MatchBuilder icmpv4Match = null; - Icmpv6MatchBuilder icmpv6Match = null; - Ipv4MatchBuilder ipv4Match = null; - ArpMatchBuilder arpMatch = null; - Ipv6MatchBuilder ipv6Match = null; - ProtocolMatchFieldsBuilder protocolMatchFields = null; - - for (MatchEntry entry : ofMatch.getMatchEntry()) { - Class field = entry.getOxmMatchField(); - if (field.equals(InPort.class)) { - matchBuilder.setInPort(InventoryDataServiceUtil.nodeConnectorIdfromDatapathPortNo(datapathid, - ((InPortCase) entry.getMatchEntryValue()).getInPort().getPortNumber().getValue(), ofVersion)); - } else if (field.equals(InPhyPort.class)) { - matchBuilder.setInPhyPort(InventoryDataServiceUtil.nodeConnectorIdfromDatapathPortNo(datapathid, - ((InPhyPortCase) entry.getMatchEntryValue()).getInPhyPort().getPortNumber().getValue(), ofVersion)); - } else if (field.equals(Metadata.class)) { - MetadataBuilder metadata = new MetadataBuilder(); - MetadataCase metadataCase = ((MetadataCase) entry.getMatchEntryValue()); - metadata.setMetadata(new BigInteger(OFConstants.SIGNUM_UNSIGNED, metadataCase.getMetadata().getMetadata())); - if (entry.isHasMask()) { - metadata.setMetadataMask(new BigInteger(OFConstants.SIGNUM_UNSIGNED, metadataCase.getMetadata().getMask())); - } - matchBuilder.setMetadata(metadata.build()); - } else if (field.equals(EthDst.class) || field.equals(EthSrc.class) || field.equals(EthType.class)) { - if (ethernetMatch == null) { - ethernetMatch = new EthernetMatchBuilder(); - } - if (field.equals(EthDst.class)) { - EthernetDestinationBuilder ethDst = new EthernetDestinationBuilder(); - EthDstCase ethDstCase = (EthDstCase) entry.getMatchEntryValue(); - ethDst.setAddress(ethDstCase.getEthDst().getMacAddress()); - if (entry.isHasMask()) { - ethDst.setMask(new MacAddress(ByteUtil.bytesToHexstring(ethDstCase.getEthDst().getMask(), ":"))); - } - ethernetMatch.setEthernetDestination(ethDst.build()); - } else if (field.equals(EthSrc.class)) { - EthernetSourceBuilder ethSrc = new EthernetSourceBuilder(); - EthSrcCase ethSrcCase = ((EthSrcCase) entry.getMatchEntryValue()); - ethSrc.setAddress(ethSrcCase.getEthSrc().getMacAddress()); - if (entry.isHasMask()) { - ethSrc.setMask(new MacAddress(ByteUtil.bytesToHexstring(ethSrcCase.getEthSrc().getMask(), ":"))); - } - ethernetMatch.setEthernetSource(ethSrc.build()); - } else if (field.equals(EthType.class)) { - EthernetTypeBuilder ethType = new EthernetTypeBuilder(); - EthTypeCase ethTypeCase = ((EthTypeCase) entry.getMatchEntryValue()); - ethType.setType(new EtherType(ethTypeCase.getEthType().getEthType().getValue().longValue())); - ethernetMatch.setEthernetType(ethType.build()); - } - } else if (field.equals(VlanVid.class) || field.equals(VlanPcp.class)) { - if (vlanMatch == null) { - vlanMatch = new VlanMatchBuilder(); - } - if (field.equals(VlanVid.class)) { - boolean vlanIdPresent = false; - VlanIdBuilder vlanId = new VlanIdBuilder(); - VlanVidCase vlanVidCase = ((VlanVidCase) entry.getMatchEntryValue()); - Integer vlanVidValue = vlanVidCase.getVlanVid().getVlanVid(); - if (vlanVidCase.getVlanVid().isCfiBit()) { - vlanIdPresent = true; - } - vlanId.setVlanIdPresent(vlanIdPresent); - if (vlanVidValue != null) { - vlanId.setVlanId(new VlanId(vlanVidValue)); - } - vlanMatch.setVlanId(vlanId.build()); - } else if (field.equals(VlanPcp.class)) { - VlanPcpCase vlanPcpCase = ((VlanPcpCase) entry.getMatchEntryValue()); - vlanMatch.setVlanPcp(new org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanPcp(vlanPcpCase.getVlanPcp().getVlanPcp())); - } - } else if (field.equals(IpDscp.class) || field.equals(IpEcn.class) || field.equals(IpProto.class)) { - if (ipMatch == null) { - ipMatch = new IpMatchBuilder(); - } - if (field.equals(IpDscp.class)) { - IpDscpCase ipDscpCase = ((IpDscpCase) entry.getMatchEntryValue()); - ipMatch.setIpDscp(new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Dscp( - ipDscpCase.getIpDscp().getDscp())); - } else if (field.equals(IpEcn.class)) { - IpEcnCase ipEcnCase = ((IpEcnCase) entry.getMatchEntryValue()); - ipMatch.setIpEcn(ipEcnCase.getIpEcn().getEcn()); - } else if (field.equals(IpProto.class)) { - IpProtoCase ipProtoCase = ((IpProtoCase) entry.getMatchEntryValue()); - ipMatch.setIpProtocol(ipProtoCase.getIpProto().getProtocolNumber()); - } - } else if (field.equals(TcpSrc.class) || field.equals(TcpDst.class)) { - if (tcpMatch == null) { - tcpMatch = new TcpMatchBuilder(); - } - if (field.equals(TcpSrc.class)) { - TcpSrcCase tcpSrcCase = ((TcpSrcCase) entry.getMatchEntryValue()); - tcpMatch.setTcpSourcePort(new PortNumber(tcpSrcCase.getTcpSrc().getPort().getValue())); - } else if (field.equals(TcpDst.class)) { - TcpDstCase tcpDstCase = ((TcpDstCase) entry.getMatchEntryValue()); - tcpMatch.setTcpDestinationPort(new PortNumber(tcpDstCase.getTcpDst().getPort().getValue())); - } - } else if (field.equals(UdpSrc.class) || field.equals(UdpDst.class)) { - if (udpMatch == null) { - udpMatch = new UdpMatchBuilder(); - } - if (field.equals(UdpSrc.class)) { - UdpSrcCase udpSrcCase = ((UdpSrcCase) entry.getMatchEntryValue()); - udpMatch.setUdpSourcePort(new PortNumber(udpSrcCase.getUdpSrc().getPort().getValue())); - } else if (field.equals(UdpDst.class)) { - UdpDstCase udpDstCase = ((UdpDstCase) entry.getMatchEntryValue()); - udpMatch.setUdpDestinationPort(new PortNumber(udpDstCase.getUdpDst().getPort())); - } - } else if (field.equals(SctpSrc.class) || field.equals(SctpDst.class)) { - if (sctpMatch == null) { - sctpMatch = new SctpMatchBuilder(); - } - if (field.equals(SctpSrc.class)) { - SctpSrcCase sctpSrcCase = ((SctpSrcCase) entry.getMatchEntryValue()); - sctpMatch.setSctpSourcePort(new PortNumber(sctpSrcCase.getSctpSrc().getPort())); - } else if (field.equals(SctpDst.class)) { - SctpDstCase sctpDstCase = ((SctpDstCase) entry.getMatchEntryValue()); - sctpMatch.setSctpDestinationPort(new PortNumber(sctpDstCase.getSctpDst().getPort())); - } - } else if (field.equals(Icmpv4Type.class) || field.equals(Icmpv4Code.class)) { - if (icmpv4Match == null) { - icmpv4Match = new Icmpv4MatchBuilder(); - } - if (field.equals(Icmpv4Type.class)) { - Icmpv4TypeCase icmpv4TypeCase = ((Icmpv4TypeCase) entry.getMatchEntryValue()); - icmpv4Match.setIcmpv4Type(icmpv4TypeCase.getIcmpv4Type().getIcmpv4Type()); - } else if (field.equals(Icmpv4Code.class)) { - Icmpv4CodeCase icmpv4CodeCase = ((Icmpv4CodeCase) entry.getMatchEntryValue()); - icmpv4Match.setIcmpv4Code(icmpv4CodeCase.getIcmpv4Code().getIcmpv4Code()); - } - } else if (field.equals(Icmpv6Type.class) || field.equals(Icmpv6Code.class)) { - if (icmpv6Match == null) { - icmpv6Match = new Icmpv6MatchBuilder(); - } - if (field.equals(Icmpv6Type.class)) { - Icmpv6TypeCase icmpv6TypeCase = ((Icmpv6TypeCase) entry.getMatchEntryValue()); - icmpv6Match.setIcmpv6Type(icmpv6TypeCase.getIcmpv6Type().getIcmpv6Type()); - } else if (field.equals(Icmpv6Code.class)) { - Icmpv6CodeCase icmpv6CodeCase = ((Icmpv6CodeCase) entry.getMatchEntryValue()); - icmpv6Match.setIcmpv6Code(icmpv6CodeCase.getIcmpv6Code().getIcmpv6Code()); - } - } else if (field.equals(Ipv4Src.class) || field.equals(Ipv4Dst.class)) { - if (ipv4Match == null) { - ipv4Match = new Ipv4MatchBuilder(); - } - if (field.equals(Ipv4Src.class)) { - Ipv4SrcCase ipv4SrcCase = ((Ipv4SrcCase) entry.getMatchEntryValue()); - int prefix; - if (entry.isHasMask()) { - prefix = IpConversionUtil.countBits(ipv4SrcCase.getIpv4Src().getMask()); - } else { - prefix = 32; - } - ipv4Match.setIpv4Source( - IpConversionUtil.createPrefix(ipv4SrcCase.getIpv4Src().getIpv4Address(), prefix) - ); - - } else if (field.equals(Ipv4Dst.class)) { - Ipv4DstCase ipv4DstCase = ((Ipv4DstCase) entry.getMatchEntryValue()); - int prefix; - if (entry.isHasMask()) { - prefix = IpConversionUtil.countBits(ipv4DstCase.getIpv4Dst().getMask()); - } else { - prefix = 32; - } - ipv4Match.setIpv4Destination( - IpConversionUtil.createPrefix(ipv4DstCase.getIpv4Dst().getIpv4Address(), prefix) - ); - } - } else if (field.equals(ArpOp.class) || field.equals(ArpSpa.class) || field.equals(ArpTpa.class) - || field.equals(ArpSha.class) || field.equals(ArpTha.class)) { - if (arpMatch == null) { - arpMatch = new ArpMatchBuilder(); - } - if (field.equals(ArpOp.class)) { - ArpOpCase arpOpCase = ((ArpOpCase) entry.getMatchEntryValue()); - arpMatch.setArpOp(arpOpCase.getArpOp().getOpCode()); - } else if (field.equals(ArpSpa.class)) { - - ArpSpaCase arpSpaCase = ((ArpSpaCase) entry.getMatchEntryValue()); - int prefix; - if (entry.isHasMask()) { - prefix = IpConversionUtil.countBits(arpSpaCase.getArpSpa().getMask()); - } else { - prefix = 32; - } - arpMatch.setArpSourceTransportAddress( - IpConversionUtil.createPrefix(arpSpaCase.getArpSpa().getIpv4Address(), prefix) - ); - } else if (field.equals(ArpTpa.class)) { - ArpTpaCase arpTpaCase = ((ArpTpaCase) entry.getMatchEntryValue()); - int prefix; - if (entry.isHasMask()) { - prefix = IpConversionUtil.countBits(arpTpaCase.getArpTpa().getMask()); - } else { - prefix = 32; - } - - arpMatch.setArpTargetTransportAddress( - IpConversionUtil.createPrefix(arpTpaCase.getArpTpa().getIpv4Address(), prefix) - ); - } else if (field.equals(ArpSha.class)) { - ArpSourceHardwareAddressBuilder arpSha = new ArpSourceHardwareAddressBuilder(); - ArpShaCase arpShaCase = ((ArpShaCase) entry.getMatchEntryValue()); - arpSha.setAddress(arpShaCase.getArpSha().getMacAddress()); - if (entry.isHasMask()) { - arpSha.setMask(new MacAddress(ByteUtil.bytesToHexstring(arpShaCase.getArpSha().getMask(), ":"))); - } - arpMatch.setArpSourceHardwareAddress(arpSha.build()); - } else if (field.equals(ArpTha.class)) { - ArpThaCase arpThaCase = ((ArpThaCase) entry.getMatchEntryValue()); - ArpTargetHardwareAddressBuilder arpTha = new ArpTargetHardwareAddressBuilder(); - arpTha.setAddress(arpThaCase.getArpTha().getMacAddress()); - if (entry.isHasMask()) { - arpTha.setMask(new MacAddress(ByteUtil.bytesToHexstring(arpThaCase.getArpTha().getMask(), ":"))); - } - arpMatch.setArpTargetHardwareAddress(arpTha.build()); - } - } else if (field.equals(TunnelIpv4Src.class) || field.equals(TunnelIpv4Dst.class)) { - if (ipv4Match == null) { - ipv4Match = new Ipv4MatchBuilder(); - } - if (field.equals(TunnelIpv4Src.class)) { - Ipv4SrcCase ipv4SrcCase = ((Ipv4SrcCase) entry.getMatchEntryValue()); - int prefix; - if (entry.isHasMask()) { - prefix = IpConversionUtil.countBits(ipv4SrcCase.getIpv4Src().getMask()); - } else { - prefix = 32; - } - - ipv4Match.setIpv4Source( - IpConversionUtil.createPrefix(ipv4SrcCase.getIpv4Src().getIpv4Address(), prefix) - ); - } else if (field.equals(TunnelIpv4Dst.class)) { - Ipv4DstCase ipv4DstCase = ((Ipv4DstCase) entry.getMatchEntryValue()); - int prefix; - if (entry.isHasMask()) { - prefix = IpConversionUtil.countBits(ipv4DstCase.getIpv4Dst().getMask()); - } else { - prefix = 32; - } - - ipv4Match.setIpv4Destination( - IpConversionUtil.createPrefix(ipv4DstCase.getIpv4Dst().getIpv4Address(), prefix) - ); } - } else if (field.equals(Ipv6Src.class) || field.equals(Ipv6Dst.class) || field.equals(Ipv6Flabel.class) - || field.equals(Ipv6NdTarget.class) || field.equals(Ipv6NdSll.class) - || field.equals(Ipv6NdTll.class) || field.equals(Ipv6Exthdr.class)) { - if (ipv6Match == null) { - ipv6Match = new Ipv6MatchBuilder(); - } - if (field.equals(Ipv6Src.class)) { - Ipv6SrcCase ipv6SrcCase = ((Ipv6SrcCase) entry.getMatchEntryValue()); - int prefix ; - if (entry.isHasMask()) { - prefix = IpConversionUtil.countBits(ipv6SrcCase.getIpv6Src().getMask()); - } else { - prefix = 128; - } - ipv6Match.setIpv6Source( - IpConversionUtil.createPrefix(ipv6SrcCase.getIpv6Src().getIpv6Address(), prefix) - ); - } else if (field.equals(Ipv6Dst.class)) { - Ipv6DstCase ipv6DstCase = ((Ipv6DstCase) entry.getMatchEntryValue()); - int prefix; - if (entry.isHasMask()) { - prefix = IpConversionUtil.countBits(ipv6DstCase.getIpv6Dst().getMask()); - } else { - prefix = 128; - } - ipv6Match.setIpv6Destination( - IpConversionUtil.createPrefix(ipv6DstCase.getIpv6Dst().getIpv6Address(), prefix) - ); - } else if (field.equals(Ipv6Flabel.class)) { - Ipv6LabelBuilder ipv6Label = new Ipv6LabelBuilder(); - Ipv6FlabelCase ipv6FlabelCase = ((Ipv6FlabelCase) entry.getMatchEntryValue()); - ipv6Label.setIpv6Flabel(ipv6FlabelCase.getIpv6Flabel().getIpv6Flabel()); - if (entry.isHasMask()) { - ipv6Label.setFlabelMask(new Ipv6FlowLabel(ByteUtil.bytesToUnsignedInt(ipv6FlabelCase.getIpv6Flabel().getMask()))); - } - ipv6Match.setIpv6Label(ipv6Label.build()); - } else if (field.equals(Ipv6NdTarget.class)) { - Ipv6NdTargetCase ipv6NdTargetCase = ((Ipv6NdTargetCase) entry.getMatchEntryValue()); - ipv6Match.setIpv6NdTarget(ipv6NdTargetCase.getIpv6NdTarget().getIpv6Address()); - } else if (field.equals(Ipv6NdSll.class)) { - Ipv6NdSllCase ipv6NdSllCase = ((Ipv6NdSllCase) entry.getMatchEntryValue()); - ipv6Match.setIpv6NdSll(ipv6NdSllCase.getIpv6NdSll().getMacAddress()); - } else if (field.equals(Ipv6NdTll.class)) { - Ipv6NdTllCase ipv6NdTllCase = ((Ipv6NdTllCase) entry.getMatchEntryValue()); - ipv6Match.setIpv6NdTll(ipv6NdTllCase.getIpv6NdTll().getMacAddress()); - } else if (field.equals(Ipv6Exthdr.class)) { - Ipv6ExthdrCase ipv6ExthdrCase = ((Ipv6ExthdrCase) entry.getMatchEntryValue()); - // verify - Ipv6ExtHeaderBuilder ipv6ExtHeaderBuilder = new Ipv6ExtHeaderBuilder(); - Ipv6ExthdrFlags pseudoField = ipv6ExthdrCase.getIpv6Exthdr().getPseudoField(); - Map map = new HashMap<>(); - map.put(0, pseudoField.isNonext()); - map.put(1, pseudoField.isEsp()); - map.put(2, pseudoField.isAuth()); - map.put(3, pseudoField.isDest()); - map.put(4, pseudoField.isFrag()); - map.put(5, pseudoField.isRouter()); - map.put(6, pseudoField.isHop()); - map.put(7, pseudoField.isUnrep()); - map.put(8, pseudoField.isUnseq()); - int bitmap = ByteBufUtils.fillBitMaskFromMap(map); - ipv6ExtHeaderBuilder.setIpv6Exthdr(bitmap); - if (entry.isHasMask()) { - ipv6ExtHeaderBuilder.setIpv6ExthdrMask( - ByteUtil.bytesToUnsignedShort(ipv6ExthdrCase.getIpv6Exthdr().getMask())); - } - ipv6Match.setIpv6ExtHeader(ipv6ExtHeaderBuilder.build()); - } - } else if (field.equals(MplsLabel.class) || field.equals(MplsTc.class) || field.equals(MplsBos.class) - || field.equals(PbbIsid.class)) { - if (protocolMatchFields == null) { - protocolMatchFields = new ProtocolMatchFieldsBuilder(); - } - if (field.equals(MplsLabel.class)) { - MplsLabelCase mplsLabelCase = ((MplsLabelCase) entry.getMatchEntryValue()); - protocolMatchFields.setMplsLabel(mplsLabelCase.getMplsLabel().getMplsLabel()); - } else if (field.equals(MplsTc.class)) { - MplsTcCase mplsTcCase = ((MplsTcCase) entry.getMatchEntryValue()); - protocolMatchFields.setMplsTc(mplsTcCase.getMplsTc().getTc()); - } else if (field.equals(MplsBos.class)) { - MplsBosCase mplsBosCase = ((MplsBosCase) entry.getMatchEntryValue()); - protocolMatchFields - .setMplsBos((short) (mplsBosCase.getMplsBos().isBos() ? 1 : 0)); - } else if (field.equals(PbbIsid.class)) { - PbbIsidCase pbbIsidCase = ((PbbIsidCase) entry.getMatchEntryValue()); - PbbBuilder pbb = new PbbBuilder(); - pbb.setPbbIsid(pbbIsidCase.getPbbIsid().getIsid()); - if (entry.isHasMask()) { - pbb.setPbbMask(ByteUtil.bytesToUnsignedInt(pbbIsidCase.getPbbIsid().getMask())); - } - protocolMatchFields.setPbb(pbb.build()); - } - } else if (field.equals(TunnelId.class)) { - TunnelIdCase tunnelIdCase = ((TunnelIdCase) entry.getMatchEntryValue()); - TunnelBuilder tunnel = new TunnelBuilder(); - tunnel.setTunnelId(new BigInteger(OFConstants.SIGNUM_UNSIGNED, tunnelIdCase.getTunnelId().getTunnelId())); - if (entry.isHasMask()) { - tunnel.setTunnelMask(new BigInteger(OFConstants.SIGNUM_UNSIGNED, tunnelIdCase.getTunnelId().getMask())); - } - matchBuilder.setTunnel(tunnel.build()); - } - } - - AugmentTuple matchExtensionWrap = - MatchExtensionHelper.processAllExtensions( - ofMatch.getMatchEntry(), ofVersion, MatchPath.SWITCHFLOWREMOVED_MATCH); - if (matchExtensionWrap != null) { - matchBuilder.addAugmentation(matchExtensionWrap.getAugmentationClass(), matchExtensionWrap.getAugmentationObject()); - } - - - if (ethernetMatch != null) { - matchBuilder.setEthernetMatch(ethernetMatch.build()); - } - if (vlanMatch != null) { - matchBuilder.setVlanMatch(vlanMatch.build()); - } - if (ipMatch != null) { - matchBuilder.setIpMatch(ipMatch.build()); - } - - if (tcpMatch != null) { - matchBuilder.setLayer4Match(tcpMatch.build()); - } else if (udpMatch != null) { - matchBuilder.setLayer4Match(udpMatch.build()); - } else if (sctpMatch != null) { - matchBuilder.setLayer4Match(sctpMatch.build()); - } - - if (icmpv4Match != null) { - matchBuilder.setIcmpv4Match(icmpv4Match.build()); - } else if (icmpv6Match != null) { - matchBuilder.setIcmpv6Match(icmpv6Match.build()); - } - - if (ipv4Match != null) { - matchBuilder.setLayer3Match(ipv4Match.build()); - } else if (arpMatch != null) { - matchBuilder.setLayer3Match(arpMatch.build()); - } else if (ipv6Match != null) { - matchBuilder.setLayer3Match(ipv6Match.build()); - } - if (protocolMatchFields != null) { - matchBuilder.setProtocolMatchFields(protocolMatchFields.build()); - } - return matchBuilder.build(); - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartMessageDescToNodeUpdatedTranslator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartMessageDescToNodeUpdatedTranslator.java deleted file mode 100644 index 7c0cce64e4..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartMessageDescToNodeUpdatedTranslator.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.translator; - -import java.math.BigInteger; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil; -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.inventory.rev130819.NodeUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdatedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyDescCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.desc._case.MultipartReplyDesc; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MultiPartMessageDescToNodeUpdatedTranslator implements IMDMessageTranslator> { - private static final Logger LOG = LoggerFactory.getLogger(MultiPartMessageDescToNodeUpdatedTranslator.class); - @Override - public List translate(SwitchConnectionDistinguisher cookie, - SessionContext sc, OfHeader msg) { - if(msg instanceof MultipartReply && ((MultipartReply) msg).getType() == MultipartType.OFPMPDESC) { - LOG.debug("MultipartReplyMessage - MultipartReplyDesc Being translated to NodeUpdated "); - MultipartReplyMessage message = (MultipartReplyMessage) msg; - List list = new CopyOnWriteArrayList(); - BigInteger datapathId = sc.getFeatures().getDatapathId(); - NodeUpdatedBuilder builder = InventoryDataServiceUtil.nodeUpdatedBuilderFromDataPathId(datapathId); - FlowCapableNodeUpdatedBuilder fnub = new FlowCapableNodeUpdatedBuilder(); - MultipartReplyDescCase caseBody = (MultipartReplyDescCase) message.getMultipartReplyBody(); - MultipartReplyDesc body = caseBody.getMultipartReplyDesc(); - fnub.setHardware(body.getHwDesc()); - fnub.setManufacturer(body.getMfrDesc()); - fnub.setSerialNumber(body.getSerialNum()); - fnub.setDescription(body.getDpDesc()); - fnub.setSoftware(body.getSwDesc()); - builder.addAugmentation(FlowCapableNodeUpdated.class, fnub.build()); - NodeUpdated nodeUpdated = builder.build(); - list.add(nodeUpdated); - return list; - } else { - return Collections.emptyList(); - } - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartReplyPortToNodeConnectorUpdatedTranslator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartReplyPortToNodeConnectorUpdatedTranslator.java deleted file mode 100644 index 6f08409ec1..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartReplyPortToNodeConnectorUpdatedTranslator.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.translator; - -import java.math.BigInteger; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.util.PortTranslatorUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyPortDescCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.MultipartReplyPortDesc; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.multipart.reply.port.desc.Ports; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MultiPartReplyPortToNodeConnectorUpdatedTranslator implements IMDMessageTranslator> { - private static final Logger LOG = LoggerFactory.getLogger(MultiPartReplyPortToNodeConnectorUpdatedTranslator.class); - @Override - public List translate(SwitchConnectionDistinguisher cookie, - SessionContext sc, OfHeader msg) { - if(msg instanceof MultipartReply && ((MultipartReply) msg).getType() == MultipartType.OFPMPPORTDESC) { - BigInteger datapathId = sc.getFeatures().getDatapathId(); - LOG.trace("MultiPartReplyPortToNodeConnectorUpdatedTranslator Being translated to NodeConnectorUpdated "); - MultipartReplyMessage message = (MultipartReplyMessage) msg; - MultipartReplyPortDescCase caseBody = (MultipartReplyPortDescCase) message.getMultipartReplyBody(); - MultipartReplyPortDesc body = caseBody.getMultipartReplyPortDesc(); - List list = new CopyOnWriteArrayList(); - for ( Ports port : body.getPorts() ) { - LOG.debug("Port: " + port); - list.add(PortTranslatorUtil.translatePort(msg.getVersion(), datapathId, port.getPortNo(), port)); - } - return list; - } else { - return Collections.emptyList(); - } - } - - - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTableFeaturesToTableUpdatedTranslator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTableFeaturesToTableUpdatedTranslator.java deleted file mode 100644 index e2f755ca37..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTableFeaturesToTableUpdatedTranslator.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright (c) 2014 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.translator; - -import java.math.BigInteger; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CopyOnWriteArrayList; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.VersionConvertorData; -import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableFeaturesCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.MultipartReplyTableFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.TableUpdatedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MultipartReplyTableFeaturesToTableUpdatedTranslator implements - IMDMessageTranslator> { - - private static final Logger LOG = LoggerFactory - .getLogger(MultipartReplyTableFeaturesToTableUpdatedTranslator.class); - private final ConvertorExecutor convertorExecutor; - - public MultipartReplyTableFeaturesToTableUpdatedTranslator(ConvertorExecutor convertorExecutor) { - this.convertorExecutor = convertorExecutor; - } - - @Override - public List translate(SwitchConnectionDistinguisher cookie, SessionContext sc, OfHeader msg) { - if (msg instanceof MultipartReply && ((MultipartReply) msg).getType() == MultipartType.OFPMPTABLEFEATURES) { - LOG.debug("MultipartReply Being translated to TableUpdated "); - MultipartReplyMessage mpReply = (MultipartReplyMessage) msg; - - List listDataObject = new CopyOnWriteArrayList<>(); - - TableUpdatedBuilder message = new TableUpdatedBuilder(); - message.setNode((new NodeRef(InventoryDataServiceUtil.identifierFromDatapathId(sc.getFeatures() - .getDatapathId())))); - message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE()); - message.setTransactionId(new TransactionId(BigInteger.valueOf(mpReply.getXid()))); - MultipartReplyTableFeaturesCase caseBody = (MultipartReplyTableFeaturesCase) mpReply.getMultipartReplyBody(); - MultipartReplyTableFeatures body = caseBody.getMultipartReplyTableFeatures(); - - final VersionConvertorData data = new VersionConvertorData(sc.getPrimaryConductor().getVersion()); - final Optional> tableFeaturesList = convertorExecutor.convert(body, data); - message.setTableFeatures(tableFeaturesList.orElse(Collections.emptyList())); - listDataObject.add( message.build()) ; - - return listDataObject ; - - } - return Collections.emptyList(); - - } - -} \ No newline at end of file diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslator.java deleted file mode 100644 index 0c985dbe56..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslator.java +++ /dev/null @@ -1,515 +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.openflow.md.core.translator; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.CopyOnWriteArrayList; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion; -import org.opendaylight.openflowplugin.extension.api.path.MatchPath; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.FlowStatsResponseConvertorData; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.VersionDatapathIdConvertorData; -import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil; -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.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.flow.and.statistics.map.list.FlowAndStatisticsMapList; -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.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.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.queue.rev130925.QueueId; -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.types.rev131018.Chaining; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.ChainingChecks; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupAll; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupCapability; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupFf; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupIndirect; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupSelect; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.SelectLiveness; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.SelectWeight; -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.inventory.rev130819.NodeId; -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.types.rev130918.MeterBand; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterBandDrop; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterBandDscpRemark; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterBurst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterCapability; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterKbps; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterPktps; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.config.stats.reply.MeterConfigStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.statistics.types.rev130925.duration.DurationBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.statistics.types.rev130925.node.connector.statistics.BytesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.statistics.types.rev130925.node.connector.statistics.PacketsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyAggregateCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyFlowCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupDescCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupFeaturesCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterConfigCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterFeaturesCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyPortStatsCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyQueueCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.aggregate._case.MultipartReplyAggregate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.flow._case.MultipartReplyFlow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group._case.MultipartReplyGroup; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.desc._case.MultipartReplyGroupDesc; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.features._case.MultipartReplyGroupFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter._case.MultipartReplyMeter; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.config._case.MultipartReplyMeterConfig; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.features._case.MultipartReplyMeterFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.stats._case.MultipartReplyPortStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.stats._case.multipart.reply.port.stats.PortStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.queue._case.MultipartReplyQueue; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.queue._case.multipart.reply.queue.QueueStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table._case.MultipartReplyTable; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table._case.multipart.reply.table.TableStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.NodeConnectorStatisticsUpdateBuilder; -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.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.table.types.rev131026.TableId; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class converts multipart reply messages to the notification objects defined - * by statistics provider (manager ). - * - * @author avishnoi@in.ibm.com - * - */ -public class MultipartReplyTranslator implements IMDMessageTranslator> { - - protected static final Logger LOG = LoggerFactory - .getLogger(MultipartReplyTranslator.class); - private final ConvertorExecutor convertorExecutor; - - public MultipartReplyTranslator(ConvertorExecutor convertorExecutor) { - this.convertorExecutor = convertorExecutor; - } - - - @Override - public List translate(final SwitchConnectionDistinguisher cookie, final SessionContext sc, final OfHeader msg) { - - List listDataObject = new CopyOnWriteArrayList(); - - OpenflowVersion ofVersion = OpenflowVersion.get(sc.getPrimaryConductor().getVersion()); - final VersionDatapathIdConvertorData data = new VersionDatapathIdConvertorData(sc.getPrimaryConductor().getVersion()); - data.setDatapathId(sc.getFeatures().getDatapathId()); - - if(msg instanceof MultipartReplyMessage){ - MultipartReplyMessage mpReply = (MultipartReplyMessage)msg; - NodeId node = MultipartReplyTranslator.nodeIdFromDatapathId(sc.getFeatures().getDatapathId()); - switch (mpReply.getType()){ - case OFPMPFLOW: { - LOG.debug("Received flow statistics reponse from openflow {} switch",msg.getVersion()==1?"1.0":"1.3+"); - FlowStatsResponseConvertorData flowData = new FlowStatsResponseConvertorData(data.getVersion()); - flowData.setDatapathId(data.getDatapathId()); - flowData.setMatchPath(MatchPath.FLOWSSTATISTICSUPDATE_FLOWANDSTATISTICSMAPLIST_MATCH); - FlowsStatisticsUpdateBuilder message = new FlowsStatisticsUpdateBuilder(); - message.setId(node); - message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE()); - message.setTransactionId(generateTransactionId(mpReply.getXid())); - MultipartReplyFlowCase caseBody = (MultipartReplyFlowCase)mpReply.getMultipartReplyBody(); - MultipartReplyFlow replyBody = caseBody.getMultipartReplyFlow(); - - final Optional> flowAndStatisticsMapLists = convertorExecutor.convert(replyBody.getFlowStats(), flowData); - - message.setFlowAndStatisticsMapList(flowAndStatisticsMapLists.orElse(Collections.emptyList())); - LOG.debug("Converted flow statistics : {}",message.build().toString()); - listDataObject.add(message.build()); - return listDataObject; - } - case OFPMPAGGREGATE: { - LOG.debug("Received aggregate flow statistics reponse from openflow {} switch",msg.getVersion()==1?"1.0":"1.3+"); - AggregateFlowStatisticsUpdateBuilder message = new AggregateFlowStatisticsUpdateBuilder(); - message.setId(node); - message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE()); - message.setTransactionId(generateTransactionId(mpReply.getXid())); - - MultipartReplyAggregateCase caseBody = (MultipartReplyAggregateCase)mpReply.getMultipartReplyBody(); - MultipartReplyAggregate replyBody = caseBody.getMultipartReplyAggregate(); - message.setByteCount(new Counter64(replyBody.getByteCount())); - message.setPacketCount(new Counter64(replyBody.getPacketCount())); - message.setFlowCount(new Counter32(replyBody.getFlowCount())); - - LOG.debug("Converted aggregate flow statistics : {}",message.build().toString()); - listDataObject.add(message.build()); - return listDataObject; - } - case OFPMPPORTSTATS: { - - LOG.debug("Received port statistics multipart response"); - - NodeConnectorStatisticsUpdateBuilder message = new NodeConnectorStatisticsUpdateBuilder(); - message.setId(node); - message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE()); - message.setTransactionId(generateTransactionId(mpReply.getXid())); - - MultipartReplyPortStatsCase caseBody = (MultipartReplyPortStatsCase)mpReply.getMultipartReplyBody(); - MultipartReplyPortStats replyBody = caseBody.getMultipartReplyPortStats(); - - List statsMap = - new ArrayList(); - for (PortStats portStats: replyBody.getPortStats()){ - - NodeConnectorStatisticsAndPortNumberMapBuilder statsBuilder = - new NodeConnectorStatisticsAndPortNumberMapBuilder(); - statsBuilder.setNodeConnectorId( - InventoryDataServiceUtil.nodeConnectorIdfromDatapathPortNo(sc.getFeatures().getDatapathId(), - portStats.getPortNo(), ofVersion)); - - BytesBuilder bytesBuilder = new BytesBuilder(); - bytesBuilder.setReceived(portStats.getRxBytes()); - bytesBuilder.setTransmitted(portStats.getTxBytes()); - statsBuilder.setBytes(bytesBuilder.build()); - - PacketsBuilder packetsBuilder = new PacketsBuilder(); - packetsBuilder.setReceived(portStats.getRxPackets()); - packetsBuilder.setTransmitted(portStats.getTxPackets()); - statsBuilder.setPackets(packetsBuilder.build()); - - DurationBuilder durationBuilder = new DurationBuilder(); - if (portStats.getDurationSec() != null) { - durationBuilder.setSecond(new Counter32(portStats.getDurationSec())); - } - if (portStats.getDurationNsec() != null) { - durationBuilder.setNanosecond(new Counter32(portStats.getDurationNsec())); - } - statsBuilder.setDuration(durationBuilder.build()); - statsBuilder.setCollisionCount(portStats.getCollisions()); - statsBuilder.setKey(new NodeConnectorStatisticsAndPortNumberMapKey(statsBuilder.getNodeConnectorId())); - statsBuilder.setReceiveCrcError(portStats.getRxCrcErr()); - statsBuilder.setReceiveDrops(portStats.getRxDropped()); - statsBuilder.setReceiveErrors(portStats.getRxErrors()); - statsBuilder.setReceiveFrameError(portStats.getRxFrameErr()); - statsBuilder.setReceiveOverRunError(portStats.getRxOverErr()); - statsBuilder.setTransmitDrops(portStats.getTxDropped()); - statsBuilder.setTransmitErrors(portStats.getTxErrors()); - - statsMap.add(statsBuilder.build()); - } - message.setNodeConnectorStatisticsAndPortNumberMap(statsMap); - - LOG.debug("Converted ports statistics : {}",message.build().toString()); - - listDataObject.add(message.build()); - return listDataObject; - } - case OFPMPGROUP:{ - LOG.debug("Received group statistics multipart reponse"); - GroupStatisticsUpdatedBuilder message = new GroupStatisticsUpdatedBuilder(); - message.setId(node); - message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE()); - message.setTransactionId(generateTransactionId(mpReply.getXid())); - MultipartReplyGroupCase caseBody = (MultipartReplyGroupCase)mpReply.getMultipartReplyBody(); - MultipartReplyGroup replyBody = caseBody.getMultipartReplyGroup(); - final Optional> groupStatsList = convertorExecutor.convert(replyBody.getGroupStats(), data); - message.setGroupStats(groupStatsList.orElse(Collections.emptyList())); - LOG.debug("Converted group statistics : {}",message.toString()); - listDataObject.add(message.build()); - return listDataObject; - } - case OFPMPGROUPDESC:{ - LOG.debug("Received group description statistics multipart reponse"); - - GroupDescStatsUpdatedBuilder message = new GroupDescStatsUpdatedBuilder(); - message.setId(node); - message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE()); - message.setTransactionId(generateTransactionId(mpReply.getXid())); - MultipartReplyGroupDescCase caseBody = (MultipartReplyGroupDescCase)mpReply.getMultipartReplyBody(); - MultipartReplyGroupDesc replyBody = caseBody.getMultipartReplyGroupDesc(); - - final Optional> groupDescStatsList = convertorExecutor.convert(replyBody.getGroupDesc(), data); - message.setGroupDescStats(groupDescStatsList.orElse(Collections.emptyList())); - LOG.debug("Converted group statistics : {}",message.toString()); - listDataObject.add(message.build()); - return listDataObject; - } - case OFPMPGROUPFEATURES: { - LOG.debug("Received group features multipart reponse"); - GroupFeaturesUpdatedBuilder message = new GroupFeaturesUpdatedBuilder(); - message.setId(node); - message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE()); - message.setTransactionId(generateTransactionId(mpReply.getXid())); - MultipartReplyGroupFeaturesCase caseBody = (MultipartReplyGroupFeaturesCase)mpReply.getMultipartReplyBody(); - MultipartReplyGroupFeatures replyBody = caseBody.getMultipartReplyGroupFeatures(); - List> supportedGroups = - new ArrayList>(); - - if(replyBody.getTypes().isOFPGTALL()){ - supportedGroups.add(GroupAll.class); - } - if(replyBody.getTypes().isOFPGTSELECT()){ - supportedGroups.add(GroupSelect.class); - } - if(replyBody.getTypes().isOFPGTINDIRECT()){ - supportedGroups.add(GroupIndirect.class); - } - if(replyBody.getTypes().isOFPGTFF()){ - supportedGroups.add(GroupFf.class); - } - message.setGroupTypesSupported(supportedGroups); - message.setMaxGroups(replyBody.getMaxGroups()); - - List> supportedCapabilities = - new ArrayList>(); - - if(replyBody.getCapabilities().isOFPGFCCHAINING()){ - supportedCapabilities.add(Chaining.class); - } - if(replyBody.getCapabilities().isOFPGFCCHAININGCHECKS()){ - supportedCapabilities.add(ChainingChecks.class); - } - if(replyBody.getCapabilities().isOFPGFCSELECTLIVENESS()){ - supportedCapabilities.add(SelectLiveness.class); - } - if(replyBody.getCapabilities().isOFPGFCSELECTWEIGHT()){ - supportedCapabilities.add(SelectWeight.class); - } - - message.setGroupCapabilitiesSupported(supportedCapabilities); - - message.setActions(getGroupActionsSupportBitmap(replyBody.getActionsBitmap())); - listDataObject.add(message.build()); - - return listDataObject; - } - case OFPMPMETER: { - LOG.debug("Received meter statistics multipart reponse"); - MeterStatisticsUpdatedBuilder message = new MeterStatisticsUpdatedBuilder(); - message.setId(node); - message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE()); - message.setTransactionId(generateTransactionId(mpReply.getXid())); - - MultipartReplyMeterCase caseBody = (MultipartReplyMeterCase)mpReply.getMultipartReplyBody(); - MultipartReplyMeter replyBody = caseBody.getMultipartReplyMeter(); - - final Optional> meterStatsList = - convertorExecutor.convert(replyBody.getMeterStats(), data); - - message.setMeterStats(meterStatsList.orElse(Collections.emptyList())); - listDataObject.add(message.build()); - return listDataObject; - } - case OFPMPMETERCONFIG:{ - LOG.debug("Received meter config statistics multipart reponse"); - - MeterConfigStatsUpdatedBuilder message = new MeterConfigStatsUpdatedBuilder(); - message.setId(node); - message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE()); - message.setTransactionId(generateTransactionId(mpReply.getXid())); - - MultipartReplyMeterConfigCase caseBody = (MultipartReplyMeterConfigCase)mpReply.getMultipartReplyBody(); - MultipartReplyMeterConfig replyBody = caseBody.getMultipartReplyMeterConfig(); - - final Optional> meterConfigStatsList = convertorExecutor.convert(replyBody.getMeterConfig(), data); - - message.setMeterConfigStats(meterConfigStatsList.orElse(Collections.emptyList())); - listDataObject.add(message.build()); - return listDataObject; - } - case OFPMPMETERFEATURES:{ - LOG.debug("Received meter features multipart reponse"); - //Convert OF message and send it to SAL listener - MeterFeaturesUpdatedBuilder message = new MeterFeaturesUpdatedBuilder(); - message.setId(node); - message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE()); - message.setTransactionId(generateTransactionId(mpReply.getXid())); - - MultipartReplyMeterFeaturesCase caseBody = (MultipartReplyMeterFeaturesCase)mpReply.getMultipartReplyBody(); - MultipartReplyMeterFeatures replyBody = caseBody.getMultipartReplyMeterFeatures(); - message.setMaxBands(replyBody.getMaxBands()); - message.setMaxColor(replyBody.getMaxColor()); - message.setMaxMeter(new Counter32(replyBody.getMaxMeter())); - - List> supportedCapabilities = - new ArrayList>(); - if(replyBody.getCapabilities().isOFPMFBURST()){ - supportedCapabilities.add(MeterBurst.class); - } - if(replyBody.getCapabilities().isOFPMFKBPS()){ - supportedCapabilities.add(MeterKbps.class); - - } - if(replyBody.getCapabilities().isOFPMFPKTPS()){ - supportedCapabilities.add(MeterPktps.class); - - } - if(replyBody.getCapabilities().isOFPMFSTATS()){ - supportedCapabilities.add(MeterStats.class); - - } - message.setMeterCapabilitiesSupported(supportedCapabilities); - - List> supportedMeterBand = - new ArrayList>(); - if(replyBody.getBandTypes().isOFPMBTDROP()){ - supportedMeterBand.add(MeterBandDrop.class); - } - if(replyBody.getBandTypes().isOFPMBTDSCPREMARK()){ - supportedMeterBand.add(MeterBandDscpRemark.class); - } - message.setMeterBandSupported(supportedMeterBand); - listDataObject.add(message.build()); - - return listDataObject; - } - case OFPMPTABLE: { - LOG.debug("Received flow table statistics reponse from openflow {} switch",msg.getVersion()==1?"1.0":"1.3+"); - - FlowTableStatisticsUpdateBuilder message = new FlowTableStatisticsUpdateBuilder(); - message.setId(node); - message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE()); - message.setTransactionId(generateTransactionId(mpReply.getXid())); - - MultipartReplyTableCase caseBody = (MultipartReplyTableCase)mpReply.getMultipartReplyBody(); - MultipartReplyTable replyBody = caseBody.getMultipartReplyTable(); - List swTablesStats = replyBody.getTableStats(); - - List salFlowStats = new ArrayList(); - for(TableStats swTableStats : swTablesStats){ - FlowTableAndStatisticsMapBuilder statisticsBuilder = new FlowTableAndStatisticsMapBuilder(); - - statisticsBuilder.setActiveFlows(new Counter32(swTableStats.getActiveCount())); - statisticsBuilder.setPacketsLookedUp(new Counter64(swTableStats.getLookupCount())); - statisticsBuilder.setPacketsMatched(new Counter64(swTableStats.getMatchedCount())); - statisticsBuilder.setTableId(new TableId(swTableStats.getTableId())); - salFlowStats.add(statisticsBuilder.build()); - } - - message.setFlowTableAndStatisticsMap(salFlowStats); - - LOG.debug("Converted flow table statistics : {}",message.build().toString()); - listDataObject.add(message.build()); - return listDataObject; - } - case OFPMPQUEUE: { - LOG.debug("Received queue statistics multipart response"); - - QueueStatisticsUpdateBuilder message = new QueueStatisticsUpdateBuilder(); - message.setId(node); - message.setMoreReplies(mpReply.getFlags().isOFPMPFREQMORE()); - message.setTransactionId(generateTransactionId(mpReply.getXid())); - - MultipartReplyQueueCase caseBody = (MultipartReplyQueueCase)mpReply.getMultipartReplyBody(); - MultipartReplyQueue replyBody = caseBody.getMultipartReplyQueue(); - - List statsMap = - new ArrayList(); - - for (QueueStats queueStats: replyBody.getQueueStats()){ - - QueueIdAndStatisticsMapBuilder statsBuilder = - new QueueIdAndStatisticsMapBuilder(); - statsBuilder.setNodeConnectorId( - InventoryDataServiceUtil.nodeConnectorIdfromDatapathPortNo(sc.getFeatures().getDatapathId(), - queueStats.getPortNo(), ofVersion)); - statsBuilder.setTransmissionErrors(new Counter64(queueStats.getTxErrors())); - statsBuilder.setTransmittedBytes(new Counter64(queueStats.getTxBytes())); - statsBuilder.setTransmittedPackets(new Counter64(queueStats.getTxPackets())); - - DurationBuilder durationBuilder = new DurationBuilder(); - durationBuilder.setSecond(new Counter32(queueStats.getDurationSec())); - durationBuilder.setNanosecond(new Counter32(queueStats.getDurationNsec())); - statsBuilder.setDuration(durationBuilder.build()); - - statsBuilder.setQueueId(new QueueId(queueStats.getQueueId())); - statsBuilder.setNodeConnectorId(InventoryDataServiceUtil.nodeConnectorIdfromDatapathPortNo(sc.getFeatures().getDatapathId(), - queueStats.getPortNo(), ofVersion)); - - statsMap.add(statsBuilder.build()); - } - message.setQueueIdAndStatisticsMap(statsMap); - - LOG.debug("Converted queue statistics : {}",message.build().toString()); - listDataObject.add(message.build()); - return listDataObject; - } - - default: - return listDataObject; - } - } - - return listDataObject; - } - - private static NodeId nodeIdFromDatapathId(final BigInteger datapathId) { - String current = datapathId.toString(); - return new NodeId("openflow:" + current); - } - - private static TransactionId generateTransactionId(final Long xid){ - BigInteger bigIntXid = BigInteger.valueOf(xid); - return new TransactionId(bigIntXid); - } - - /* - * Method returns the bitmap of actions supported by each group. - * TODO: My recommendation would be, its good to have a respective model of - * 'type bits', which will generate a class where all these flags will eventually - * be stored as boolean. It will be convenient for application to check the - * supported action, rather then doing bitmap operation. - * @param actionsSupported - * @return - */ - private static List getGroupActionsSupportBitmap(final List actionsSupported){ - List supportActionByGroups = new ArrayList(); - for(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ActionType supportedActions : actionsSupported){ - long supportActionBitmap = 0; - supportActionBitmap |= supportedActions.isOFPATOUTPUT()?(1 << 0): 0; - supportActionBitmap |= supportedActions.isOFPATCOPYTTLOUT()?(1 << 11): 0; - supportActionBitmap |= supportedActions.isOFPATCOPYTTLIN()?(1 << 12): 0; - supportActionBitmap |= supportedActions.isOFPATSETMPLSTTL()?(1 << 15): 0; - supportActionBitmap |= supportedActions.isOFPATDECMPLSTTL()?(1 << 16): 0; - supportActionBitmap |= supportedActions.isOFPATPUSHVLAN()?(1 << 17): 0; - supportActionBitmap |= supportedActions.isOFPATPOPVLAN()?(1 << 18): 0; - supportActionBitmap |= supportedActions.isOFPATPUSHMPLS()?(1 << 19): 0; - supportActionBitmap |= supportedActions.isOFPATPOPMPLS()?(1 << 20): 0; - supportActionBitmap |= supportedActions.isOFPATSETQUEUE()?(1 << 21): 0; - supportActionBitmap |= supportedActions.isOFPATGROUP()?(1 << 22): 0; - supportActionBitmap |= supportedActions.isOFPATSETNWTTL()?(1 << 23): 0; - supportActionBitmap |= supportedActions.isOFPATDECNWTTL()?(1 << 24): 0; - supportActionBitmap |= supportedActions.isOFPATSETFIELD()?(1 << 25): 0; - supportActionBitmap |= supportedActions.isOFPATPUSHPBB()?(1 << 26): 0; - supportActionBitmap |= supportedActions.isOFPATPOPPBB()?(1 << 27): 0; - supportActionByGroups.add(Long.valueOf(supportActionBitmap)); - } - return supportActionByGroups; - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/NotificationPlainTranslator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/NotificationPlainTranslator.java deleted file mode 100644 index 2b14466622..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/NotificationPlainTranslator.java +++ /dev/null @@ -1,51 +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.openflow.md.core.translator; - -import java.math.BigInteger; -import java.util.Collections; -import java.util.List; - -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.Lists; - -/** - * - */ -public class NotificationPlainTranslator implements IMDMessageTranslator> { - - private static final Logger LOG = LoggerFactory - .getLogger(NotificationPlainTranslator.class); - - @Override - public List translate(SwitchConnectionDistinguisher cookie, - SessionContext sc, OfHeader msg) { - List results = null; - - if(msg instanceof NotificationQueueWrapper) { - NotificationQueueWrapper wrappedNotification = (NotificationQueueWrapper) msg; - BigInteger datapathId = sc.getFeatures().getDatapathId(); - Short version = wrappedNotification.getVersion(); - LOG.debug("NotificationQueueWrapper: version {} dataPathId {} notification {}", version, datapathId, wrappedNotification.getImplementedInterface()); - results = Lists.newArrayList((DataObject) wrappedNotification.getNotification()); - } else { - // TODO - Do something smarter than returning null if translation fails... what Exception should we throw here? - results = Collections.emptyList(); - } - return results; - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PacketInTranslator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PacketInTranslator.java deleted file mode 100644 index c3d8401a75..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PacketInTranslator.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.translator; - -import java.math.BigInteger; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion; -import org.opendaylight.openflowplugin.extension.api.AugmentTuple; -import org.opendaylight.openflowplugin.extension.api.path.MatchPath; -import org.opendaylight.openflowplugin.openflow.md.core.extension.MatchExtensionHelper; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.data.VersionDatapathIdConvertorData; -import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil; -import org.opendaylight.openflowplugin.openflow.md.util.PacketInUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntry; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.InPortCase; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.ConnectionCookie; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceivedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.packet.received.MatchBuilder; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * translates packetIn from OF-API model to MD-SAL model, supports OF-1.3 - */ -public class PacketInTranslator implements IMDMessageTranslator> { - - private static final Logger LOG = LoggerFactory - .getLogger(PacketInTranslator.class); - private final ConvertorExecutor convertorExecutor; - - public PacketInTranslator(ConvertorExecutor convertorExecutor) { - this.convertorExecutor = convertorExecutor; - } - - @Override - public List translate(final SwitchConnectionDistinguisher cookie, - final SessionContext sc, final OfHeader msg) { - - List salPacketIn = Collections.emptyList(); - - if (sc != null && msg instanceof PacketInMessage) { - PacketInMessage message = (PacketInMessage) msg; - LOG.trace("PacketIn[v{}]: Cookie: {} Match.type: {}", - message.getVersion(), message.getCookie(), - message.getMatch() != null ? message.getMatch().getType() : message.getMatch()); - - // create a packet received event builder - PacketReceivedBuilder pktInBuilder = new PacketReceivedBuilder(); - pktInBuilder.setPayload(message.getData()); - if (cookie != null) { - pktInBuilder.setConnectionCookie(new ConnectionCookie(cookie.getCookie())); - } - - // get the DPID - GetFeaturesOutput features = sc.getFeatures(); - // Make sure we actually have features, some naughty switches start sending packetIn before they send us the FeatureReply - if (features == null) { - LOG.warn("Received packet_in, but there is no device datapathId received yet"); - } else { - BigInteger dpid = features.getDatapathId(); - - // get the Cookie if it exists - if (message.getCookie() != null) { - pktInBuilder.setFlowCookie(new FlowCookie(message.getCookie())); - } - - // extract the port number - Long port = null; - if (message.getMatch() != null && message.getMatch().getMatchEntry() != null) { - List entries = message.getMatch().getMatchEntry(); - for (MatchEntry entry : entries) { - if(InPortCase.class.equals(entry.getMatchEntryValue().getImplementedInterface())) { - InPortCase inPortCase = ((InPortCase) entry.getMatchEntryValue()); - org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.in.port._case.InPort inPort = inPortCase.getInPort(); - if (inPort != null) { - port = inPort.getPortNumber().getValue(); - break; - } - } - } - } - - if (port == null) { - // no incoming port, so drop the event - LOG.warn("Received packet_in, but couldn't find an input port"); - } else { - LOG.trace("Received packet_in from {} on port {}", dpid, port); - final VersionDatapathIdConvertorData datapathIdConvertorData = new VersionDatapathIdConvertorData(sc.getPrimaryConductor().getVersion()); - datapathIdConvertorData.setDatapathId(dpid); - - final OpenflowVersion ofVersion = OpenflowVersion.get(sc.getPrimaryConductor().getVersion()); - final Optional matchOptional = convertorExecutor.convert(message.getMatch(), datapathIdConvertorData); - final MatchBuilder matchBuilder = new MatchBuilder(matchOptional.orElse(new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder()).build()); - - AugmentTuple matchExtensionWrap = - MatchExtensionHelper.processAllExtensions( - message.getMatch().getMatchEntry(), ofVersion, MatchPath.PACKETRECEIVED_MATCH); - if (matchExtensionWrap != null) { - matchBuilder.addAugmentation(matchExtensionWrap.getAugmentationClass(), matchExtensionWrap.getAugmentationObject()); - } - - org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.packet.received.Match packetInMatch = matchBuilder.build(); - pktInBuilder.setMatch(packetInMatch); - - pktInBuilder.setPacketInReason(PacketInUtil.getMdSalPacketInReason(message.getReason())); - pktInBuilder.setTableId(new org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId(message.getTableId().getValue().shortValue())); - pktInBuilder.setIngress(InventoryDataServiceUtil.nodeConnectorRefFromDatapathIdPortno(dpid, port, ofVersion)); - PacketReceived pktInEvent = pktInBuilder.build(); - salPacketIn = Collections.singletonList(pktInEvent); - } - } - } - return salPacketIn; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PacketInV10Translator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PacketInV10Translator.java deleted file mode 100644 index 978b202a83..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PacketInV10Translator.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.translator; - -import java.math.BigInteger; -import java.util.Collections; -import java.util.List; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion; -import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil; -import org.opendaylight.openflowplugin.openflow.md.util.PacketInUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceivedBuilder; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * translates packetIn from OF-API model to MD-SAL model, supports OF-1.0 - */ -public class PacketInV10Translator implements IMDMessageTranslator> { - - private static final Logger LOG = LoggerFactory - .getLogger(PacketInV10Translator.class); - @Override - public List translate(final SwitchConnectionDistinguisher cookie, - final SessionContext sc, final OfHeader msg) { - - List salPacketIn = Collections.emptyList(); - - if (sc != null && msg instanceof PacketInMessage) { - PacketInMessage message = (PacketInMessage)msg; - LOG.trace("PacketIn[v{}]: InPort: {}", - msg.getVersion(), message.getInPort()); - - // create a packet received event builder - PacketReceivedBuilder pktInBuilder = new PacketReceivedBuilder(); - pktInBuilder.setPayload(message.getData()); - - // get the DPID - GetFeaturesOutput features = sc.getFeatures(); - // Make sure we actually have features, some naughty switches start sending packetIn before they send us the FeatureReply - if ( features == null) { - LOG.warn("Received packet_in, but there is no device datapathId received yet"); - } else { - BigInteger dpid = features.getDatapathId(); - - // extract the port number - Long port = null; - if (message.getInPort() != null) { - port = message.getInPort().longValue(); - } - - if (port == null) { - // no incoming port, so drop the event - LOG.warn("Received packet_in, but couldn't find an input port"); - } else { - LOG.trace("Received packet_in from {} on port {}", dpid, port); - pktInBuilder.setPacketInReason(PacketInUtil.getMdSalPacketInReason(message.getReason())); - pktInBuilder.setIngress(InventoryDataServiceUtil.nodeConnectorRefFromDatapathIdPortno(dpid, port, - OpenflowVersion.get(sc.getPrimaryConductor().getVersion()))); - PacketReceived pktInEvent = pktInBuilder.build(); - salPacketIn = Collections.singletonList(pktInEvent); - } - } - } - return salPacketIn; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PortStatusMessageToNodeConnectorUpdatedTranslator.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PortStatusMessageToNodeConnectorUpdatedTranslator.java deleted file mode 100644 index 46f66628ef..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PortStatusMessageToNodeConnectorUpdatedTranslator.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.translator; - -import java.math.BigInteger; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.util.PortTranslatorUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * translates {@link PortStatusMessage} from OF-API model to MD-SAL model, - * supports OF-{1.0; 1.3} - */ -public class PortStatusMessageToNodeConnectorUpdatedTranslator implements IMDMessageTranslator> { - private static final Logger LOG = LoggerFactory - .getLogger(PortStatusMessageToNodeConnectorUpdatedTranslator.class); - - @Override - public List translate(SwitchConnectionDistinguisher cookie, - SessionContext sc, OfHeader msg) { - if(msg instanceof PortStatusMessage) { - PortStatusMessage port = (PortStatusMessage)msg; - List list = new CopyOnWriteArrayList(); - BigInteger datapathId = sc.getFeatures().getDatapathId(); - Long portNo = port.getPortNo(); - Short version = port.getVersion(); - if(port.getReason() == PortReason.OFPPRDELETE){ - LOG.debug("PortStatusMessage: version {} dataPathId {} portNo {} reason {}",version, datapathId,portNo,port.getReason()); - list.add(PortTranslatorUtil.translatePortRemoved(version, datapathId, portNo, port)); - - }else{ - LOG.debug("PortStatusMessage: version {} dataPathId {} portNo {}",version, datapathId,portNo); - list.add(PortTranslatorUtil.translatePort(version, datapathId, portNo, port)); - } - return list; - } else { - // TODO - Do something smarter than returning null if translation fails... what Exception should we throw here? - return Collections.emptyList(); - } - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/MessageSourcePollRegistration.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/MessageSourcePollRegistration.java deleted file mode 100644 index cc543eb991..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/MessageSourcePollRegistration.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - - -import org.opendaylight.openflowplugin.api.openflow.md.queue.MessageSourcePollRegistrator; - -/** - * closable registration for {@link org.opendaylight.openflowplugin.api.openflow.md.queue.MessageSourcePollRegistrator} - * @param queue input message type - */ -public class MessageSourcePollRegistration implements AutoCloseable { - - private MessageSourcePollRegistrator messageSourceRegistry; - private IN messageSource; - - /** - * @param messageSourceRegistry message source registry - * @param messageSource message source - */ - public MessageSourcePollRegistration(MessageSourcePollRegistrator messageSourceRegistry, - IN messageSource) { - this.messageSourceRegistry = messageSourceRegistry; - this.messageSource = messageSource; - } - - @Override - public void close() throws Exception { - messageSourceRegistry.unregisterMessageSource(messageSource); - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueItemOFImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueItemOFImpl.java deleted file mode 100644 index 9ecdf433f3..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueItemOFImpl.java +++ /dev/null @@ -1,52 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueItem; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper.QueueType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; - -/** - * QueueItem implementation based on {@link OfHeader} - */ -public class QueueItemOFImpl implements QueueItem { - - private OfHeader message; - private ConnectionConductor connectionConductor; - private QueueType queueType; - - - - /** - * @param message openflow message - * @param connectionConductor switch connection conductor - * @param queueType queue type - */ - public QueueItemOFImpl(OfHeader message, - ConnectionConductor connectionConductor, QueueType queueType) { - this.message = message; - this.connectionConductor = connectionConductor; - this.queueType = queueType; - } - - @Override - public OfHeader getMessage() { - return message; - } - - @Override - public ConnectionConductor getConnectionConductor() { - return connectionConductor; - } - - @Override - public QueueType getQueueType() { - return queueType; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueKeeperFactory.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueKeeperFactory.java deleted file mode 100644 index 918dfede32..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueKeeperFactory.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - -import org.opendaylight.openflowplugin.api.openflow.md.queue.MessageSourcePollRegistrator; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper; -import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; - -/** - * factory for - * {@link org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper} - * implementations - */ -public abstract class QueueKeeperFactory { - - /** - * @param sourceRegistrator source registrator - * @param capacity blocking queue capacity - * @param waterMarkListener water mark listener - * @return fair reading implementation of - * {@link org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper} - * (not registered = not started yet) - */ - public static QueueKeeper createFairQueueKeeper( - MessageSourcePollRegistrator> sourceRegistrator, - int capacity, WaterMarkListener waterMarkListener) { - QueueKeeperFairImpl queueKeeper = new QueueKeeperFairImpl(); - queueKeeper.setCapacity(capacity); - queueKeeper.setHarvesterHandle(sourceRegistrator.getHarvesterHandle()); - queueKeeper.setWaterMarkListener(waterMarkListener); - queueKeeper.init(); - - return queueKeeper; - } - - /** - * register queue by harvester, start processing it. Use - * {@link QueueKeeperFairImpl#close()} to kill the queue and stop - * processing. - * - * @param sourceRegistrator source registrator - * @param queueKeeper queue keeper - */ - public static void plugQueue( - MessageSourcePollRegistrator> sourceRegistrator, - QueueKeeper queueKeeper) { - AutoCloseable registration = sourceRegistrator - .registerMessageSource(queueKeeper); - queueKeeper.setPollRegistration(registration); - sourceRegistrator.getHarvesterHandle().ping(); - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueKeeperFairImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueKeeperFairImpl.java deleted file mode 100644 index 656df50e57..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueKeeperFairImpl.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - -import com.google.common.base.Preconditions; -import java.util.Queue; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.queue.HarvesterHandle; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueItem; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper; -import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListener; -import org.opendaylight.openflowplugin.api.openflow.md.util.PollableQueuesPriorityZipper; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * QueueKeeper implementation based on {@link OfHeader} - */ -public class QueueKeeperFairImpl implements QueueKeeper { - - private static final Logger LOG = LoggerFactory - .getLogger(QueueKeeperFairImpl.class); - - private Queue> queueDefault; - private BlockingQueue> queueUnordered; - private AutoCloseable pollRegistration; - private int capacity = 5000; - private HarvesterHandle harvesterHandle; - private PollableQueuesPriorityZipper> queueZipper; - - private WaterMarkListener waterMarkListener; - - @Override - public void close() throws Exception { - Preconditions.checkNotNull(pollRegistration, - "pollRegistration not available"); - pollRegistration.close(); - } - - @Override - public void push(OfHeader message, ConnectionConductor conductor, - QueueKeeper.QueueType queueType) { - QueueItemOFImpl qItem = new QueueItemOFImpl(message, conductor, - queueType); - boolean enqueued = false; - - switch (queueType) { - case DEFAULT: - enqueued = queueDefault.offer(qItem); - break; - case UNORDERED: - enqueued = queueUnordered.offer(qItem); - break; - default: - LOG.warn("unsupported queue type: [{}] -> dropping message [{}]", - queueType, message.getImplementedInterface()); - } - - if (enqueued) { - harvesterHandle.ping(); - } else { - LOG.debug("ingress throttling is use -> {}", queueType); - } - - // if enqueueing fails -> message will be dropped - } - - /** - * @return the ingressQueue - */ - @Override - public QueueItem poll() { - return queueZipper.poll(); - } - - /** - * @param processingRegistration - * the processingRegistration to set - */ - @Override - public void setPollRegistration(AutoCloseable processingRegistration) { - this.pollRegistration = processingRegistration; - } - - /** - * @param capacity - * the capacity of internal blocking queue - */ - public void setCapacity(int capacity) { - this.capacity = capacity; - } - - /** - * init blocking queue - */ - public void init() { - Preconditions.checkNotNull(waterMarkListener); - queueUnordered = new ArrayBlockingQueue<>(capacity); - queueDefault = new ArrayBlockingQueue<>(capacity); - WrapperQueueImpl> wrapperQueue = new WrapperQueueImpl<>( - capacity, queueDefault, waterMarkListener); - queueZipper = new PollableQueuesPriorityZipper<>(); - queueZipper.addSource(queueUnordered); - queueZipper.setPrioritizedSource(wrapperQueue); - } - - public void setWaterMarkListener(WaterMarkListener waterMarkListener) { - this.waterMarkListener = waterMarkListener; - } - - /** - * @param harvesterHandle harvester handle - */ - public void setHarvesterHandle(HarvesterHandle harvesterHandle) { - this.harvesterHandle = harvesterHandle; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueKeeperHarvester.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueKeeperHarvester.java deleted file mode 100644 index 3d4657f5d0..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueKeeperHarvester.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - -import java.util.Collection; -import org.opendaylight.openflowplugin.api.openflow.md.queue.Enqueuer; -import org.opendaylight.openflowplugin.api.openflow.md.queue.HarvesterHandle; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueItem; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @param Type of queue keeper harvester - * - */ -public class QueueKeeperHarvester implements Runnable, HarvesterHandle { - private static final Logger LOG = LoggerFactory.getLogger(QueueKeeperHarvester.class); - - private final Collection> messageSources; - private final Enqueuer> enqueuer; - private final Object harvestLock = new Object(); - private volatile boolean finishing = false; - private volatile boolean wakeMe = false; - - /** - * @param enqueuer queue enqueuer - * @param messageSources source of message - */ - public QueueKeeperHarvester(final Enqueuer> enqueuer, - final Collection> messageSources) { - this.enqueuer = enqueuer; - this.messageSources = messageSources; - } - - @Override - public void run() { - while (!finishing) { - boolean starving = true; - for (QueueKeeper source : messageSources) { - QueueItem qItem = source.poll(); - if (qItem != null) { - starving = false; - enqueuer.enqueueQueueItem(qItem); - } - } - - if (starving) { - LOG.trace("messageHarvester is about to make a starve sleep"); - synchronized (harvestLock) { - wakeMe = true; - try { - this.harvestLock.wait(); - LOG.trace("messageHarvester is waking up from a starve sleep"); - } catch (InterruptedException e) { - LOG.warn("message harvester has been interrupted during starve sleep", e); - } finally { - wakeMe = false; - } - } - } - } - } - - /** - * finish harvester - */ - public void shutdown() { - this.finishing = true; - ping(); - } - - @Override - public void ping() { - if (wakeMe) { - synchronized (harvestLock) { - // Might've raced while waiting for lock, so need to recheck - if (wakeMe) { - LOG.debug("pinging message harvester in starve status"); - harvestLock.notify(); - } - } - } - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueProcessorLightImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueProcessorLightImpl.java deleted file mode 100644 index 60f6114b9b..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/QueueProcessorLightImpl.java +++ /dev/null @@ -1,242 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; -import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey; -import org.opendaylight.openflowplugin.api.openflow.md.queue.HarvesterHandle; -import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueItem; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy.StatisticsGroup; -import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -/** - * {@link org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper} implementation focused to keep order and use up mutiple threads for translation phase. - *
- * There is internal thread pool of limited size ({@link QueueProcessorLightImpl#setProcessingPoolSize(int)}) - * dedicated to translation. Then there is singleThreadPool dedicated to publishing (via popListeners) - *
- * Workflow: - *
    - *
  1. upon message push ticket is created and enqueued
  2. - *
  3. available threads from internal pool translate the massage wrapped in ticket
  4. - *
  5. when translation of particular message is finished, result is set in future result of wrapping ticket
    - * (order of tickets in queue is not touched during translate) - *
  6. - *
  7. at the end of queue there is {@link TicketFinisher} running in singleThreadPool and for each ticket it does: - *
      - *
    1. invoke blocking {@link BlockingQueue#take()} method in order to get the oldest ticket
    2. - *
    3. invoke blocking {@link Future#get()} on the dequeued ticket
    4. - *
    5. as soon as the result of translation is available, appropriate popListener is invoked
    6. - *
    - * and this way the order of messages is preserved and also multiple threads are used by translating - *
  8. - *
- * - * - */ -public class QueueProcessorLightImpl implements QueueProcessor { - - private static final Logger LOG = LoggerFactory - .getLogger(QueueProcessorLightImpl.class); - - private BlockingQueue> ticketQueue; - private ThreadPoolExecutor processorPool; - private int processingPoolSize = 4; - private ExecutorService harvesterPool; - private ExecutorService finisherPool; - - protected Map, Collection>> popListenersMapping; - private Map>>> translatorMapping; - private TicketProcessorFactory ticketProcessorFactory; - private MessageSpy messageSpy; - protected Collection> messageSources; - private QueueKeeperHarvester harvester; - - protected TicketFinisher finisher; - - /** - * prepare queue - */ - public void init() { - int ticketQueueCapacity = 1500; - ticketQueue = new ArrayBlockingQueue<>(ticketQueueCapacity); - /* - * TODO FIXME - DOES THIS REALLY NEED TO BE CONCURRENT? Can we figure out - * a better lifecycle? Why does this have to be a Set? - */ - messageSources = new CopyOnWriteArraySet<>(); - - processorPool = new ThreadPoolLoggingExecutor(processingPoolSize, processingPoolSize, 0, - TimeUnit.MILLISECONDS, - new ArrayBlockingQueue(ticketQueueCapacity), - "OFmsgProcessor"); - // force blocking when pool queue is full - processorPool.setRejectedExecutionHandler(new RejectedExecutionHandler() { - @Override - public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { - try { - executor.getQueue().put(r); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(e); - } - } - }); - - harvesterPool = new ThreadPoolLoggingExecutor(1, 1, 0, - TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), "OFmsgHarvester"); - finisherPool = new ThreadPoolLoggingExecutor(1, 1, 0, - TimeUnit.MILLISECONDS, new ArrayBlockingQueue(1), "OFmsgFinisher"); - finisher = new TicketFinisherImpl( - ticketQueue, popListenersMapping); - finisherPool.execute(finisher); - - harvester = new QueueKeeperHarvester(this, messageSources); - harvesterPool.execute(harvester); - - ticketProcessorFactory = new TicketProcessorFactoryImpl(); - ticketProcessorFactory.setTranslatorMapping(translatorMapping); - ticketProcessorFactory.setSpy(messageSpy); - ticketProcessorFactory.setTicketFinisher(finisher); - } - - /** - * stop processing queue - */ - public void shutdown() { - processorPool.shutdown(); - } - - @Override - public void enqueueQueueItem(QueueItem queueItem) { - messageSpy.spyMessage(queueItem.getMessage(), StatisticsGroup.FROM_SWITCH_ENQUEUED); - TicketImpl ticket = new TicketImpl<>(); - ticket.setConductor(queueItem.getConnectionConductor()); - ticket.setMessage(queueItem.getMessage()); - ticket.setQueueType(queueItem.getQueueType()); - - LOG.trace("ticket scheduling: {}, ticket: {}", - queueItem.getMessage().getImplementedInterface().getSimpleName(), - System.identityHashCode(queueItem)); - scheduleTicket(ticket); - } - - - @Override - public void directProcessQueueItem(QueueItem queueItem) { - messageSpy.spyMessage(queueItem.getMessage(), StatisticsGroup.FROM_SWITCH_ENQUEUED); - TicketImpl ticket = new TicketImpl<>(); - ticket.setConductor(queueItem.getConnectionConductor()); - ticket.setMessage(queueItem.getMessage()); - - LOG.debug("ticket scheduling: {}, ticket: {}", - queueItem.getMessage().getImplementedInterface().getSimpleName(), - System.identityHashCode(queueItem)); - - ticketProcessorFactory.createProcessor(ticket).run(); - - // publish notification - finisher.firePopNotification(ticket.getDirectResult()); - } - - /** - * @param ticket - */ - private void scheduleTicket(Ticket ticket) { - switch (ticket.getQueueType()) { - case DEFAULT: - Runnable ticketProcessor = ticketProcessorFactory.createProcessor(ticket); - processorPool.execute(ticketProcessor); - try { - ticketQueue.put(ticket); - } catch (InterruptedException e) { - LOG.warn("enqeueue of unordered message ticket failed", e); - } - break; - case UNORDERED: - Runnable ticketProcessorSync = ticketProcessorFactory.createSyncProcessor(ticket); - processorPool.execute(ticketProcessorSync); - break; - default: - LOG.warn("unsupported enqueue type: {}", ticket.getQueueType()); - } - } - - /** - * @param poolSize the poolSize to set - */ - public void setProcessingPoolSize(int poolSize) { - this.processingPoolSize = poolSize; - } - - @Override - public void setTranslatorMapping( - Map>>> translatorMapping) { - this.translatorMapping = translatorMapping; - } - - @Override - public void setPopListenersMapping( - Map, Collection>> popListenersMapping) { - this.popListenersMapping = popListenersMapping; - } - - /** - * @param messageSpy the messageSpy to set - */ - public void setMessageSpy(MessageSpy messageSpy) { - this.messageSpy = messageSpy; - } - - @Override - public AutoCloseable registerMessageSource(QueueKeeper queue) { - boolean added = messageSources.add(queue); - if (! added) { - LOG.debug("registration of message source queue failed - already registered"); - } - MessageSourcePollRegistration> queuePollRegistration = - new MessageSourcePollRegistration<>(this, queue); - return queuePollRegistration; - } - - @Override - public boolean unregisterMessageSource(QueueKeeper queue) { - return messageSources.remove(queue); - } - - @Override - public Collection> getMessageSources() { - return messageSources; - } - - @Override - public HarvesterHandle getHarvesterHandle() { - return harvester; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/Ticket.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/Ticket.java deleted file mode 100644 index b3d155f87a..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/Ticket.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper.QueueType; - -/** - * @author mirehak - * - * @param source type of process ticket - * @param resulting type of process ticket - */ -public interface Ticket extends TicketResult { - - /** - * @return connection wrapper - */ - ConnectionConductor getConductor(); - - /** - * @return processed message - */ - IN getMessage(); - - /** - * @return queue type associated with ticket - */ - QueueType getQueueType(); -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketFinisher.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketFinisher.java deleted file mode 100644 index d312d62fac..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketFinisher.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - -import java.util.List; - -/** - * @param result type - * - */ -public interface TicketFinisher extends Runnable { - - /** - * initiate shutdown of this worker - */ - void finish(); - - /** - * notify popListeners - * @param processedMessages processed message - */ - void firePopNotification(List processedMessages); -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketFinisherImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketFinisherImpl.java deleted file mode 100644 index 111f5c7226..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketFinisherImpl.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.concurrent.BlockingQueue; - -import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class TicketFinisherImpl implements TicketFinisher { - - private static final Logger LOG = LoggerFactory - .getLogger(TicketFinisherImpl.class); - - private final Map, Collection>> popListenersMapping; - - private boolean finished; - - private BlockingQueue> queue; - - /** - * @param queue ticket queue - * @param popListenersMapping message pop listener - */ - public TicketFinisherImpl(BlockingQueue> queue, - Map, Collection>> popListenersMapping) { - this.queue = queue; - this.popListenersMapping = popListenersMapping; - } - - @Override - public void run() { - while (! finished ) { - try { - //TODO:: handle shutdown of queue - TicketResult result = queue.take(); - List processedMessages = result.getResult().get(); - firePopNotification(processedMessages); - } catch (Exception e) { - LOG.warn("processing (translate, publish) of ticket failed", e); - } - } - } - - @Override - public void firePopNotification(List processedMessages) { - for (DataObject msg : processedMessages) { - Class registeredType = - msg.getImplementedInterface(); - Collection> popListeners = popListenersMapping.get(registeredType); - if (popListeners == null) { - LOG.warn("no popListener registered for type {}", registeredType); - } else { - for (PopListener consumer : popListeners) { - try { - consumer.onPop(msg); - } catch (Exception e){ - LOG.warn("firePopNotification: processing (translate, publish) of ticket failed for consumer {} msg {} Exception: ", consumer, msg,e); - } - } - } - } - } - - /** - * initiate shutdown of this worker - */ - @Override - public void finish() { - finished = true; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketImpl.java deleted file mode 100644 index cd301de78a..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketImpl.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - -import java.util.List; - -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueKeeper.QueueType; - -import com.google.common.util.concurrent.SettableFuture; - -/** - * @param source type - * @param result type - */ -public class TicketImpl implements Ticket { - - private IN message; - private ConnectionConductor conductor; - private SettableFuture> future; - private QueueType queueType; - private List directResult; - - /** - * default ctor - */ - public TicketImpl() { - future = SettableFuture.create(); - } - - @Override - public SettableFuture> getResult() { - return future; - } - - /** - * @return the message - */ - @Override - public IN getMessage() { - return message; - } - - /** - * @param message the message to set - */ - public void setMessage(IN message) { - this.message = message; - } - - /** - * @return the conductor - */ - @Override - public ConnectionConductor getConductor() { - return conductor; - } - - /** - * @param conductor the conductor to set - */ - public void setConductor(ConnectionConductor conductor) { - this.conductor = conductor; - } - - /** - * @param queueType the queueType to set - */ - public void setQueueType(QueueType queueType) { - this.queueType = queueType; - } - - @Override - public QueueType getQueueType() { - return queueType; - } - - /** - * @return the directResult - */ - @Override - public List getDirectResult() { - return directResult; - } - - /** - * @param directResult the directResult to set - */ - @Override - public void setDirectResult(List directResult) { - this.directResult = directResult; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketProcessorFactory.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketProcessorFactory.java deleted file mode 100644 index 3018d8212c..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketProcessorFactory.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.binding.DataObject; - -/** - * @param type of DataObject - * @param type of DataObject - */ -public interface TicketProcessorFactory { - - /** - * @param ticket ticket - * @return runnable ticket processor - */ - Runnable createProcessor(final Ticket ticket); - - /** - * @param ticket ticket - * @return runnable ticket processor - */ - Runnable createSyncProcessor(final Ticket ticket); - - /** - * @param ticket ticket - * @return translated messages - * - */ - List translate(Ticket ticket); - - /** - * @param ticketFinisher setter - */ - void setTicketFinisher(TicketFinisher ticketFinisher); - - /** - * @param spy setter - */ - void setSpy(MessageSpy spy); - - /** - * @param translatorMapping setter - */ - void setTranslatorMapping(Map>>> translatorMapping); -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketProcessorFactoryImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketProcessorFactoryImpl.java deleted file mode 100644 index 45fc0433eb..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketProcessorFactoryImpl.java +++ /dev/null @@ -1,177 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - -import com.google.common.collect.ImmutableMap; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * OfHeader to DataObject implementation - */ -public class TicketProcessorFactoryImpl implements TicketProcessorFactory { - - private static final Logger LOG = LoggerFactory - .getLogger(TicketProcessorFactoryImpl.class); - - protected Map>>> translatorMapping; - protected MessageSpy spy; - protected TicketFinisher ticketFinisher; - - /** - * @param translatorMapping the translatorMapping to set - */ - @Override - public void setTranslatorMapping( - Map>>> translatorMapping) { - this.translatorMapping = ImmutableMap.copyOf(translatorMapping); - } - - /** - * @param spy the spy to set - */ - @Override - public void setSpy(MessageSpy spy) { - this.spy = spy; - } - - /** - * @param ticketFinisher the finisher to set - */ - @Override - public void setTicketFinisher(TicketFinisher ticketFinisher) { - this.ticketFinisher = ticketFinisher; - } - - /** - * @param ticket ticket - * @return runnable ticket processor - */ - @Override - public Runnable createProcessor(final Ticket ticket) { - - Runnable ticketProcessor = new Runnable() { - @Override - public void run() { - LOG.debug("message received, type: {}", ticket.getMessage().getImplementedInterface().getSimpleName()); - List translate; - try { - translate = translate(ticket); - ticket.getResult().set(translate); - ticket.setDirectResult(translate); - // spying on result - if (spy != null) { - spy.spyIn(ticket.getMessage()); - for (DataObject outMessage : translate) { - spy.spyOut(outMessage); - } - } - } catch (Exception e) { - LOG.warn("translation problem: {}", e.getMessage()); - ticket.getResult().setException(e); - } - LOG.debug("message processing done (type: {}, ticket: {})", - ticket.getMessage().getImplementedInterface().getSimpleName(), - System.identityHashCode(ticket)); - } - }; - - - return ticketProcessor; - } - - /** - * @param ticket ticket - * @return runnable ticket processor - */ - @Override - public Runnable createSyncProcessor(final Ticket ticket) { - - Runnable ticketProcessor = new Runnable() { - @Override - public void run() { - List translate; - try { - translate = translate(ticket); - // spying on result - if (spy != null) { - spy.spyIn(ticket.getMessage()); - for (DataObject outMessage : translate) { - spy.spyOut(outMessage); - } - } - ticketFinisher.firePopNotification(translate); - } catch (Exception e) { - LOG.error("translation problem: {}", e.getMessage()); - ticket.getResult().setException(e); - } - } - }; - - - return ticketProcessor; - } - - - /** - * @param ticket ticket - * - */ - @Override - public List translate(Ticket ticket) { - List result = new ArrayList<>(); - - OfHeader message = ticket.getMessage(); - Class messageType = ticket.getMessage().getImplementedInterface(); - ConnectionConductor conductor = ticket.getConductor(); - Collection>> translators = null; - LOG.trace("translating ticket: {}, ticket: {}", messageType.getSimpleName(), System.identityHashCode(ticket)); - - Short version = message.getVersion(); - if (version == null) { - throw new IllegalArgumentException("version is NULL"); - } - TranslatorKey tKey = new TranslatorKey(version, messageType.getName()); - translators = translatorMapping.get(tKey); - - LOG.debug("translatorKey: {} + {}", version, messageType.getName()); - - if (translators != null) { - for (IMDMessageTranslator> translator : translators) { - SwitchConnectionDistinguisher cookie = null; - // Pass cookie only for PACKT_OfHeader - if (messageType.equals("PacketInMessage.class")) { - cookie = conductor.getAuxiliaryKey(); - } - long start = System.nanoTime(); - List translatorOutput = translator.translate(cookie, conductor.getSessionContext(), message); - long end = System.nanoTime(); - LOG.trace("translator: {} elapsed time {} ns",translator,end-start); - if(translatorOutput != null && !translatorOutput.isEmpty()) { - result.addAll(translatorOutput); - } - } - } else { - LOG.warn("No translators for this message Type: {}", messageType); - } - - return result; - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketResult.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketResult.java deleted file mode 100644 index 031d26ae2c..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/TicketResult.java +++ /dev/null @@ -1,35 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.queue; - -import java.util.List; - -import com.google.common.util.concurrent.SettableFuture; - -/** - * @author mirehak - * @param result typer - */ -public interface TicketResult { - - /** - * @return processed result - */ - SettableFuture> getResult(); - - /** - * @return direct access to result - */ - List getDirectResult(); - - /** - * @param directResult setter for direct result - */ - void setDirectResult(List directResult); - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/WrapperQueueImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/WrapperQueueImpl.java deleted file mode 100644 index 538691dba5..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/queue/WrapperQueueImpl.java +++ /dev/null @@ -1,157 +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.openflow.md.queue; - -import com.google.common.base.Preconditions; -import java.util.Collection; -import java.util.Iterator; -import java.util.Queue; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueItem; -import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class WrapperQueueImpl implements Queue { - - private static final Logger LOG = LoggerFactory - .getLogger(WrapperQueueImpl.class); - - private int lowWaterMark; - private int highWaterMark; - - private WaterMarkListener queueListenerMark; - - private Queue queueDefault; - - private boolean flooded; - - /** - * @param capacity - */ - public WrapperQueueImpl(int capacity, Queue queueDefault, - WaterMarkListener queueListenerMark) { - this.queueListenerMark = queueListenerMark; - this.queueDefault = Preconditions.checkNotNull(queueDefault); - - this.highWaterMark = (int) (capacity * 0.8); - this.lowWaterMark = (int) (capacity * 0.65); - } - - /** - * Marking checks size of {@link #queueDefault} and on the basis of this is - * set autoRead - */ - private void marking() { - if (queueDefault.size() >= highWaterMark && !flooded) { - queueListenerMark.onHighWaterMark(); - flooded = true; - } else if (queueDefault.size() <= lowWaterMark && flooded) { - queueListenerMark.onLowWaterMark(); - flooded = false; - } - } - - /** - * @return true if flooded - */ - public boolean isFlooded() { - return flooded; - } - - /** - * poll {@link QueueItem} and call {@link #marking()} for check marks and - * set autoRead if it need it - * - * @return polled item - */ - public E poll() { - E nextQueueItem = queueDefault.poll(); - marking(); - return nextQueueItem; - } - - public boolean add(E e) { - return queueDefault.add(e); - } - - public int size() { - return queueDefault.size(); - } - - public boolean isEmpty() { - return queueDefault.isEmpty(); - } - - public boolean contains(Object o) { - return queueDefault.contains(o); - } - - public boolean offer(E e) { - boolean enqueueResult = queueDefault.offer(e); - marking(); - return enqueueResult; - } - - public Iterator iterator() { - return queueDefault.iterator(); - } - - public E remove() { - return queueDefault.remove(); - } - - public Object[] toArray() { - return queueDefault.toArray(); - } - - public E element() { - return queueDefault.element(); - } - - public E peek() { - return queueDefault.peek(); - } - - public T[] toArray(T[] a) { - return queueDefault.toArray(a); - } - - public boolean remove(Object o) { - return queueDefault.remove(o); - } - - public boolean containsAll(Collection c) { - return queueDefault.containsAll(c); - } - - public boolean addAll(Collection c) { - return queueDefault.addAll(c); - } - - public boolean removeAll(Collection c) { - return queueDefault.removeAll(c); - } - - public boolean retainAll(Collection c) { - return queueDefault.retainAll(c); - } - - public void clear() { - queueDefault.clear(); - } - - public boolean equals(Object o) { - return queueDefault.equals(o); - } - - public int hashCode() { - return queueDefault.hashCode(); - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/ByteUtil.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/ByteUtil.java index c41c26b8b0..115c146f29 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/ByteUtil.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/ByteUtil.java @@ -13,9 +13,6 @@ import java.util.Arrays; import com.google.common.base.Preconditions; import com.google.common.io.BaseEncoding; -/** - * @author mirehak - */ public abstract class ByteUtil { /** default hex string separator */ diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/InventoryDataServiceUtil.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/InventoryDataServiceUtil.java index 65b8bd00c4..3d2d92dd3c 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/InventoryDataServiceUtil.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/InventoryDataServiceUtil.java @@ -8,20 +8,17 @@ package org.opendaylight.openflowplugin.openflow.md.util; import com.google.common.base.Optional; +import com.google.common.base.Splitter; import java.math.BigInteger; import java.util.List; import java.util.concurrent.ExecutionException; - -import com.google.common.base.Splitter; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang3.StringUtils; import org.opendaylight.controller.md.sal.binding.api.ReadTransaction; -import org.opendaylight.controller.md.sal.binding.api.WriteTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.openflowplugin.api.OFConstants; import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdatedBuilder; @@ -50,45 +47,6 @@ public abstract class InventoryDataServiceUtil { */ private static final InstanceIdentifier NODES_IDENTIFIER = InstanceIdentifier.create(Nodes.class); - public static Nodes checkForNodes() { - Nodes nodes = null; - LOG.error("Before Nodes - nodes: " + nodes); - try { - nodes = getDataObject(OFSessionUtil.getSessionManager().getDataBroker().newReadOnlyTransaction(), NODES_IDENTIFIER); - } catch (Exception e) { - LOG.error( - "Caught exception from OFSessionUtil.getSessionManager().getDataBroker().newReadWriteTransaction()", - e); - } - LOG.error("After Nodes- nodes: " + nodes); - return nodes; - } - - public static List readAllNodes() { - Nodes nodes = getDataObject(OFSessionUtil.getSessionManager().getDataBroker().newReadOnlyTransaction(), NODES_IDENTIFIER); - return nodes.getNode(); - } - - public static Node readNode(final InstanceIdentifier instance) { - return getDataObject(OFSessionUtil.getSessionManager().getDataBroker().newReadOnlyTransaction(), instance); - } - - public static void putNodeConnector(final InstanceIdentifier instance, final NodeConnector nodeConnector) { - WriteTransaction transaction = OFSessionUtil.getSessionManager().getDataBroker().newWriteOnlyTransaction(); - InstanceIdentifier nodeConnectorID = instance.child(NodeConnector.class, nodeConnector.getKey()); - transaction.merge(LogicalDatastoreType.OPERATIONAL, nodeConnectorID, nodeConnector); - transaction.submit(); - } - - public static void putNodeConnector(final NodeKey nodeKey, final NodeConnector nodeConnector) { - InstanceIdentifier instance = nodeKeyToInstanceIdentifier(nodeKey); - putNodeConnector(instance, nodeConnector); - } - - public static void putNodeConnector(final NodeId nodeId, final NodeConnector nodeConnector) { - putNodeConnector(new NodeKey(nodeId), nodeConnector); - } - public static InstanceIdentifier identifierFromDatapathId(final BigInteger datapathId) { NodeKey nodeKey = nodeKeyFromDatapathId(datapathId); return NODES_IDENTIFIER.child(Node.class, nodeKey); diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/OpenflowPortsUtil.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/OpenflowPortsUtil.java index 3e69463127..1e207cc3de 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/OpenflowPortsUtil.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/OpenflowPortsUtil.java @@ -26,8 +26,6 @@ import org.slf4j.LoggerFactory; * Class which integrates the port constants defined and used by MDSAL and the ports defined in openflow java * This class is responsible for converting MDSAL given logical names to port numbers and back. * Any newer version of openflow can have a similar mapping or can/should be extended. - * - * @author Kamal Rameshan on 5/2/14. */ public class OpenflowPortsUtil { diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/PacketInUtil.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/PacketInUtil.java index 0f2698b865..d7dfa991f8 100644 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/PacketInUtil.java +++ b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/PacketInUtil.java @@ -13,9 +13,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.No import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketInReason; import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.SendToController; -/** - * - */ public final class PacketInUtil { private PacketInUtil(){ diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/RoleUtil.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/RoleUtil.java deleted file mode 100644 index 1189a2befa..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/RoleUtil.java +++ /dev/null @@ -1,162 +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.openflow.md.util; - -import com.google.common.base.Function; -import com.google.common.util.concurrent.CheckedFuture; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.JdkFutureAdapters; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.SettableFuture; -import java.math.BigInteger; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager; -import org.opendaylight.openflowplugin.openflow.md.core.session.RolePushException; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ControllerRole; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public final class RoleUtil { - - private static final Logger LOG = LoggerFactory.getLogger(RoleUtil.class); - private static final Function exceptionFunction = new Function() { - @Override - public RolePushException apply(Exception input) { - RolePushException output = null; - if (input instanceof ExecutionException) { - if (input.getCause() instanceof RolePushException) { - output = (RolePushException) input.getCause(); - } - } - - if (output == null) { - output = new RolePushException(input.getMessage(), input); - } - - return output; - } - }; - - private RoleUtil() { - throw new UnsupportedOperationException("RoleUtil is not expected to be instantiated."); - } - - /** - * @param role openflow role for controller - * @return protocol role - */ - public static ControllerRole toOFJavaRole(OfpRole role) { - ControllerRole ofJavaRole = null; - switch (role) { - case BECOMEMASTER: - ofJavaRole = ControllerRole.OFPCRROLEMASTER; - break; - case BECOMESLAVE: - ofJavaRole = ControllerRole.OFPCRROLESLAVE; - break; - case NOCHANGE: - ofJavaRole = ControllerRole.OFPCRROLENOCHANGE; - break; - default: - // no intention - LOG.warn("given role is not supported by protocol roles: {}", role); - break; - } - return ofJavaRole; - } - - /** - * @param session switch session context - * @param role controller openflow role - * @param generationId generate id for role negotiation - * @return input builder - */ - public static RoleRequestInputBuilder createRoleRequestInput( - final SessionContext session, OfpRole role, BigInteger generationId) { - - ControllerRole ofJavaRole = RoleUtil.toOFJavaRole(role); - - return new RoleRequestInputBuilder() - .setGenerationId(generationId) - .setRole(ofJavaRole) - .setVersion(session.getFeatures().getVersion()) - .setXid(session.getNextXid()); - } - - /** - * @param sessionContext switch session context - * @param ofpRole controller openflow role - * @param generationId generate id for role negotiation - * @return roleRequest future result - */ - public static Future> sendRoleChangeRequest(SessionContext sessionContext, OfpRole ofpRole, BigInteger generationId) { - RoleRequestInputBuilder ruleRequestInputBld = RoleUtil.createRoleRequestInput(sessionContext, ofpRole, generationId); - Future> roleReply = sessionContext.getPrimaryConductor().getConnectionAdapter() - .roleRequest(ruleRequestInputBld.build()); - return roleReply; - } - - /** - * @param sessionContext switch session context - * @return generationId from future RpcResult - */ - public static Future readGenerationIdFromDevice(SessionContext sessionContext) { - Future> roleReply = sendRoleChangeRequest(sessionContext, OfpRole.NOCHANGE, BigInteger.ZERO); - final SettableFuture result = SettableFuture.create(); - - Futures.addCallback(JdkFutureAdapters.listenInPoolThread(roleReply), new FutureCallback>() { - @Override - public void onSuccess(RpcResult input) { - if(input != null && input.getResult() != null) { - result.set(input.getResult().getGenerationId()); - } - } - @Override - public void onFailure(Throwable t) { - //TODO - } - }); - return result; - } - - /** - * @param generationId generate id for role negotiation - * @return next (incremented value) - */ - public static BigInteger getNextGenerationId(BigInteger generationId) { - BigInteger nextGenerationId = null; - if (generationId.compareTo(OFRoleManager.MAX_GENERATION_ID) < 0) { - nextGenerationId = generationId.add(BigInteger.ONE); - } else { - nextGenerationId = BigInteger.ZERO; - } - - return nextGenerationId; - } - - /** - * @param rolePushResult result of role push request - * @return future which throws {@link RolePushException} - */ - public static CheckedFuture makeCheckedRuleRequestFxResult( - ListenableFuture rolePushResult) { - return Futures.makeChecked( - rolePushResult, exceptionFunction - ); - } -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/RpcInputOutputTuple.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/RpcInputOutputTuple.java deleted file mode 100644 index 36f4652011..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/RpcInputOutputTuple.java +++ /dev/null @@ -1,42 +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.openflow.md.util; - -/** - * @param rpc input value type - * @param rpc output value type - */ -public class RpcInputOutputTuple { - - private IN input; - private OUT output; - - - /** - * @param input input - * @param output output - */ - public RpcInputOutputTuple(IN input, OUT output) { - this.input = input; - this.output = output; - } - - /** - * @return the input - */ - public IN getInput() { - return input; - } - /** - * @return the output - */ - public OUT getOutput() { - return output; - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/RpcResultUtil.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/RpcResultUtil.java deleted file mode 100644 index ac4305e83d..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/RpcResultUtil.java +++ /dev/null @@ -1,53 +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.openflow.md.util; - -import com.google.common.util.concurrent.SettableFuture; -import java.util.ArrayList; -import java.util.List; -import org.opendaylight.openflowplugin.api.ConnectionException; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService; -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; - -/** - * - */ -public final class RpcResultUtil { - - private RpcResultUtil() { - throw new UnsupportedOperationException("RpcResultUtil is not expected to be instantiated."); - } - - /** - * @param e connection exception - * @param rpc result return type - * @return error wrapped inside {@link RpcResult} which is wrapped inside future - */ - public static SettableFuture> getRpcErrorFuture(ConnectionException e) { - List rpcErrorList = wrapConnectionErrorIntoRpcErrors(e); - SettableFuture> futureWithError = SettableFuture.create(); - futureWithError.set(RpcResultBuilder.failed().withRpcErrors(rpcErrorList).build()); - return futureWithError; - } - - private static List wrapConnectionErrorIntoRpcErrors(ConnectionException e) { - List rpcErrorList = new ArrayList<>(); - rpcErrorList.add(RpcResultBuilder.newError( - RpcError.ErrorType.TRANSPORT, - OFConstants.ERROR_TAG_TIMEOUT, - e.getMessage(), - OFConstants.APPLICATION_TAG, - IMessageDispatchService.CONNECTION_ERROR_MESSAGE, - e.getCause())); - return rpcErrorList; - } - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/TaskUtil.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/TaskUtil.java deleted file mode 100644 index 5ec05a1393..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/openflow/md/util/TaskUtil.java +++ /dev/null @@ -1,47 +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.openflow.md.util; - -import com.google.common.util.concurrent.JdkFutureAdapters; -import com.google.common.util.concurrent.ListenableFuture; -import java.util.concurrent.Future; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.MessageFactory; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput; -import org.opendaylight.yangtools.yang.common.RpcResult; - -/** - * - */ -public final class TaskUtil { - - private TaskUtil() { - throw new AssertionError("TaskUtil is not expected to be instantiated."); - } - - /** - * @param session switch session context - * @param cookie connection distinguisher cookie value - * @param messageService message dispatch service instance - * @return barrier response - */ - public static RpcInputOutputTuple>> sendBarrier(SessionContext session, - SwitchConnectionDistinguisher cookie, IMessageDispatchService messageService) { - BarrierInput barrierInput = MessageFactory.createBarrier( - session.getFeatures().getVersion(), session.getNextXid()); - Future> barrierResult = messageService.barrier(barrierInput, cookie); - ListenableFuture> output = JdkFutureAdapters.listenInPoolThread(barrierResult); - - return new RpcInputOutputTuple<>(barrierInput, output); - } - - -} diff --git a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/statistics/MessageSpyCounterImpl.java b/openflowplugin/src/main/java/org/opendaylight/openflowplugin/statistics/MessageSpyCounterImpl.java deleted file mode 100644 index 1ff698dd87..0000000000 --- a/openflowplugin/src/main/java/org/opendaylight/openflowplugin/statistics/MessageSpyCounterImpl.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.statistics; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicLongFieldUpdater; - -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageObservatory; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * message counter (by type) - */ -public class MessageSpyCounterImpl implements MessageObservatory { - - private static final Logger LOG = LoggerFactory.getLogger(MessageSpyCounterImpl.class); - - private static final class MessageCounters { - private static final AtomicLongFieldUpdater UPDATER = AtomicLongFieldUpdater.newUpdater(MessageCounters.class, "current"); - private volatile long current; - private long cumulative; - - public synchronized long accumulate() { - final long inc = UPDATER.getAndSet(this, 0); - cumulative += inc; - return inc; - } - - public synchronized long getCumulative() { - return cumulative; - } - - public long increment() { - return UPDATER.incrementAndGet(this); - } - } - - private final ConcurrentMap, MessageCounters>> inputStats = new ConcurrentHashMap<>(); - - @Override - public void spyIn(final DataContainer message) { - getCounters(message, StatisticsGroup.FROM_SWITCH_TRANSLATE_IN_SUCCESS).increment(); - } - - @Override - public void spyOut(final DataContainer message) { - getCounters(message, StatisticsGroup.FROM_SWITCH_TRANSLATE_OUT_SUCCESS).increment(); - } - - @Override - public void spyMessage(final DataContainer message, final StatisticsGroup statGroup) { - getCounters(message, statGroup).increment(); - } - - /** - * @param message - * @param statGroup TODO - * @return - */ - private MessageCounters getCounters(final DataContainer message, final StatisticsGroup statGroup) { - Class msgType = message.getImplementedInterface(); - ConcurrentMap, MessageCounters> groupData = getOrCreateGroupData(statGroup); - MessageCounters counters = getOrCreateCountersPair(msgType, groupData); - return counters; - } - - private static MessageCounters getOrCreateCountersPair(final Class msgType, final ConcurrentMap,MessageCounters> groupData) { - final MessageCounters lookup = groupData.get(msgType); - if (lookup != null) { - return lookup; - } - - final MessageCounters newCounters = new MessageCounters(); - final MessageCounters check = groupData.putIfAbsent(msgType, newCounters); - return check == null ? newCounters : check; - - } - - private ConcurrentMap, MessageCounters> getOrCreateGroupData(final StatisticsGroup statGroup) { - final ConcurrentMap, MessageCounters> lookup = inputStats.get(statGroup); - if (lookup != null) { - return lookup; - } - - final ConcurrentMap, MessageCounters> newmap = new ConcurrentHashMap<>(); - final ConcurrentMap, MessageCounters> check = inputStats.putIfAbsent(statGroup, newmap); - - return check == null ? newmap : check; - } - - @Override - public void run() { - // log current counters and cleans it - if (LOG.isDebugEnabled()) { - for (String counterItem : dumpMessageCounts()) { - LOG.debug(counterItem); - } - } - } - - @Override - public List dumpMessageCounts() { - List dump = new ArrayList<>(); - - for (StatisticsGroup statGroup : StatisticsGroup.values()) { - Map, MessageCounters> groupData = inputStats.get(statGroup); - if (groupData != null) { - for (Entry, MessageCounters> statEntry : groupData.entrySet()) { - long amountPerInterval = statEntry.getValue().accumulate(); - long cumulativeAmount = statEntry.getValue().getCumulative(); - dump.add(String.format("%s: MSG[%s] -> +%d | %d", - statGroup, - statEntry.getKey().getSimpleName(), - amountPerInterval, cumulativeAmount)); - } - } else { - dump.add(String.format("%s: no activity detected", statGroup)); - } - } - return dump; - } -} diff --git a/openflowplugin/src/main/yang/openflow-plugin-cfg-impl.yang b/openflowplugin/src/main/yang/openflow-plugin-cfg-impl.yang deleted file mode 100644 index 9e8f545a63..0000000000 --- a/openflowplugin/src/main/yang/openflow-plugin-cfg-impl.yang +++ /dev/null @@ -1,28 +0,0 @@ -module openflow-provider-impl { - yang-version 1; - namespace "urn:opendaylight:params:xml:ns:yang:openflow:common:config:impl"; - prefix "ofplugin-cfg-impl"; - - description - "openflow-plugin-custom-config-impl"; - - revision "2014-03-26" { - description - "Initial revision"; - } - - // role of OFPlugin instance - typedef ofp-role { - type enumeration { - enum NOCHANGE { - description "no change to role"; - } - enum BECOMEMASTER { - description "promote current role to MASTER"; - } - enum BECOMESLAVE { - description "demote current role to SLAVE"; - } - } - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/ConnectionConductorImplTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/ConnectionConductorImplTest.java deleted file mode 100644 index 8eb350f358..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/ConnectionConductorImplTest.java +++ /dev/null @@ -1,722 +0,0 @@ -/** - * Copyright (c) 2013, 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.openflow.md.core; - -import static org.junit.Assert.assertNotNull; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Stack; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.connection.HandshakeContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.openflowplugin.openflow.md.core.plan.ConnectionAdapterStackImpl; -import org.opendaylight.openflowplugin.openflow.md.core.plan.EventFactory; -import org.opendaylight.openflowplugin.openflow.md.core.plan.SwitchTestEvent; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.openflowplugin.openflow.md.queue.QueueProcessorLightImpl; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeaturesV10; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatus; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessageBuilder; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(MockitoJUnitRunner.class) -public class ConnectionConductorImplTest { - - protected static final Logger LOG = LoggerFactory - .getLogger(ConnectionConductorImplTest.class); - - /** - * in [ms] - */ - private final int maxProcessingTimeout = 500; - - protected ConnectionAdapterStackImpl adapter; - private ConnectionConductorImpl connectionConductor; - private MDController controller; - private Stack eventPlan; - - private Thread libSimulation; - private final ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor( - 8); - - protected QueueProcessorLightImpl queueProcessor; - - private PopListenerCountingImpl popListener; - - private int experimenterMessageCounter; - private int packetinMessageCounter; - private int flowremovedMessageCounter; - private int portstatusAddMessageCounter; - private int portstatusDeleteMessageCounter; - private int portstatusModifyMessageCounter; - private int errorMessageCounter; - - @Mock - private ErrorHandlerSimpleImpl errorHandler; - - private final int expectedErrors = 0; - @Mock - private MessageSpy messageSpy; - @Mock - HandshakeContext handshakeContext; - private ErrorMessageService objErms; - - public void incrExperimenterMessageCounter() { - this.experimenterMessageCounter++; - } - - public void incrPacketinMessageCounter() { - this.packetinMessageCounter++; - } - - public void incrFlowremovedMessageCounter() { - this.flowremovedMessageCounter++; - } - - public void incrPortstatusAddMessageCounter() { - this.portstatusAddMessageCounter++; - } - - public void incrPortstatusDeleteMessageCounter() { - this.portstatusDeleteMessageCounter++; - } - - public void incrPortstatusModifyMessageCounter() { - this.portstatusModifyMessageCounter++; - } - - public void incrErrorMessageCounter() { - this.errorMessageCounter++; - } - - @Test - /** - * Test for ConnectionConductorFactory#createConductor - */ - public void testCreateConductor() { - ConnectionConductor connectionConductor = ConnectionConductorFactory.createConductor(adapter, queueProcessor); - assertNotNull(connectionConductor); - } - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - adapter = new ConnectionAdapterStackImpl(); - - popListener = new PopListenerCountingImpl<>(); - - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - controller = new MDController(convertorManager); - controller.init(); - controller.getMessageTranslators().putAll(assembleTranslatorMapping()); - - queueProcessor = new QueueProcessorLightImpl(); - queueProcessor.setMessageSpy(messageSpy); - queueProcessor.setPopListenersMapping(assemblePopListenerMapping()); - queueProcessor.setTranslatorMapping(controller.getMessageTranslators()); - queueProcessor.init(); - - connectionConductor = new ConnectionConductorImpl(adapter); - connectionConductor.setQueueProcessor(queueProcessor); - connectionConductor.setErrorHandler(errorHandler); - connectionConductor.init(); - connectionConductor.setHandshakeContext(handshakeContext); - eventPlan = new Stack<>(); - adapter.setEventPlan(eventPlan); - adapter.setProceedTimeout(5000L); - adapter.checkListeners(); - } - - /** - * @return - */ - private Map, Collection>> assemblePopListenerMapping() { - Map, Collection>> mapping = new HashMap<>(); - Collection> popListenerBag = new ArrayList<>(); - popListenerBag.add(popListener); - //TODO: add testing registered types - mapping.put(DataObject.class, popListenerBag); - return mapping; - } - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - if (libSimulation != null) { - libSimulation.join(); - } - queueProcessor.shutdown(); - connectionConductor.getHsPool().shutdown(); - - for (Exception problem : adapter.getOccuredExceptions()) { - LOG.error("during simulation on adapter side: " - + problem.getMessage()); - } - Assert.assertEquals(0, adapter.getOccuredExceptions().size()); - adapter = null; - if (LOG.isDebugEnabled()) { - if (eventPlan.size() > 0) { - LOG.debug("eventPlan size: " + eventPlan.size()); - for (SwitchTestEvent event : eventPlan) { - LOG.debug(" # EVENT:: " + event); - } - } - } - Assert.assertTrue("plan is not finished", eventPlan.isEmpty()); - eventPlan = null; - controller = null; - - // logging errors if occurred - ArgumentCaptor errorCaptor = ArgumentCaptor.forClass(Throwable.class); - Mockito.verify(errorHandler, Mockito.atMost(1)).handleException( - errorCaptor.capture(), Matchers.any(SessionContext.class)); - for (Throwable problem : errorCaptor.getAllValues()) { - LOG.warn(problem.getMessage(), problem); - } - - Mockito.verify(errorHandler, Mockito.times(expectedErrors)).handleException( - Matchers.any(Throwable.class), Matchers.any(SessionContext.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onEchoRequestMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage)} - * . - * - * @throws Exception - */ - @Test - public void testOnEchoRequestMessage() throws Exception { - simulateV13PostHandshakeState(connectionConductor); - - eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L, - EventFactory.DEFAULT_VERSION, new EchoRequestMessageBuilder())); - eventPlan.add(0, - EventFactory.createDefaultWaitForRpcEvent(42, "echoReply")); - executeNow(); - } - - /** - * Test of handshake, covering version negotiation and features. - * Switch delivers first helloMessage with default version. - * - * @throws Exception - */ - @Test - public void testHandshake1() throws Exception { - eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L, - EventFactory.DEFAULT_VERSION, new HelloMessageBuilder())); - eventPlan.add(0, EventFactory.createDefaultWaitForAllEvent( - EventFactory.createDefaultWaitForRpcEvent(43, "helloReply"), - EventFactory.createDefaultWaitForRpcEvent(44, "getFeatures"))); - eventPlan.add(0, EventFactory.createDefaultRpcResponseEvent(44, - EventFactory.DEFAULT_VERSION, getFeatureResponseMsg())); - - int i = 1; - executeNow(); - - Assert.assertEquals(ConnectionConductor.CONDUCTOR_STATE.WORKING, - connectionConductor.getConductorState()); - Assert.assertEquals((short) 0x04, connectionConductor.getVersion() - .shortValue()); - } - - /** - * Test of handshake, covering version negotiation and features. - * Controller sends first helloMessage with default version - * - * @throws Exception - */ - @Test - public void testHandshake1SwitchStarts() throws Exception { - eventPlan.add(0, EventFactory.createConnectionReadyCallback(connectionConductor)); - eventPlan.add(0, EventFactory.createDefaultWaitForRpcEvent(21, "helloReply")); - eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L, - EventFactory.DEFAULT_VERSION, new HelloMessageBuilder())); - eventPlan.add(0, EventFactory.createDefaultWaitForRpcEvent(43, "getFeatures")); - eventPlan.add(0, EventFactory.createDefaultRpcResponseEvent(43, - EventFactory.DEFAULT_VERSION, getFeatureResponseMsg())); - - executeNow(); - - Assert.assertEquals(ConnectionConductor.CONDUCTOR_STATE.WORKING, - connectionConductor.getConductorState()); - Assert.assertEquals((short) 0x04, connectionConductor.getVersion() - .shortValue()); - } - - /** - * Test of handshake, covering version negotiation and features. - * Switch delivers first helloMessage with version 0x05 - * and negotiates following versions: 0x03, 0x01 - * - * @throws Exception - */ - @Test - public void testHandshake2() throws Exception { - connectionConductor.setBitmapNegotiationEnable(false); - eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L, - (short) 0x05, new HelloMessageBuilder())); - eventPlan.add(0, - EventFactory.createDefaultWaitForRpcEvent(43, "helloReply")); - eventPlan.add(0, EventFactory.createDefaultNotificationEvent(43L, - (short) 0x03, new HelloMessageBuilder())); - eventPlan.add(0, - EventFactory.createDefaultWaitForRpcEvent(44, "helloReply")); - eventPlan.add(0, EventFactory.createDefaultNotificationEvent(44L, - (short) 0x01, new HelloMessageBuilder())); - eventPlan.add(0, - EventFactory.createDefaultWaitForRpcEvent(45, "getFeatures")); - - eventPlan.add(0, EventFactory.createDefaultRpcResponseEvent(45, - (short) 0x01, getFeatureResponseMsg())); - - executeNow(); - - Assert.assertEquals(ConnectionConductor.CONDUCTOR_STATE.WORKING, - connectionConductor.getConductorState()); - Assert.assertEquals((short) 0x01, connectionConductor.getVersion() - .shortValue()); - } - - /** - * Test of handshake, covering version negotiation and features. - * Controller sends first helloMessage with default version - * and switch negotiates following versions: 0x05, 0x03, 0x01 - * - * @throws Exception - */ - @Test - public void testHandshake2SwitchStarts() throws Exception { - connectionConductor.setBitmapNegotiationEnable(false); - eventPlan.add(0, EventFactory.createConnectionReadyCallback(connectionConductor)); - eventPlan.add(0, - EventFactory.createDefaultWaitForRpcEvent(21, "helloReply")); - eventPlan.add(0, EventFactory.createDefaultNotificationEvent(42L, - (short) 0x05, new HelloMessageBuilder())); - eventPlan.add(0, EventFactory.createDefaultNotificationEvent(43L, - (short) 0x03, new HelloMessageBuilder())); - eventPlan.add(0, - EventFactory.createDefaultWaitForRpcEvent(44, "helloReply")); - eventPlan.add(0, EventFactory.createDefaultNotificationEvent(44L, - (short) 0x01, new HelloMessageBuilder())); - eventPlan.add(0, - EventFactory.createDefaultWaitForRpcEvent(45, "getFeatures")); - - eventPlan.add(0, EventFactory.createDefaultRpcResponseEvent(45, - (short) 0x01, getFeatureResponseMsg())); - - executeNow(); - - Assert.assertEquals(ConnectionConductor.CONDUCTOR_STATE.WORKING, - connectionConductor.getConductorState()); - Assert.assertEquals((short) 0x01, connectionConductor.getVersion() - .shortValue()); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onFlowRemovedMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage)} - * . - * - * @throws InterruptedException - */ - @Test - public void testOnFlowRemovedMessage() throws InterruptedException { - FlowRemovedMessageService objFms = new FlowRemovedMessageService(); - controller.addMessageTranslator(FlowRemovedMessage.class, 4, objFms); - - simulateV13PostHandshakeState(connectionConductor); - objFms.resetLatch(2); - - // Now send Flow Removed messages - FlowRemovedMessageBuilder builder1 = new FlowRemovedMessageBuilder(); - builder1.setVersion((short) 4); - builder1.setXid(1L); - connectionConductor.onFlowRemovedMessage(builder1.build()); - LOG.debug("about to wait for popListener"); - builder1.setXid(2L); - connectionConductor.onFlowRemovedMessage(builder1.build()); - - flushMessageProcessing(); - Assert.assertTrue(objFms.await(maxProcessingTimeout, TimeUnit.MILLISECONDS)); - Assert.assertEquals(2, flowremovedMessageCounter); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onMultipartReplyMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage)} - * . - */ - @Test - public void testOnMultipartReplyMessage() { - // fail("Not yet implemented"); - // TODO:: add test - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onPacketInMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage)} - * . - * - * @throws InterruptedException - */ - @Test - public void testOnPacketInMessage() throws InterruptedException { - PacketInMessageService objPms = new PacketInMessageService(); - controller.addMessageTranslator(PacketInMessage.class, 4, objPms); - - simulateV13PostHandshakeState(connectionConductor); - - // Now send PacketIn - PacketInMessageBuilder builder1 = new PacketInMessageBuilder(); - builder1.setVersion((short) 4); - builder1.setBufferId((long) 1); - connectionConductor.onPacketInMessage(builder1.build()); - builder1.setBufferId((long) 2); - connectionConductor.onPacketInMessage(builder1.build()); - - flushMessageProcessing(); - Assert.assertTrue(objPms.await(maxProcessingTimeout, TimeUnit.MILLISECONDS)); - Assert.assertEquals(2, packetinMessageCounter); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onPortStatusMessage(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage)} - * . - * - * @throws InterruptedException - */ - @Test - public void testOnPortStatusMessage() throws InterruptedException { - PortStatusMessageService objPSms = new PortStatusMessageService(); - controller.addMessageTranslator(PortStatusMessage.class, 4, objPSms); - - simulateV13PostHandshakeState(connectionConductor); - - // Send Port Status messages - PortStatusMessageBuilder builder1 = new PortStatusMessageBuilder(); - builder1.setVersion((short) 4); - PortFeatures features = new PortFeatures(true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false); - builder1.setPortNo(90L).setReason(PortReason.OFPPRADD).setCurrentFeatures(features); - objPSms.resetLatch(3); - LOG.debug("sending port message"); - connectionConductor.onPortStatusMessage(builder1.build()); - builder1.setPortNo(90L).setReason(PortReason.OFPPRMODIFY).setCurrentFeatures(features); - connectionConductor.onPortStatusMessage(builder1.build()); - builder1.setPortNo(90L).setReason(PortReason.OFPPRDELETE).setCurrentFeatures(features); - connectionConductor.onPortStatusMessage(builder1.build()); - - flushMessageProcessing(); - Assert.assertTrue(objPSms.await(maxProcessingTimeout, TimeUnit.MILLISECONDS)); - Assert.assertEquals(1, portstatusModifyMessageCounter); - Assert.assertEquals(1, portstatusAddMessageCounter); - Assert.assertEquals(1, portstatusDeleteMessageCounter); - } - - private void flushMessageProcessing() throws InterruptedException { - // make sure that harvester sleeps deeply - Thread.sleep(maxProcessingTimeout); - // flushing messages - queueProcessor.getHarvesterHandle().ping(); - } - - /** - * @throws InterruptedException - */ - private void executeLater() throws InterruptedException { - execute(false); - } - - /** - * @throws InterruptedException - */ - private void executeNow() throws InterruptedException { - execute(true); - connectionConductor.getHsPool().shutdown(); - } - - /** - * @throws InterruptedException - */ - private void execute(final boolean join) throws InterruptedException { - libSimulation = new Thread(adapter, "junit-adapter"); - libSimulation.start(); - if (join) { - libSimulation.join(); - } - } - - private static GetFeaturesOutputBuilder getFeatureResponseMsg() { - GetFeaturesOutputBuilder getFeaturesOutputBuilder = new GetFeaturesOutputBuilder(); - getFeaturesOutputBuilder.setDatapathId(new BigInteger("102030405060")); - getFeaturesOutputBuilder.setAuxiliaryId((short) 0); - getFeaturesOutputBuilder.setBuffers(4L); - getFeaturesOutputBuilder.setReserved(0L); - getFeaturesOutputBuilder.setTables((short) 2); - getFeaturesOutputBuilder.setCapabilities(createCapabilities(84)); - - return getFeaturesOutputBuilder; - } - - /** - * @return - */ - private static Capabilities createCapabilities(final long input) { - final Boolean FLOW_STATS = (input & (1 << 0)) != 0; - final Boolean TABLE_STATS = (input & (1 << 1)) != 0; - final Boolean PORT_STATS = (input & (1 << 2)) != 0; - final Boolean GROUP_STATS = (input & (1 << 3)) != 0; - final Boolean IP_REASM = (input & (1 << 5)) != 0; - final Boolean QUEUE_STATS = (input & (1 << 6)) != 0; - final Boolean PORT_BLOCKED = (input & (1 << 8)) != 0; - Capabilities capabilities = new Capabilities(FLOW_STATS, GROUP_STATS, IP_REASM, - PORT_BLOCKED, PORT_STATS, QUEUE_STATS, TABLE_STATS); - return capabilities; - } - - public abstract class ProcessingLatchService { - private CountDownLatch processingLatch = new CountDownLatch(0); - - public void resetLatch(int passAmount) { - processingLatch = new CountDownLatch(passAmount); - } - - protected void countDown() { - processingLatch.countDown(); - } - - public boolean await(long timeout, TimeUnit unit) throws InterruptedException { - return processingLatch.await(timeout, unit); - } - } - - public class ExperimenterMessageService implements IMDMessageTranslator> { - @Override - public List translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) { - LOG.debug("Received a packet in Experimenter Service"); - ConnectionConductorImplTest.this.incrExperimenterMessageCounter(); - return null; - } - } - - public class PacketInMessageService extends ProcessingLatchService implements IMDMessageTranslator> { - @Override - public List translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) { - LOG.debug("Received a packet in PacketIn Service"); - ConnectionConductorImplTest.this.incrPacketinMessageCounter(); - countDown(); - return null; - } - } - - public class FlowRemovedMessageService extends ProcessingLatchService implements IMDMessageTranslator> { - @Override - public List translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) { - LOG.debug("Received a packet in FlowRemoved Service"); - ConnectionConductorImplTest.this.incrFlowremovedMessageCounter(); - countDown(); - return null; - } - } - - public class PortStatusMessageService extends ProcessingLatchService implements IMDMessageTranslator> { - @Override - public List translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) { - LOG.debug("Received a packet in PortStatus Service"); - if ((((PortStatusMessage) msg).getReason().equals(PortReason.OFPPRADD))) { - ConnectionConductorImplTest.this.incrPortstatusAddMessageCounter(); - } else if (((PortStatusMessage) msg).getReason().equals(PortReason.OFPPRDELETE)) { - ConnectionConductorImplTest.this.incrPortstatusDeleteMessageCounter(); - } else if (((PortStatusMessage) msg).getReason().equals(PortReason.OFPPRMODIFY)) { - ConnectionConductorImplTest.this.incrPortstatusModifyMessageCounter(); - } - countDown(); - return null; - } - } - - public class ErrorMessageService extends ProcessingLatchService implements IMDMessageTranslator> { - @Override - public List translate(final SwitchConnectionDistinguisher cookie, final SessionContext sw, final OfHeader msg) { - LOG.debug("Received a packet in Experimenter Service"); - ConnectionConductorImplTest.this.incrErrorMessageCounter(); - countDown(); - return null; - } - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#onExperimenterMessage(ExperimenterMessage)} - * . - * - * @throws InterruptedException - */ - @Test - public void testOnErrorMessage() throws InterruptedException { - simulateV13PostHandshakeState(connectionConductor); - final int messageAmount = 2; - - objErms.resetLatch(messageAmount); - ErrorMessageBuilder builder1 = new ErrorMessageBuilder(); - builder1.setVersion((short) 4); - builder1.setCode(100); - connectionConductor.onErrorMessage(builder1.build()); - builder1.setCode(200); - connectionConductor.onErrorMessage(builder1.build()); - - flushMessageProcessing(); - Assert.assertTrue(objErms.await(maxProcessingTimeout, TimeUnit.MILLISECONDS)); - Assert.assertEquals(messageAmount, errorMessageCounter); - } - - /** - * @return listener mapping for: - *
    - *
  • experimenter
  • - *
  • error
  • - *
- */ - private Map>>> assembleTranslatorMapping() { - Map>>> translatorMapping = new HashMap<>(); - TranslatorKey tKey; - - IMDMessageTranslator> objEms = new ExperimenterMessageService(); - Collection>> existingValues = new ArrayList<>(); - existingValues.add(objEms); - tKey = new TranslatorKey(4, ExperimenterMessage.class.getName()); - translatorMapping.put(tKey, existingValues); - objErms = new ErrorMessageService(); - existingValues.add(objErms); - tKey = new TranslatorKey(4, ErrorMessage.class.getName()); - translatorMapping.put(tKey, existingValues); - return translatorMapping; - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl#processPortStatusMsg(PortStatus)} - *

- * Tests for getting features from port status message by port version - *
    - *
  • features are malformed - one of them is null
  • - *
  • mismatch between port version and port features
  • - *
  • mismatch between port version and port features
  • - *
  • non-existing port version
  • - *
  • port version OF 1.0
  • - *
  • port version OF 1.3
  • - *
- */ - @Test - public void testProcessPortStatusMsg() { - simulateV13PostHandshakeState(connectionConductor); - - long portNumber = 90L; - long portNumberV10 = 91L; - PortStatusMessage msg; - - PortStatusMessageBuilder builder = new PortStatusMessageBuilder(); - PortFeatures features = new PortFeatures(true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false); - PortFeatures featuresMal = new PortFeatures(true, false, false, false, null, false, false, false, false, false, false, false, false, false, false, false); - PortFeaturesV10 featuresV10 = new PortFeaturesV10(true, false, false, false, false, false, false, false, false, false, false, false); - - //Malformed features - builder.setVersion((short) 1).setPortNo(portNumber).setReason(PortReason.OFPPRADD).setCurrentFeatures(featuresMal); - connectionConductor.processPortStatusMsg(builder.build()); - Assert.assertTrue(connectionConductor.getSessionContext().getPortsBandwidth().isEmpty()); - Assert.assertTrue(connectionConductor.getSessionContext().getPhysicalPorts().isEmpty()); - - //Version-features mismatch - builder.setCurrentFeatures(features); - connectionConductor.processPortStatusMsg(builder.build()); - Assert.assertTrue(connectionConductor.getSessionContext().getPortsBandwidth().isEmpty()); - Assert.assertTrue(connectionConductor.getSessionContext().getPhysicalPorts().isEmpty()); - - //Non existing version - builder.setVersion((short) 0); - connectionConductor.processPortStatusMsg(builder.build()); - Assert.assertTrue(connectionConductor.getSessionContext().getPortsBandwidth().isEmpty()); - Assert.assertTrue(connectionConductor.getSessionContext().getPhysicalPorts().isEmpty()); - - //Version OF 1.3 - builder.setVersion((short) 4); - msg = builder.build(); - connectionConductor.processPortStatusMsg(builder.build()); - Assert.assertTrue(connectionConductor.getSessionContext().getPortBandwidth(portNumber)); - Assert.assertEquals(connectionConductor.getSessionContext().getPhysicalPort(portNumber), msg); - - //Version OF 1.0 - builder.setVersion((short) 1).setPortNo(portNumberV10).setCurrentFeatures(null).setCurrentFeaturesV10(featuresV10); - msg = builder.build(); - connectionConductor.processPortStatusMsg(builder.build()); - Assert.assertTrue(connectionConductor.getSessionContext().getPortBandwidth(portNumberV10)); - Assert.assertEquals(connectionConductor.getSessionContext().getPhysicalPort(portNumberV10), msg); - } - - - @Test - public void testHandshakeFailOperations(){ - connectionConductor.onHandshakeFailure(); - connectionConductor.checkState(ConnectionConductor.CONDUCTOR_STATE.RIP); - } - private static void simulateV13PostHandshakeState(final ConnectionConductorImpl conductor) { - GetFeaturesOutputBuilder featureOutput = getFeatureResponseMsg(); - conductor.postHandshakeBasic(featureOutput.build(), OFConstants.OFP_VERSION_1_3); - LOG.debug("simulating post handshake event done"); - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/ErrorHandlerSimpleImplTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/ErrorHandlerSimpleImplTest.java index ce0c3f71a3..1effdb2a1a 100644 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/ErrorHandlerSimpleImplTest.java +++ b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/ErrorHandlerSimpleImplTest.java @@ -8,39 +8,22 @@ package org.opendaylight.openflowplugin.openflow.md.core; -import static org.mockito.Mockito.when; import junit.framework.TestCase; -import org.junit.Before; import org.junit.Test; -import org.mockito.Mock; import org.opendaylight.openflowplugin.api.ConnectionException; import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF; public class ErrorHandlerSimpleImplTest extends TestCase { ErrorHandler errorHandler = new ErrorHandlerSimpleImpl(); - @Mock - SessionContext sessionContext; - - @Mock - SwitchSessionKeyOF switchSessionKeyOF; - - @Before - public void setup() { - when(sessionContext.getSessionKey()).thenReturn(switchSessionKeyOF); - when(switchSessionKeyOF.getId()).thenReturn(new byte[0]); - } - @Test public void testHandleException() throws Exception { ConnectionException connectionException = new ConnectionException("Exception for testing purpose only."); - errorHandler.handleException(connectionException, sessionContext); + errorHandler.handleException(connectionException); Exception someException = new Exception("Exception for testing purpose only."); - errorHandler.handleException(someException, sessionContext); + errorHandler.handleException(someException); } } \ No newline at end of file diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/HandshakeManagerImplTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/HandshakeManagerImplTest.java index 6db520e4b0..a7193c654e 100644 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/HandshakeManagerImplTest.java +++ b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/HandshakeManagerImplTest.java @@ -23,10 +23,8 @@ import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler; import org.opendaylight.openflowplugin.api.openflow.md.core.HandshakeListener; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.HelloElementType; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; @@ -69,7 +67,7 @@ public class HandshakeManagerImplTest { @Before public void setUp() { handshakeManager = new HandshakeManagerImpl(adapter, OFConstants.OFP_VERSION_1_3, - ConnectionConductor.VERSION_ORDER); + OFConstants.VERSION_ORDER); handshakeManager.setErrorHandler(errorHandler); handshakeManager.setHandshakeListener(handshakeListener); handshakeManager.setUseVersionBitmap(false); @@ -89,13 +87,13 @@ public class HandshakeManagerImplTest { // logging errors if occurred ArgumentCaptor errorCaptor = ArgumentCaptor.forClass(Throwable.class); Mockito.verify(errorHandler, Mockito.atMost(1)).handleException( - errorCaptor.capture(), Matchers.any(SessionContext.class)); + errorCaptor.capture()); for (Throwable problem : errorCaptor.getAllValues()) { LOG.warn(problem.getMessage(), problem); } Mockito.verify(errorHandler, Mockito.times(expectedErrors)).handleException( - Matchers.any(Throwable.class), Matchers.any(SessionContext.class)); + Matchers.any(Throwable.class)); } /** diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/MDControllerTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/MDControllerTest.java deleted file mode 100644 index d871ec0fcc..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/MDControllerTest.java +++ /dev/null @@ -1,112 +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.openflow.md.core; - -import java.util.List; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketIn; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class MDControllerTest { - protected static final Logger LOG = LoggerFactory - .getLogger(ConnectionConductorImplTest.class); - - protected MDController controller; - - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - controller = new MDController(convertorManager); - controller.init(); - } - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - controller = null; - } - - @Test - public void testAddMessageListeners() { - //clean translators - controller.getMessageTranslators().clear(); - - // Empty map - int size = controller.getMessageTranslators().size(); - Assert.assertEquals(0, size); - // Add one - IMDMessageTranslator> objDps = new DataPacketService() ; - controller.addMessageTranslator(PacketIn.class, 4, objDps); - size = controller.getMessageTranslators().size(); - Assert.assertEquals(1, size); - // Remove one - controller.removeMessageTranslator(PacketIn.class, 4, objDps); - size = controller.getMessageTranslators().size(); - Assert.assertEquals(0, size); - // Add two and remove One - IMDMessageTranslator objFps = new FlowProgrammerService(); - controller.addMessageTranslator(PacketIn.class, 4, objDps); - controller.addMessageTranslator(FlowRemoved.class, 4, objFps); - controller.removeMessageTranslator(FlowRemoved.class, 4, objFps); - size = controller.getMessageTranslators().size(); - Assert.assertEquals(1, size); - // Add one more and remove both - controller.addMessageTranslator(FlowRemoved.class, 4, objFps); - controller.removeMessageTranslator(PacketIn.class, 4, objDps); - controller.removeMessageTranslator(FlowRemoved.class, 4, objFps); - size = controller.getMessageTranslators().size(); - Assert.assertEquals(0, size); - // Add multiple listeners to messageTypes - controller.addMessageTranslator(PacketIn.class, 4, objDps); - controller.addMessageTranslator(PacketIn.class, 4, objFps); // Duplicate value entry - controller.addMessageTranslator(FlowRemoved.class, 4, objFps); - size = controller.getMessageTranslators().size(); - Assert.assertEquals(2, size); - // Remove one of the multiple listener, still size remains same - controller.removeMessageTranslator(PacketIn.class, 4, objFps); - size = controller.getMessageTranslators().size(); - Assert.assertEquals(2, size); - } - - private class DataPacketService implements IMDMessageTranslator> { - @Override - public List translate(SwitchConnectionDistinguisher cookie, SessionContext sw, OfHeader msg) { - LOG.debug("Received a packet in DataPacket Service"); - return null; - } - } - - private class FlowProgrammerService implements IMDMessageTranslator { - @Override - public DataObject translate(SwitchConnectionDistinguisher cookie, SessionContext sw, OfHeader msg) { - LOG.debug("Received a packet in Flow Programmer Service"); - return null; - } - } - - - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/MessageFactoryTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/MessageFactoryTest.java index 773b161deb..f4dfa041b6 100644 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/MessageFactoryTest.java +++ b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/MessageFactoryTest.java @@ -10,7 +10,7 @@ package org.opendaylight.openflowplugin.openflow.md.core; import org.junit.Assert; import org.junit.Test; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; +import org.opendaylight.openflowplugin.api.OFConstants; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.HelloElementType; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.hello.Elements; @@ -21,7 +21,7 @@ public class MessageFactoryTest { public void testCreateHelloInputWoElements() { short highestVersion = (short) 0x04; long xid = 42L; - + HelloInput helloMsg = MessageFactory.createHelloInput(highestVersion, xid); Assert.assertEquals(highestVersion, helloMsg.getVersion().shortValue()); Assert.assertEquals(xid, helloMsg.getXid().longValue()); @@ -34,9 +34,8 @@ public class MessageFactoryTest { long xid = 42L; Boolean[] expectedVersionBitmap = new Boolean[]{ false, true, false, false, true}; - - HelloInput helloMsg = MessageFactory.createHelloInput(highestVersion, xid, - ConnectionConductor.VERSION_ORDER); + + HelloInput helloMsg = MessageFactory.createHelloInput(highestVersion, xid, OFConstants.VERSION_ORDER); Assert.assertEquals(highestVersion, helloMsg.getVersion().shortValue()); Assert.assertEquals(xid, helloMsg.getXid().longValue()); Assert.assertEquals(1, helloMsg.getElements().size()); diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/NotificationQueueWrapperTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/NotificationQueueWrapperTest.java deleted file mode 100644 index ffe669775f..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/NotificationQueueWrapperTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessageBuilder; - -/** - * @author michal.polkorab - * - */ -public class NotificationQueueWrapperTest { - - /** - * Test NotificationQueueWrapper creation - */ - @Test(expected=IllegalArgumentException.class) - public void test() { - NotificationQueueWrapper queueWrapper = new NotificationQueueWrapper(null, null); - } - - /** - * Test NotificationQueueWrapper creation - */ - @Test(expected=IllegalArgumentException.class) - public void test2() { - EchoRequestMessageBuilder echoBuilder = new EchoRequestMessageBuilder(); - NotificationQueueWrapper queueWrapper = new NotificationQueueWrapper(echoBuilder.build(), null); - } - - /** - * Test NotificationQueueWrapper creation - */ - @Test - public void test3() { - EchoRequestMessageBuilder echoBuilder = new EchoRequestMessageBuilder(); - NotificationQueueWrapper queueWrapper = new NotificationQueueWrapper(echoBuilder.build(), - (short) EncodeConstants.OF13_VERSION_ID); - - Assert.assertEquals("Wrong implemented interface", "org.opendaylight.openflowplugin.api.openflow.md" - + ".core.NotificationQueueWrapper", queueWrapper.getImplementedInterface().getName()); - Assert.assertEquals("Wrong version", 4, queueWrapper.getVersion().intValue()); - Assert.assertEquals("Wrong notification", "org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol" - + ".rev130731.EchoRequestMessage", queueWrapper.getNotification().getImplementedInterface().getName()); - Assert.assertEquals("Wrong xid", -1, queueWrapper.getXid().longValue()); - queueWrapper.setXid(12345L); - Assert.assertEquals("Wrong xid", 12345, queueWrapper.getXid().intValue()); - } -} \ No newline at end of file diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/PopListenerCountingImpl.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/PopListenerCountingImpl.java deleted file mode 100644 index 95e5244070..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/PopListenerCountingImpl.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core; - -import org.opendaylight.openflowplugin.api.openflow.md.queue.PopListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author mirehak - * @param resulting type - * - */ -public class PopListenerCountingImpl implements PopListener { - - private static final Logger LOG = LoggerFactory - .getLogger(PopListenerCountingImpl.class); - private int count = 0; - - @Override - public synchronized void onPop(T processedMessage) { - LOG.debug("message popped: {}", processedMessage); - count += 1; - notify(); - } - - /** - * @return the count - */ - public int getCount() { - return count; - } - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/SwitchConnectionHandlerImplTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/SwitchConnectionHandlerImplTest.java deleted file mode 100644 index 8d9b8a37f6..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/SwitchConnectionHandlerImplTest.java +++ /dev/null @@ -1,47 +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.openflow.md.core; - -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.yangtools.yang.binding.DataContainer; - -/** - * Created by Martin Bobak mbobak@cisco.com on 8/29/14. - */ -@RunWith(MockitoJUnitRunner.class) -public class SwitchConnectionHandlerImplTest { - - - @Mock - private ErrorHandler errorHandler; - @Mock - private MessageSpy messageSpy; - @Mock - private ConnectionAdapter connectionAdapter; - - /** - * Test method for SwitchConnectionHandlerImpl initialization. - */ - @Test - public void basicInitializationTest() { - SwitchConnectionHandlerImpl switchConnectionHandler = new SwitchConnectionHandlerImpl(); - assertNotNull(switchConnectionHandler); - switchConnectionHandler.setMessageSpy(messageSpy); - switchConnectionHandler.setErrorHandler(errorHandler); - } - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/ConnectionAdapterStackImpl.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/ConnectionAdapterStackImpl.java deleted file mode 100644 index 8ca9178b33..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/ConnectionAdapterStackImpl.java +++ /dev/null @@ -1,670 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -import com.google.common.base.Joiner; -import com.google.common.collect.Lists; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.SettableFuture; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Stack; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import org.opendaylight.controller.sal.common.util.RpcErrors; -import org.opendaylight.controller.sal.common.util.Rpcs; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener; -import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandler; -import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration; -import org.opendaylight.openflowjava.protocol.api.extensibility.AlienMessageListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoRequestMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetAsyncInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEvent; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.DisconnectEventBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener; -import org.opendaylight.yangtools.yang.binding.Notification; -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity; -import org.opendaylight.yangtools.yang.common.RpcError.ErrorType; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author mirehak - */ -public class ConnectionAdapterStackImpl implements ConnectionAdapter, Runnable { - - /** notify and rpc-response thread start default delay in [ms] */ - public static final int JOB_DELAY = 50; - - protected static final Logger LOG = LoggerFactory - .getLogger(ConnectionAdapterStackImpl.class); - - protected Stack eventPlan; - protected OpenflowProtocolListener ofListener; - protected SystemNotificationsListener systemListener; - - protected Map> rpcResults = new HashMap<>(); - protected boolean planTouched = false; - - private long proceedTimeout; - - protected List occuredExceptions = new ArrayList<>(); - - private ConnectionReadyListener connectionReadyListener; - - private int planItemCounter; - - private boolean autoRead = true; - private final ExecutorService pool; - private boolean packetInFiltering; - - - /** - * default ctor - */ - public ConnectionAdapterStackImpl() { - pool = Executors.newSingleThreadExecutor(); - } - - @Override - public synchronized Future> barrier( - final BarrierInput arg0) { - checkRpcAndNext(arg0, "barrier"); - SettableFuture> result = createAndRegisterRpcResult(arg0); - return result; - } - - @Override - public synchronized Future> echo(final EchoInput arg0) { - checkRpcAndNext(arg0, "echo"); - Future> result = createAndRegisterRpcResult(arg0); - return result; - } - - @Override - public Future> echoReply(final EchoReplyInput arg0) { - checkRpcAndNext(arg0, "echoReply"); - ListenableFuture> result = createOneWayRpcResult(); - return result; - } - - @Override - public Future> experimenter(final ExperimenterInput arg0) { - checkRpcAndNext(arg0, "experimenter"); - ListenableFuture> result = createOneWayRpcResult(); - return result; - } - - @Override - public Future> flowMod(final FlowModInput arg0) { - checkRpcAndNext(arg0, "flowMod"); - ListenableFuture> result = createOneWayRpcResult(); - return result; - } - - @Override - public synchronized Future> getAsync( - final GetAsyncInput arg0) { - checkRpcAndNext(arg0, "echo"); - Future> result = createAndRegisterRpcResult(arg0); - return result; - } - - @Override - public synchronized Future> getConfig( - final GetConfigInput arg0) { - checkRpcAndNext(arg0, "echo"); - Future> result = createAndRegisterRpcResult(arg0); - return result; - } - - @Override - public synchronized Future> getFeatures( - final GetFeaturesInput arg0) { - checkRpcAndNext(arg0, "getFeatures"); - Future> result = createAndRegisterRpcResult(arg0); - return result; - } - - @Override - public synchronized Future> getQueueConfig( - final GetQueueConfigInput arg0) { - checkRpcAndNext(arg0, "echo"); - Future> result = createAndRegisterRpcResult(arg0); - return result; - } - - @Override - public Future> groupMod(final GroupModInput arg0) { - checkRpcAndNext(arg0, "groupMod"); - ListenableFuture> result = createOneWayRpcResult(); - return result; - } - - @Override - public Future> hello(final HelloInput arg0) { - checkRpcAndNext(arg0, "helloReply"); - ListenableFuture> result = createOneWayRpcResult(); - return result; - } - - @Override - public Future> meterMod(final MeterModInput arg0) { - checkRpcAndNext(arg0, "meterMod"); - ListenableFuture> result = createOneWayRpcResult(); - return result; - } - - @Override - public Future> packetOut(final PacketOutInput arg0) { - checkRpcAndNext(arg0, "packetOut"); - ListenableFuture> result = createOneWayRpcResult(); - return result; - } - - @Override - public Future> portMod(final PortModInput arg0) { - checkRpcAndNext(arg0, "portMod"); - ListenableFuture> result = createOneWayRpcResult(); - return result; - } - - @Override - public synchronized Future> roleRequest( - final RoleRequestInput arg0) { - checkRpcAndNext(arg0, "echo"); - Future> result = createAndRegisterRpcResult(arg0); - return result; - } - - @Override - public Future> setAsync(final SetAsyncInput arg0) { - checkRpcAndNext(arg0, "setAsync"); - ListenableFuture> result = createOneWayRpcResult(); - return result; - } - - @Override - public Future> setConfig(final SetConfigInput arg0) { - checkRpcAndNext(arg0, "setConfig"); - ListenableFuture> result = createOneWayRpcResult(); - return result; - } - - @Override - public Future> tableMod(final TableModInput arg0) { - checkRpcAndNext(arg0, "tableMod"); - ListenableFuture> result = createOneWayRpcResult(); - return result; - } - - @Override - public Future disconnect() { - LOG.debug("adapter is told to disconnect"); - DisconnectEventBuilder disconnectEventBuilder = new DisconnectEventBuilder(); - disconnectEventBuilder.setInfo("disconnected by plugin"); - systemListener.onDisconnectEvent(disconnectEventBuilder.build()); - return null; - } - - @Override - public boolean isAlive() { - // TODO make dynamic - return true; - } - - @Override - public void setMessageListener(final OpenflowProtocolListener ofListener) { - this.ofListener = ofListener; - } - - @Override - public void checkListeners() { - if (ofListener == null || systemListener == null - || connectionReadyListener == null) { - occuredExceptions - .add(new IllegalStateException("missing listeners")); - } - } - - @Override - public void setSystemListener(final SystemNotificationsListener systemListener) { - this.systemListener = systemListener; - } - - @Override - public void setAlienMessageListener(final AlienMessageListener alienMessageListener) { - - } - - /** - * @param rpcInput - * rpc call parameter - * @param rpcName - * rpc yang name - */ - private boolean checkRpc(final OfHeader rpcInput, final String rpcName) { - String msg = null; - boolean finished = true; - - if (eventPlan.isEmpty()) { - throw new IllegalStateException("eventPlan already depleted"); - } - - LOG.debug("checking rpc: name={}, ver={}, xid={}", rpcName, - rpcInput.getVersion(), rpcInput.getXid()); - if (!(eventPlan.peek() instanceof SwitchTestWaitForRpcEvent) - && !(eventPlan.peek() instanceof SwitchTestWaitForAllEvent)) { - if (eventPlan.peek() instanceof SwitchTestNotificationEvent) { - SwitchTestNotificationEvent notifEvent = (SwitchTestNotificationEvent) (eventPlan - .peek()); - msg = "expected [notification: " - + notifEvent.getPlannedNotification() + "], got [" - + rpcInput.getClass().getSimpleName() + "]"; - } else if (eventPlan.peek() instanceof SwitchTestRcpResponseEvent) { - SwitchTestRcpResponseEvent rpcEvent = (SwitchTestRcpResponseEvent) (eventPlan - .peek()); - msg = "expected [rpc: " + rpcEvent.getPlannedRpcResponse() - + "], got [" + rpcInput.getClass().getSimpleName() - + "]"; - } - } else { - if (eventPlan.peek() instanceof SwitchTestWaitForAllEvent) { - SwitchTestWaitForAllEvent switchTestWaitForAll = (SwitchTestWaitForAllEvent) eventPlan - .peek(); - Set eventBag = switchTestWaitForAll - .getWaitEventBag(); - List msgLot = new ArrayList<>(); - - if (eventBag == null || eventBag.isEmpty()) { - msg = "no wait events in bag"; - } else { - finished = false; - for (SwitchTestWaitForRpcEvent switchTestWaitForRpc : eventBag) { - String msgPart = checkSingleRpcContent(rpcInput, - rpcName, switchTestWaitForRpc); - - if (msgPart != null) { - msgLot.add(msgPart); - } else { - LOG.debug("wait event matched: {}", rpcName); - eventBag.remove(switchTestWaitForRpc); - if (eventBag.isEmpty()) { - finished = true; - } - msgLot.clear(); - break; - } - } - } - - if (!msgLot.isEmpty()) { - msg = Joiner.on(" | ").join(msgLot); - } - } else if (eventPlan.peek() instanceof SwitchTestWaitForRpcEvent) { - SwitchTestWaitForRpcEvent switchTestRpcEvent = (SwitchTestWaitForRpcEvent) eventPlan - .peek(); - msg = checkSingleRpcContent(rpcInput, rpcName, - switchTestRpcEvent); - } - } - - if (msg != null) { - LOG.debug("rpc check .. FAILED: " + msg); - occuredExceptions.add(new IllegalArgumentException("step:" - + planItemCounter + " | " + msg)); - } else { - LOG.debug("rpc check .. OK"); - } - return finished; - } - - /** - * @param rpcInput - * @param rpcName - * @param switchTestWaitForRpc - * @return - */ - private static String checkSingleRpcContent(final OfHeader rpcInput, - final String rpcName, final SwitchTestWaitForRpcEvent switchTestWaitForRpc) { - String failureMsg = null; - if (!rpcName.equals(switchTestWaitForRpc.getRpcName())) { - failureMsg = "expected rpc name [" - + switchTestWaitForRpc.getRpcName() + "], got [" + rpcName - + "]"; - } else if (!rpcInput.getXid().equals(switchTestWaitForRpc.getXid())) { - failureMsg = "expected " + rpcName + ".xid [" - + switchTestWaitForRpc.getXid() + "], got [" - + rpcInput.getXid() + "]"; - } - - return failureMsg; - } - - /** - * @param rpcInput - * rpc call parameter - * @param rpcName - * rpc yang name - */ - private synchronized void checkRpcAndNext(final OfHeader rpcInput, final String rpcName) { - boolean finished = checkRpc(rpcInput, rpcName); - if (finished) { - next(); - } - } - - /** - * discard current event, execute next, if possible - */ - private void next() { - LOG.debug("<---> STEPPING TO NEXT event in plan (leaving [{}] {})", - planItemCounter, eventPlan.peek()); - eventPlan.pop(); - planItemCounter++; - planTouched = true; - try { - Thread.sleep(JOB_DELAY); - } catch (InterruptedException e) { - LOG.error(e.getMessage(), e); - } - notify(); - } - - /** - * start or continue processing plan - */ - private synchronized void proceed() { - boolean processed = false; - LOG.debug("proceeding plan item[{}]: {}", planItemCounter, - eventPlan.peek()); - if (eventPlan.peek() instanceof SwitchTestNotificationEvent) { - SwitchTestNotificationEvent notification = (SwitchTestNotificationEvent) eventPlan - .peek(); - processNotification(notification); - processed = true; - } else if (eventPlan.peek() instanceof SwitchTestRcpResponseEvent) { - SwitchTestRcpResponseEvent rpcResponse = (SwitchTestRcpResponseEvent) eventPlan - .peek(); - processRpcResponse(rpcResponse); - processed = true; - } else if (eventPlan.peek() instanceof SwitchTestCallbackEvent) { - SwitchTestCallbackEvent callbackEvent = (SwitchTestCallbackEvent) eventPlan - .peek(); - try { - callbackEvent.getCallback().call(); - } catch (Exception e) { - LOG.error(e.getMessage(), e); - occuredExceptions.add(e); - } - processed = true; - } - - if (processed) { - next(); - } else { - try { - LOG.debug("now WAITING for OF_LISTENER to act .."); - wait(proceedTimeout); - } catch (InterruptedException e) { - LOG.error(e.getMessage(), e); - } - } - } - - @Override - public void run() { - LOG.debug("|---> evenPlan STARTING .."); - planItemCounter = 0; - while (!eventPlan.isEmpty()) { - planTouched = false; - proceed(); - if (!planTouched) { - occuredExceptions - .add(new IllegalStateException( - "eventPlan STALLED, planItemCounter=" - + planItemCounter)); - break; - } - } - - try { - Thread.sleep(JOB_DELAY); - } catch (InterruptedException e) { - LOG.error(e.getMessage(), e); - } - LOG.debug("<---| eventPlan DONE"); - } - - /** - * @param notificationEvent - */ - private synchronized void processNotification( - final SwitchTestNotificationEvent notificationEvent) { - - Notification notification = notificationEvent.getPlannedNotification(); - LOG.debug("notificating OF_LISTENER: " - + notification.getClass().getSimpleName()); - - // system events - if (notification instanceof DisconnectEvent) { - systemListener.onDisconnectEvent((DisconnectEvent) notification); - } - // of notifications - else if (notification instanceof EchoRequestMessage) { - ofListener.onEchoRequestMessage((EchoRequestMessage) notification); - } else if (notification instanceof ErrorMessage) { - ofListener.onErrorMessage((ErrorMessage) notification); - } else if (notification instanceof ExperimenterMessage) { - ofListener - .onExperimenterMessage((ExperimenterMessage) notification); - } else if (notification instanceof FlowRemovedMessage) { - ofListener.onFlowRemovedMessage((FlowRemovedMessage) notification); - } else if (notification instanceof HelloMessage) { - ofListener.onHelloMessage((HelloMessage) notification); - } else if (notification instanceof MultipartReplyMessage) { - ofListener - .onMultipartReplyMessage((MultipartReplyMessage) notification); - } else if (notification instanceof PacketInMessage) { - ofListener.onPacketInMessage((PacketInMessage) notification); - } else if (notification instanceof PortStatusMessage) { - ofListener.onPortStatusMessage((PortStatusMessage) notification); - } - // default - else { - occuredExceptions.add(new IllegalStateException("step:" - + planItemCounter + " | " - + "message listening not supported for type: " - + notification.getClass())); - } - - LOG.debug("notification [" + notification.getClass().getSimpleName() - + "] .. done"); - } - - /** - * @param rpcResponse - */ - private synchronized void processRpcResponse( - final SwitchTestRcpResponseEvent rpcResponse) { - OfHeader plannedRpcResponseValue = rpcResponse.getPlannedRpcResponse(); - LOG.debug("rpc-responding to OF_LISTENER: {}", rpcResponse.getXid()); - - @SuppressWarnings("unchecked") - final SettableFuture> response = (SettableFuture>) rpcResults - .get(rpcResponse.getXid()); - - if (response != null) { - boolean successful = plannedRpcResponseValue != null; - Collection errors; - if (successful) { - errors = Collections.emptyList(); - } else { - errors = Lists.newArrayList(RpcErrors.getRpcError("unit", - "unit", "not requested", ErrorSeverity.ERROR, - "planned response to RPC.id = " + rpcResponse.getXid(), - ErrorType.RPC, new Exception( - "rpc response failed (planned behavior)"))); - } - - final RpcResult result = Rpcs.getRpcResult(successful, - plannedRpcResponseValue, errors); - setFutureViaPool(response, result); - } else { - String msg = "RpcResponse not expected: xid=" - + rpcResponse.getXid() + ", " - + plannedRpcResponseValue.getClass().getSimpleName(); - LOG.error(msg); - occuredExceptions.add(new IllegalStateException("step:" - + planItemCounter + " | " + msg)); - } - - LOG.debug("rpc [" + rpcResponse.getXid() + "] .. done"); - } - - private void setFutureViaPool(final SettableFuture> response, final RpcResult result) { - pool.execute(new Runnable() { - @Override - public void run() { - response.set(result); - } - }); - } - - /** - * @param arg0 - * rpc call content - * @return rpc future result - */ - private SettableFuture> createAndRegisterRpcResult( - final IN arg0) { - SettableFuture> result = SettableFuture.create(); - rpcResults.put(arg0.getXid(), result); - return result; - } - - /** - * @return rpc future result - */ - private static ListenableFuture> createOneWayRpcResult() { - return Futures.immediateFuture(RpcResultBuilder.success().build()); - } - - /** - * @param eventPlan - * the eventPlan to set - */ - public void setEventPlan(final Stack eventPlan) { - this.eventPlan = eventPlan; - } - - /** - * @param proceedTimeout - * max timeout for processing one planned event (in [ms]) - */ - public void setProceedTimeout(final long proceedTimeout) { - this.proceedTimeout = proceedTimeout; - } - - /** - * @return the occuredExceptions - */ - public List getOccuredExceptions() { - return occuredExceptions; - } - - @Override - public void fireConnectionReadyNotification() { - connectionReadyListener.onConnectionReady(); - } - - @Override - public void setConnectionReadyListener( - final ConnectionReadyListener connectionReadyListener) { - this.connectionReadyListener = connectionReadyListener; - } - - @Override - public Future> multipartRequest(final MultipartRequestInput arg0) { - checkRpcAndNext(arg0, "multipartRequestInput"); - ListenableFuture> result = createOneWayRpcResult(); - return result; - } - - @Override - public InetSocketAddress getRemoteAddress() { - return InetSocketAddress.createUnresolved("unittest-odl.example.org", 4242); - } - - @Override - public boolean isAutoRead() { - return autoRead; - } - - @Override - public OutboundQueueHandlerRegistration registerOutboundQueueHandler(final T t, final int i, final long l) { - return null; - } - - @Override - public void setAutoRead(final boolean autoRead) { - this.autoRead = autoRead; - } - - @Override - public void setPacketInFiltering(final boolean packetInFiltering) { - this.packetInFiltering = packetInFiltering; - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/EventFactory.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/EventFactory.java deleted file mode 100644 index 0f738e9512..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/EventFactory.java +++ /dev/null @@ -1,157 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.concurrent.Callable; - -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.Notification; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author mirehak - */ -public abstract class EventFactory { - - private static final Logger LOG = LoggerFactory - .getLogger(EventFactory.class); - - /** default protocol version */ - public static final Short DEFAULT_VERSION = 4; - - /** - * @param xid - * transaction id - * @param version - * version id - * @param builder - * message builder instance - * @return default notification event - */ - public static SwitchTestNotificationEvent createDefaultNotificationEvent( - long xid, short version, Object builder) { - SwitchTestNotificationEventImpl event = new SwitchTestNotificationEventImpl(); - Notification notification = build(setupHeader(xid, version, builder)); - event.setNotification(notification); - return event; - } - - /** - * @param xid - * transaction id - * @param version - * version id - * @param builder - * rpc response builder instance - * @return default notification event - */ - public static SwitchTestRcpResponseEvent createDefaultRpcResponseEvent( - long xid, short version, Object builder) { - SwitchTestRcpResponseEventImpl event = new SwitchTestRcpResponseEventImpl(); - OfHeader rpcResponse = build(setupHeader(xid, version, builder)); - event.setResponse(rpcResponse); - event.setXid(xid); - return event; - } - - /** - * @param setupHeader - * @return - */ - @SuppressWarnings("unchecked") - private static E build(Object builder) { - E notification = null; - try { - Class builderClazz = builder.getClass(); - notification = (E) builderClazz.getMethod("build", new Class[0]) - .invoke(builder, new Object[0]); - } catch (Exception e) { - LOG.error(e.getMessage(), e); - } - return notification; - } - - /** - * @param xid - * transaction id - * @param rpcName - * name of rpc method - * @return default notification event - */ - public static SwitchTestWaitForRpcEvent createDefaultWaitForRpcEvent( - long xid, String rpcName) { - SwitchTestWaitForRpcEventImpl event = new SwitchTestWaitForRpcEventImpl(); - event.setRpcName(rpcName); - event.setXid(xid); - return event; - } - - /** - * @param events - * @return wait for all wrapper - */ - public static SwitchTestWaitForAllEvent createDefaultWaitForAllEvent( - SwitchTestWaitForRpcEvent... events) { - SwitchTestWaitForAllEventImpl eventBag = new SwitchTestWaitForAllEventImpl(); - HashSet eventsSet = new HashSet<>(Arrays.asList(events)); - eventBag.setEventBag(eventsSet); - return eventBag; - } - - /** - * @param xid - * @param version - * @param builder - * @return original builder - */ - public static E setupHeader(long xid, short version, E builder) { - try { - Class builderClazz = builder.getClass(); - builderClazz.getMethod("setXid", Long.class).invoke(builder, xid); - builderClazz.getMethod("setVersion", Short.class).invoke(builder, - version); - } catch (Exception e) { - LOG.error(e.getMessage(), e); - } - - return builder; - } - - /** - * use {@link #DEFAULT_VERSION} - * @param xid - * @param builder - * @return original builder - */ - public static E setupHeader(long xid, E builder) { - return setupHeader(xid, DEFAULT_VERSION, builder); - } - - /** - * @param connectionConductor - * @return scenario callback - */ - public static SwitchTestCallbackEventImpl createConnectionReadyCallback( - final ConnectionReadyListener connectionConductor) { - SwitchTestCallbackEventImpl connectionReadyCallback = new SwitchTestCallbackEventImpl(); - connectionReadyCallback.setCallable(new Callable() { - @Override - public Void call() throws Exception { - connectionConductor.onConnectionReady(); - return null; - } - }); - return connectionReadyCallback; - } - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestCallbackEvent.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestCallbackEvent.java deleted file mode 100644 index 2de32f2d81..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestCallbackEvent.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -import java.util.concurrent.Callable; - -/** - * @author mirehak - */ -public interface SwitchTestCallbackEvent extends SwitchTestEvent { - - /** - * @return callback to be executed - */ - public Callable getCallback(); - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestCallbackEventImpl.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestCallbackEventImpl.java deleted file mode 100644 index ccdce23624..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestCallbackEventImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -import java.util.concurrent.Callable; - -/** - * @author mirehak - * - */ -public class SwitchTestCallbackEventImpl implements SwitchTestCallbackEvent { - - private Callable callable; - - /** - * @param callable the callable to set - */ - public void setCallable(Callable callable) { - this.callable = callable; - } - - @Override - public Callable getCallback() { - return callable; - } - - @Override - public String toString() { - String callableDesc = null; - if (callable != null) { - callableDesc = "Callable:"+System.identityHashCode(callable); - } - return "SwitchTestCallbackEventImpl [" + callableDesc + "]"; - } - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestEvent.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestEvent.java deleted file mode 100644 index 8b13a53c0e..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestEvent.java +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -/** - * @author mirehak - */ -public interface SwitchTestEvent { - // nothing, unifying iface -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestNotificationEvent.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestNotificationEvent.java deleted file mode 100644 index fc06172b5e..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestNotificationEvent.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -import org.opendaylight.yangtools.yang.binding.Notification; - -/** - * @author mirehak - */ -public interface SwitchTestNotificationEvent extends SwitchTestEvent { - - /** - * @return next switch notification/rpc response - */ - Notification getPlannedNotification(); -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestNotificationEventImpl.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestNotificationEventImpl.java deleted file mode 100644 index cea3076ae0..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestNotificationEventImpl.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.Notification; - -/** - * @author mirehak - */ -public class SwitchTestNotificationEventImpl implements - SwitchTestNotificationEvent { - - private Notification notification; - - /** - * @param notification - * the notification to set - */ - public void setNotification(Notification notification) { - this.notification = notification; - } - - @Override - public Notification getPlannedNotification() { - return notification; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("SwitchTestNotificationEventImpl [notification="); - if (notification instanceof OfHeader) { - OfHeader header = (OfHeader) notification; - sb.append("version:").append(header.getVersion()).append(';') - .append("xid:").append(header.getXid()).append(';') - .append("type:").append(header.getClass().getSimpleName()); - } else { - sb.append(notification.toString()); - } - sb.append(']'); - return sb.toString(); - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestRcpResponseEvent.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestRcpResponseEvent.java deleted file mode 100644 index d0e8531b36..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestRcpResponseEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; - -/** - * @author mirehak - */ -public interface SwitchTestRcpResponseEvent extends SwitchTestEvent { - - /** - * @return switch notification/rpc response - */ - public OfHeader getPlannedRpcResponse(); - - /** - * @return response transaction id - */ - public long getXid(); -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestRcpResponseEventImpl.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestRcpResponseEventImpl.java deleted file mode 100644 index f72cf2c0ce..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestRcpResponseEventImpl.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; - -/** - * @author mirehak - */ -public class SwitchTestRcpResponseEventImpl implements - SwitchTestRcpResponseEvent { - - private OfHeader response; - private long xid; - - /** - * @param response - * the response to set - */ - public void setResponse(OfHeader response) { - this.response = response; - } - - @Override - public OfHeader getPlannedRpcResponse() { - return response; - } - - @Override - public long getXid() { - return xid; - } - - /** - * @param xid - * the xid to set - */ - public void setXid(long xid) { - this.xid = xid; - } - - @Override - public String toString() { - return "SwitchTestRcpResponseEventImpl [response=" + response.getClass().getSimpleName() - + ", xid=" + xid + "]"; - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForAllEvent.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForAllEvent.java deleted file mode 100644 index 542406dacd..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForAllEvent.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -import java.util.Set; - -/** - * @author mirehak - */ -public interface SwitchTestWaitForAllEvent extends SwitchTestEvent { - - /** - * @return set of wait events - */ - public Set getWaitEventBag(); - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForAllEventImpl.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForAllEventImpl.java deleted file mode 100644 index 1f873b704e..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForAllEventImpl.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -/** - * @author mirehak - * - */ -public class SwitchTestWaitForAllEventImpl implements SwitchTestWaitForAllEvent { - - private Set eventBag; - - /** - * @param eventBag the eventBag to set - */ - public void setEventBag(Set eventBag) { - this.eventBag = eventBag; - } - - @Override - public Set getWaitEventBag() { - return eventBag; - } - - @Override - public String toString() { - List rpcNames = null; - if (eventBag != null) { - rpcNames = new ArrayList<>(); - for (SwitchTestWaitForRpcEvent waitEvent : eventBag) { - rpcNames.add(waitEvent.getRpcName()+"["+waitEvent.getXid()+"]"); - } - } - return "SwitchTestWaitForAllEventImpl "+rpcNames; - } - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForRpcEvent.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForRpcEvent.java deleted file mode 100644 index ebb0adaa71..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForRpcEvent.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -/** - * @author mirehak - */ -public interface SwitchTestWaitForRpcEvent extends SwitchTestEvent { - - /** - * @return expected name of RPC - */ - public String getRpcName(); - - /** - * @return expected transaction ID - */ - public long getXid(); - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForRpcEventImpl.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForRpcEventImpl.java deleted file mode 100644 index e0ccd92965..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/plan/SwitchTestWaitForRpcEventImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.plan; - -/** - * @author mirehak - */ -public class SwitchTestWaitForRpcEventImpl implements SwitchTestWaitForRpcEvent { - - private String rpcName; - private long xid; - - @Override - public String getRpcName() { - return rpcName; - } - - @Override - public long getXid() { - return xid; - } - - /** - * @param rpcName - * the rpcName to set - */ - public void setRpcName(String rpcName) { - this.rpcName = rpcName; - } - - /** - * @param xid - * the xid to set - */ - public void setXid(long xid) { - this.xid = xid; - } - - @Override - public String toString() { - return "SwitchTestWaitForRpcEventImpl [rpcName=" + rpcName + ", xid=" + xid - + "]"; - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/ConcurrentSalRegistrationManagerTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/ConcurrentSalRegistrationManagerTest.java deleted file mode 100644 index ae87f009ef..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/ConcurrentSalRegistrationManagerTest.java +++ /dev/null @@ -1,258 +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.openflow.md.core.sal; - -import com.google.common.util.concurrent.ListeningExecutorService; -import java.math.BigInteger; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF; -import org.opendaylight.openflowplugin.openflow.md.core.ThreadPoolLoggingExecutor; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder; -import org.opendaylight.yangtools.yang.binding.RpcService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Created by Martin Bobak mbobak@cisco.com on 9/22/14. - */ -@RunWith(MockitoJUnitRunner.class) -public class ConcurrentSalRegistrationManagerTest { - - - /** registration related action must end within this amount of seconds */ - private static final int REGISTRATION_ACTION_TIMEOUT = 5; - protected SalRegistrationManager registrationManager; - protected static final Logger LOG = LoggerFactory.getLogger(ConcurrentSalRegistrationManagerTest.class); - protected static final SwitchSessionKeyOF SWITCH_SESSION_KEY_OF = new SwitchSessionKeyOF(); - - private static final long THREAD_SLEEP_MILLIS = 100; - private static final String DELAYED_THREAD = "DELAYED_THREAD"; - private static final String NO_DELAY_THREAD = "NO_DELAY_THREAD"; - - private ThreadPoolCollectingExecutor taskExecutor; - - @Mock - protected SessionContext context; - @Mock - private ConnectionConductor connectionConductor; - @Mock - private ListeningExecutorService rpcPool; - @Mock - private NotificationProviderService notificationProviderService; - @Mock - private RpcProviderRegistry rpcProviderRegistry; - @Mock - private DataBroker dataBroker; - @Mock - private NotificationEnqueuer notificationEnqueuer; - @Mock - private ConnectionAdapter connectionAdapter; - - private GetFeaturesOutput features; - - /** - * prepare surrounding objects - */ - @Before - public void setUp() { - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - registrationManager = new SalRegistrationManager(convertorManager); - SWITCH_SESSION_KEY_OF.setDatapathId(BigInteger.ONE); - Mockito.when(context.getNotificationEnqueuer()).thenReturn(notificationEnqueuer); - - // features mockery - features = new GetFeaturesOutputBuilder() - .setVersion(OFConstants.OFP_VERSION_1_3) - .setDatapathId(BigInteger.valueOf(42)) - .setCapabilities(new Capabilities(true, true, true, true, true, true, true)) - .build(); - Mockito.when(context.getFeatures()).thenReturn(features); - - Mockito.when(context.getPrimaryConductor()).thenReturn(connectionConductor); - Mockito.when(context.getSessionKey()).thenReturn(SWITCH_SESSION_KEY_OF); - Mockito.when(connectionConductor.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3); - - // provider context - registration responder - Mockito.when(rpcProviderRegistry.addRoutedRpcImplementation(Matchers.>any(), Matchers.any(RpcService.class))) - .then(new Answer>() { - @Override - public RoutedRpcRegistration answer(InvocationOnMock invocation) { - if (Thread.currentThread().getName().equals(DELAYED_THREAD)) { - try { - LOG.info(String.format("Will wait for %d millis", THREAD_SLEEP_MILLIS/10)); - Thread.sleep(THREAD_SLEEP_MILLIS); - } catch (InterruptedException e) { - LOG.error("delaying of worker thread [{}] failed.", Thread.currentThread().getName(), e); - } - } - - Object[] args = invocation.getArguments(); - RoutedRpcRegistration registration = Mockito.mock(RoutedRpcRegistration.class); - Mockito.when(registration.getInstance()).thenReturn((RpcService) args[1]); - - return registration; - } - }); - - Mockito.when(connectionConductor.getConnectionAdapter()).thenReturn(connectionAdapter); - Mockito.when(connectionAdapter.getRemoteAddress()).thenReturn(new InetSocketAddress("10.1.2.3", 4242)); - - taskExecutor = new ThreadPoolCollectingExecutor( - 2, 2, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(2), "junit"); - - registrationManager.setRpcProviderRegistry(rpcProviderRegistry); - registrationManager.setDataService(dataBroker); - registrationManager.setPublishService(notificationProviderService); - registrationManager.init(); - OFSessionUtil.getSessionManager().setRpcPool(rpcPool); - } - - /** - * clean up - * @throws InterruptedException - */ - @After - public void tearDown() throws InterruptedException { - taskExecutor.shutdown(); - taskExecutor.awaitTermination(1, TimeUnit.SECONDS); - if (!taskExecutor.isTerminated()) { - taskExecutor.shutdownNow(); - } - LOG.info("All tasks have finished."); - - LOG.info("amount of scheduled threads: {}, exited threads: {}, failed threads: {}", - taskExecutor.getTaskCount(), taskExecutor.getThreadExitCounter(), taskExecutor.getFailLogbook().size()); - for (String exitStatus : taskExecutor.getFailLogbook()) { - LOG.debug(exitStatus); - } - - OFSessionUtil.releaseSessionManager(); - Assert.assertTrue("there should not be any failed threads in the pool", taskExecutor.getFailLogbook().isEmpty()); - Assert.assertTrue("there should not be any living thread in the pool", taskExecutor.getActiveCount() == 0); - } - - /** - * Test method which verifies that session could not be invalidated while in creation. - * @throws InterruptedException - * @throws TimeoutException - * @throws ExecutionException - */ - @Test - public void testConcurrentRemoveSessionContext() throws InterruptedException, ExecutionException, TimeoutException { - // run registrations - Callable delayedThread = new Callable() { - @Override - public Void call() { - LOG.info("Delayed session adding thread started."); - Thread.currentThread().setName(DELAYED_THREAD); - OFSessionUtil.getSessionManager().addSessionContext(SWITCH_SESSION_KEY_OF, context); - LOG.info("Delayed session adding thread finished."); - return null; - } - }; - - Callable noDelayThread = new Callable() { - @Override - public Void call() { - LOG.info("Session removing thread started."); - Thread.currentThread().setName(NO_DELAY_THREAD); - OFSessionUtil.getSessionManager().invalidateSessionContext(SWITCH_SESSION_KEY_OF); - LOG.info("Session removing thread finished."); - return null; - } - }; - - Future addSessionResult = taskExecutor.submit(delayedThread); - Future removeSessionResult = taskExecutor.submit(noDelayThread); - - addSessionResult.get(REGISTRATION_ACTION_TIMEOUT, TimeUnit.SECONDS); - removeSessionResult.get(REGISTRATION_ACTION_TIMEOUT, TimeUnit.SECONDS); - } - - private static class ThreadPoolCollectingExecutor extends ThreadPoolLoggingExecutor { - - private List failLogbook; - private int threadExitCounter = 0; - - /** - * @param corePoolSize - * @param maximumPoolSize - * @param keepAliveTime - * @param unit - * @param workQueue - * @param poolName - */ - public ThreadPoolCollectingExecutor(int corePoolSize, - int maximumPoolSize, long keepAliveTime, TimeUnit unit, - BlockingQueue workQueue, String poolName) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, poolName); - - failLogbook = Collections.synchronizedList(new ArrayList()); - } - - @Override - protected void afterExecute(Runnable r, Throwable t) { - super.afterExecute(r, t); - threadExitCounter ++; - - if (t != null) { - failLogbook.add("job ["+r+"] exited with throwable:" + t.getMessage()); - } - } - - /** - * @return the chronicles - */ - public List getFailLogbook() { - return failLogbook; - } - - /** - * @return the threadExitCounter - */ - public int getThreadExitCounter() { - return threadExitCounter; - } - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/ModelDrivenSwitchImplTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/ModelDrivenSwitchImplTest.java deleted file mode 100644 index 36d2e38ad4..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/ModelDrivenSwitchImplTest.java +++ /dev/null @@ -1,1172 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.sal; - -import com.google.common.base.Optional; -import com.google.common.util.concurrent.CheckedFuture; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.MoreExecutors; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; -import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowHashIdMapping; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlowBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlowBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowStatisticsFromFlowTableOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.GetFlowStatisticsFromFlowTableOutputBuilder; -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.GetFlowTablesStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -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.PortFeatures; -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.PortBuilder; -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.PortKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.queue.rev130925.QueueId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowModFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.AddGroupInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.RemoveGroupInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.UpdateGroupOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918.group.update.UpdatedGroupBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetAllGroupStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupDescriptionOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupFeaturesOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GetGroupStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.AddMeterInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.RemoveMeterInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.UpdateMeterOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918.meter.update.UpdatedMeterBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterConfigStatisticsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterConfigStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetAllMeterStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterFeaturesOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.GetMeterStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId; -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.openflow.protocol.rev130731.FlowModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.UpdatePortOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107.port.update.UpdatedPortBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetAllNodeConnectorsStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.GetNodeConnectorStatisticsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromAllPortsOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetAllQueuesStatisticsFromGivenPortOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetQueueStatisticsFromGivenPortInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.GetQueueStatisticsFromGivenPortOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.table.update.UpdatedTable; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.table.update.UpdatedTableBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableConfig; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.ApplySetfieldBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.table.features.TablePropertiesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.table.features.table.properties.TableFeatureProperties; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.table.features.table.properties.TableFeaturePropertiesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.table.features.table.properties.TableFeaturePropertiesKey; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; - -/** - * simple NPE smoke test - */ -@RunWith(MockitoJUnitRunner.class) -public class ModelDrivenSwitchImplTest { - - private ModelDrivenSwitchImpl mdSwitchOF10; - private ModelDrivenSwitchImpl mdSwitchOF13; - - @Mock - private SessionContext context; - @Mock - private ConnectionConductor conductor; - @Mock - private IMessageDispatchService messageDispatchService; - @Mock - private GetFeaturesOutput features; - @Mock - private MessageSpy messageSpy; - @Mock - private DataBroker dataBroker; - @Mock - private ReadWriteTransaction rwTx; - @Mock - private EntityOwnershipService entityOwnershipService; - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - Mockito.when(context.getPrimaryConductor()).thenReturn(conductor); - Mockito.when(context.getMessageDispatchService()).thenReturn(messageDispatchService); - Mockito.when(conductor.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_0) - .thenReturn(OFConstants.OFP_VERSION_1_3); - Mockito.when(context.getFeatures()).thenReturn(features); - Mockito.when(features.getDatapathId()).thenReturn(BigInteger.valueOf(1)); - - - OFSessionUtil.getSessionManager().setRpcPool(MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10))); - OFSessionUtil.getSessionManager().setMessageSpy(messageSpy); - OFSessionUtil.getSessionManager().setDataBroker(dataBroker); - - CheckedFuture, ReadFailedException> dummyReadFuture - = Futures.,ReadFailedException>immediateCheckedFuture(Optional.absent()); - Mockito.when(rwTx.read(Matchers.any(), Matchers.>any())).thenReturn(dummyReadFuture); - Mockito.when(dataBroker.newReadWriteTransaction()).thenReturn(rwTx); - - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - mdSwitchOF10 = new ModelDrivenSwitchImpl(null, null, context, convertorManager); - mdSwitchOF13 = new ModelDrivenSwitchImpl(null, null, context, convertorManager); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#addFlow(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testAddFlow() throws InterruptedException, ExecutionException { - UpdateFlowOutputBuilder updateFlowOutput = new UpdateFlowOutputBuilder(); - updateFlowOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success(updateFlowOutput.build()).build(); - Mockito.when( - messageDispatchService.flowMod(Matchers.any(FlowModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - AddFlowInputBuilder input = new AddFlowInputBuilder(); - input.setMatch(createMatch()); - - Mockito.when(features.getVersion()).thenReturn((short)1); - mdSwitchOF10.addFlow(input.build()).get(); - Mockito.when(features.getVersion()).thenReturn((short)4); - mdSwitchOF13.addFlow(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).flowMod( - Matchers.any(FlowModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#removeFlow(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testRemoveFlow() throws InterruptedException, ExecutionException { - UpdateFlowOutputBuilder updateFlowOutput = new UpdateFlowOutputBuilder(); - updateFlowOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success(updateFlowOutput.build()).build(); - Mockito.when( - messageDispatchService.flowMod(Matchers.any(FlowModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - RemoveFlowInputBuilder input = new RemoveFlowInputBuilder(); - input.setMatch(createMatch()); - - Mockito.when(features.getVersion()).thenReturn((short)1); - mdSwitchOF10.removeFlow(input.build()).get(); - Mockito.when(features.getVersion()).thenReturn((short)4); - mdSwitchOF13.removeFlow(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).flowMod( - Matchers.any(FlowModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl#updateFlow(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testUpdateFlow() throws InterruptedException, ExecutionException { - UpdateFlowOutputBuilder updateFlowOutput = new UpdateFlowOutputBuilder(); - updateFlowOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success(updateFlowOutput.build()).build(); - Mockito.when( - messageDispatchService.flowMod(Matchers.any(FlowModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - UpdateFlowInputBuilder input = new UpdateFlowInputBuilder(); - UpdatedFlowBuilder updatedFlow = new UpdatedFlowBuilder(); - updatedFlow.setBarrier(false); - updatedFlow.setMatch(createMatch()); - updatedFlow.setPriority(65); - updatedFlow.setFlags(new FlowModFlags(true, false, true, false, true)); - input.setUpdatedFlow(updatedFlow.build()); - OriginalFlowBuilder originalFlowBuilder = new OriginalFlowBuilder(); - originalFlowBuilder.setMatch(createMatch()); - originalFlowBuilder.setPriority(65); - originalFlowBuilder.setFlags(new FlowModFlags(true, false, true, false, true)); - input.setOriginalFlow(originalFlowBuilder.build()); - KeyedInstanceIdentifier dummyIdentifier = InstanceIdentifier.create(Nodes.class) - .child(Node.class, new NodeKey(new NodeId("openflow:1"))) - .augmentation(FlowCapableNode.class) - .child(Table.class, new TableKey((short)0)) - .child(Flow.class, new FlowKey(new FlowId("1"))); - input.setFlowRef(new FlowRef(dummyIdentifier)); - - Mockito.when(features.getVersion()).thenReturn((short)1); - mdSwitchOF10.updateFlow(input.build()).get(); - Mockito.when(features.getVersion()).thenReturn((short)4); - mdSwitchOF13.updateFlow(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).flowMod( - Matchers.any(FlowModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * addGroup(org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918. - * AddGroupInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testAddGroup() throws InterruptedException, ExecutionException { - UpdateGroupOutputBuilder updateGroupOutput = new UpdateGroupOutputBuilder(); - updateGroupOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success(updateGroupOutput.build()).build(); - Mockito.when( - messageDispatchService.groupMod(Matchers.any(GroupModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - AddGroupInputBuilder input = new AddGroupInputBuilder(); - input.setGroupType(org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes.GroupFf); - input.setGroupId(new GroupId(789L)); - - mdSwitchOF10.addGroup(input.build()).get(); - mdSwitchOF13.addGroup(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).groupMod( - Matchers.any(GroupModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * updateGroup(org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918. - * UpdateGroupInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testUpdateGroup() throws InterruptedException, ExecutionException { - UpdateGroupOutputBuilder updateGroupOutput = new UpdateGroupOutputBuilder(); - updateGroupOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success(updateGroupOutput.build()).build(); - Mockito.when( - messageDispatchService.groupMod(Matchers.any(GroupModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - UpdateGroupInputBuilder input = new UpdateGroupInputBuilder(); - UpdatedGroupBuilder updatedGroupBuilder = new UpdatedGroupBuilder(); - updatedGroupBuilder.setGroupId(new GroupId(789L)); - updatedGroupBuilder.setGroupType(org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes.GroupFf); - input.setUpdatedGroup(updatedGroupBuilder.build()); - - mdSwitchOF10.updateGroup(input.build()).get(); - mdSwitchOF13.updateGroup(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).groupMod( - Matchers.any(GroupModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * removeGroup(org.opendaylight.yang.gen.v1.urn.opendaylight.group.service.rev130918. - * RemoveGroupInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testRemoveGroup() throws InterruptedException, ExecutionException { - UpdateGroupOutputBuilder updateGroupOutput = new UpdateGroupOutputBuilder(); - updateGroupOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success(updateGroupOutput.build()).build(); - Mockito.when( - messageDispatchService.groupMod(Matchers.any(GroupModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - RemoveGroupInputBuilder input = new RemoveGroupInputBuilder(); - input.setGroupId(new GroupId(789L)); - input.setGroupType(org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes.GroupFf); - - mdSwitchOF10.removeGroup(input.build()).get(); - mdSwitchOF13.removeGroup(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).groupMod( - Matchers.any(GroupModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * addMeter(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918. - * AddMeterInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testAddMeter() throws InterruptedException, ExecutionException { - UpdateMeterOutputBuilder updateMeterOutput = new UpdateMeterOutputBuilder(); - updateMeterOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success(updateMeterOutput.build()).build(); - Mockito.when( - messageDispatchService.meterMod(Matchers.any(MeterModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - AddMeterInputBuilder input = new AddMeterInputBuilder(); - input.setMeterId(new MeterId(78L)); - - mdSwitchOF10.addMeter(input.build()).get(); - mdSwitchOF13.addMeter(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).meterMod( - Matchers.any(MeterModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * updateMeter(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918. - * UpdateMeterInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testUpdtateMeter() throws InterruptedException, ExecutionException { - UpdateMeterOutputBuilder updateMeterOutput = new UpdateMeterOutputBuilder(); - updateMeterOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success(updateMeterOutput.build()).build(); - Mockito.when( - messageDispatchService.meterMod(Matchers.any(MeterModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - UpdateMeterInputBuilder input = new UpdateMeterInputBuilder(); - UpdatedMeterBuilder updatedMeterBuilder = new UpdatedMeterBuilder(); - updatedMeterBuilder.setMeterId(new MeterId(89L)); - updatedMeterBuilder.setBarrier(false); - input.setUpdatedMeter(updatedMeterBuilder.build()); - - mdSwitchOF10.updateMeter(input.build()).get(); - mdSwitchOF13.updateMeter(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).meterMod( - Matchers.any(MeterModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * removeMeter(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.service.rev130918. - * RemoveMeterInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testRemoveMeter() throws InterruptedException, ExecutionException { - UpdateMeterOutputBuilder updateMeterOutput = new UpdateMeterOutputBuilder(); - updateMeterOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success(updateMeterOutput.build()).build(); - Mockito.when( - messageDispatchService.meterMod(Matchers.any(MeterModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - RemoveMeterInputBuilder input = new RemoveMeterInputBuilder(); - input.setMeterId(new MeterId(89L)); - - mdSwitchOF10.removeMeter(input.build()).get(); - mdSwitchOF13.removeMeter(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).meterMod( - Matchers.any(MeterModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getAllGroupStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111. - * GetAllGroupStatisticsInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetAllGroupStatistics() throws InterruptedException, ExecutionException { - GetAllGroupStatisticsOutputBuilder getAllGroupStatistcsOutput = new GetAllGroupStatisticsOutputBuilder(); - getAllGroupStatistcsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetAllGroupStatisticsInputBuilder input = new GetAllGroupStatisticsInputBuilder(); - - mdSwitchOF10.getAllGroupStatistics(input.build()).get(); - mdSwitchOF13.getAllGroupStatistics(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getGroupDescription(org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111. - * GetGroupDescriptionInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetGroupDescription() throws InterruptedException, ExecutionException { - GetGroupDescriptionOutputBuilder getGroupDescOutput = new GetGroupDescriptionOutputBuilder(); - getGroupDescOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetGroupDescriptionInputBuilder input = new GetGroupDescriptionInputBuilder(); - - mdSwitchOF10.getGroupDescription(input.build()).get(); - mdSwitchOF13.getGroupDescription(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getGroupFeatures(org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111. - * GetGroupFeaturesInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetGroupFeatures() throws InterruptedException, ExecutionException { - GetGroupFeaturesOutputBuilder getGroupFeaturesOutput = new GetGroupFeaturesOutputBuilder(); - getGroupFeaturesOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetGroupFeaturesInputBuilder input = new GetGroupFeaturesInputBuilder(); - - mdSwitchOF10.getGroupFeatures(input.build()).get(); - mdSwitchOF13.getGroupFeatures(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getGroupStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111. - * GetGroupStatisticsInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - //TODO GetGroupStatistics why NPE? - @Test - public void testGetGroupStatistics() throws InterruptedException, ExecutionException { - GetGroupStatisticsOutputBuilder getGroupStatsOutput = new GetGroupStatisticsOutputBuilder(); - getGroupStatsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetGroupStatisticsInputBuilder input = new GetGroupStatisticsInputBuilder(); - input.setGroupId(new GroupId(42L)); - - mdSwitchOF10.getGroupStatistics(input.build()).get(); - mdSwitchOF13.getGroupStatistics(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getAllMeterConfigStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111. - * GetAllMeterConfigStatisticsInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetAllMeterConfigStatistics() throws InterruptedException, ExecutionException { - GetAllMeterConfigStatisticsOutputBuilder getAllMeterConfigStatsOutput = - new GetAllMeterConfigStatisticsOutputBuilder(); - getAllMeterConfigStatsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetAllMeterConfigStatisticsInputBuilder input = new GetAllMeterConfigStatisticsInputBuilder(); - - mdSwitchOF10.getAllMeterConfigStatistics(input.build()).get(); - mdSwitchOF13.getAllMeterConfigStatistics(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getAllMeterStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111. - * GetAllMeterStatisticsInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetAllMeterStatistics() throws InterruptedException, ExecutionException { - GetAllMeterStatisticsOutputBuilder getAllMeterStatisticsOutput = - new GetAllMeterStatisticsOutputBuilder(); - getAllMeterStatisticsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetAllMeterStatisticsInputBuilder input = new GetAllMeterStatisticsInputBuilder(); - - mdSwitchOF10.getAllMeterStatistics(input.build()).get(); - mdSwitchOF13.getAllMeterStatistics(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getMeterFeatures(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111. - * GetMeterFeaturesInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetMeterFeatures() throws InterruptedException, ExecutionException { - GetMeterFeaturesOutputBuilder getMeterFeaturesOutput = - new GetMeterFeaturesOutputBuilder(); - getMeterFeaturesOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetMeterFeaturesInputBuilder input = new GetMeterFeaturesInputBuilder(); - - mdSwitchOF10.getMeterFeatures(input.build()).get(); - mdSwitchOF13.getMeterFeatures(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getMeterStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111. - * GetMeterStatisticsInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetMeterStatistics() throws InterruptedException, ExecutionException { - GetMeterStatisticsOutputBuilder getMeterStatsOutput = new GetMeterStatisticsOutputBuilder(); - getMeterStatsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetMeterStatisticsInputBuilder input = new GetMeterStatisticsInputBuilder(); - input.setMeterId(new MeterId(42L)); - - mdSwitchOF10.getMeterStatistics(input.build()).get(); - mdSwitchOF13.getMeterStatistics(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getAllNodeConnectorsStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214. - * GetAllNodeConnectorsStatisticsInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetAllNodeConnectorsStatistics() throws InterruptedException, ExecutionException { - GetAllNodeConnectorsStatisticsOutputBuilder getAllNodeConnectorsStatsOutput = - new GetAllNodeConnectorsStatisticsOutputBuilder(); - getAllNodeConnectorsStatsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build();; - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetAllNodeConnectorsStatisticsInputBuilder input = new GetAllNodeConnectorsStatisticsInputBuilder(); - - mdSwitchOF10.getAllNodeConnectorsStatistics(input.build()).get(); - mdSwitchOF13.getAllNodeConnectorsStatistics(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getNodeConnectorStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214. - * GetNodeConnectorStatisticsInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetNodeConnectorStatistics() throws InterruptedException, ExecutionException { - GetNodeConnectorStatisticsOutputBuilder getNodeConnectorStatsOutput = - new GetNodeConnectorStatisticsOutputBuilder(); - getNodeConnectorStatsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetNodeConnectorStatisticsInputBuilder input = new GetNodeConnectorStatisticsInputBuilder(); - input.setNodeConnectorId(new NodeConnectorId("openflow:12:8")); - - Mockito.when(features.getVersion()).thenReturn((short)1); - mdSwitchOF10.getNodeConnectorStatistics(input.build()).get(); - Mockito.when(features.getVersion()).thenReturn((short)4); - mdSwitchOF13.getNodeConnectorStatistics(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * updatePort(org.opendaylight.yang.gen.v1.urn.opendaylight.port.service.rev131107. - * UpdatePortInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testUpdatePort() throws InterruptedException, ExecutionException { - UpdatePortOutputBuilder updatePortOutput = new UpdatePortOutputBuilder(); - updatePortOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success(updatePortOutput.build()).build(); - Mockito.when( - messageDispatchService.portMod(Matchers.any(PortModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - UpdatePortInputBuilder input = new UpdatePortInputBuilder(); - - PortBuilder portBuilder = new PortBuilder(); - List ports = new ArrayList(); - ports.add(createPort()); - portBuilder.setPort(ports); - UpdatedPortBuilder updatedPortBuilder = new UpdatedPortBuilder(); - updatedPortBuilder.setPort(portBuilder.build()); - input.setUpdatedPort(updatedPortBuilder.build()); - - mdSwitchOF10.updatePort(input.build()).get(); - mdSwitchOF13.updatePort(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).portMod( - Matchers.any(PortModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - private static Port createPort() { - org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.port.mod.port.PortBuilder port = - new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.port.mod.port.PortBuilder(); - - port.setPortName("TestingPort01"); - port.setMask(new PortConfig(true, true, true, true)); - port.setConfiguration(new PortConfig(true, true, true, true)); - port.setAdvertisedFeatures(new PortFeatures(true, true, true, true, - false, false, false, false, - true, true, true, true, - false, false, false, false)); - port.setPortNumber(new PortNumberUni(42L)); - port.setHardwareAddress(new MacAddress("01:23:45:67:89:ab")); - port.setBarrier(true); - port.setContainerName("TestContainer"); - port.setPortModOrder(25L); - port.setKey(new PortKey(25L)); - return port.build(); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * updateTable(org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026. - * UpdateTableInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testUpdateTable() throws InterruptedException, ExecutionException { - UpdateTableOutputBuilder updateTableOutput = new UpdateTableOutputBuilder(); - updateTableOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - UpdateTableInputBuilder input = new UpdateTableInputBuilder(); - input.setUpdatedTable(createUpdateTable()); - - mdSwitchOF10.updateTable(input.build()).get(); - mdSwitchOF13.updateTable(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - private static UpdatedTable createUpdateTable() { - UpdatedTableBuilder updatedTableBuilder = new UpdatedTableBuilder(); - TableFeaturesBuilder tableFeaturesBuilder = new TableFeaturesBuilder(); - tableFeaturesBuilder.setConfig(new TableConfig(true)); - tableFeaturesBuilder.setKey(new TableFeaturesKey((short) 42)); - tableFeaturesBuilder.setMaxEntries(42L); - tableFeaturesBuilder.setMetadataMatch(BigInteger.valueOf(42424242)); - tableFeaturesBuilder.setMetadataWrite(BigInteger.valueOf(42424242)); - tableFeaturesBuilder.setName("testTableFeatures"); - tableFeaturesBuilder.setTableId((short) 41); - - TablePropertiesBuilder tablePropertiesBuilder = new TablePropertiesBuilder(); - TableFeaturePropertiesBuilder tableFeaturePropertiesBuilder = new TableFeaturePropertiesBuilder(); - tableFeaturePropertiesBuilder.setKey(new TableFeaturePropertiesKey(45)); - tableFeaturePropertiesBuilder.setOrder(44); - tableFeaturePropertiesBuilder.setTableFeaturePropType(new ApplySetfieldBuilder().build()); - List tableFeatureProperties = new ArrayList(); - tableFeatureProperties.add(tableFeaturePropertiesBuilder.build()); - tablePropertiesBuilder.setTableFeatureProperties(tableFeatureProperties); - - tableFeaturesBuilder.setTableProperties(tablePropertiesBuilder.build()); - List tableFeatures = new ArrayList(); - tableFeatures.add(tableFeaturesBuilder.build()); - updatedTableBuilder.setTableFeatures(tableFeatures); - return updatedTableBuilder.build(); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getAllFlowStatisticsFromFlowTable(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819. - * GetAllFlowStatisticsFromFlowTableInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetAllFlowStatisticsFromFlowTable() throws InterruptedException, ExecutionException { - GetAllFlowStatisticsFromFlowTableOutputBuilder allFlowStatisticsFromFlowTableOutput = - new GetAllFlowStatisticsFromFlowTableOutputBuilder(); - allFlowStatisticsFromFlowTableOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetAllFlowStatisticsFromFlowTableInputBuilder input = new GetAllFlowStatisticsFromFlowTableInputBuilder(); - input.setTableId(new org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId((short) 42)); - - mdSwitchOF10.getAllFlowStatisticsFromFlowTable(input.build()).get(); - mdSwitchOF13.getAllFlowStatisticsFromFlowTable(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getAllFlowStatisticsFromFlowTable(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819. - * GetAllFlowStatisticsFromFlowTableInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetAllFlowsStatisticsFromAllFlowTables() throws InterruptedException, ExecutionException { - GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder allFlowStatisticsFromAllFlowTablesOutput = - new GetAllFlowsStatisticsFromAllFlowTablesOutputBuilder(); - allFlowStatisticsFromAllFlowTablesOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetAllFlowsStatisticsFromAllFlowTablesInputBuilder input = - new GetAllFlowsStatisticsFromAllFlowTablesInputBuilder(); - - mdSwitchOF10.getAllFlowsStatisticsFromAllFlowTables(input.build()).get(); - mdSwitchOF13.getAllFlowsStatisticsFromAllFlowTables(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getAllFlowStatisticsFromFlowTable(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819. - * GetAllFlowStatisticsFromFlowTableInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetFlowStatisticsFromFlowTables() throws InterruptedException, ExecutionException { - GetFlowStatisticsFromFlowTableOutputBuilder flowStatisticsFromFlowTablesOutput = - new GetFlowStatisticsFromFlowTableOutputBuilder(); - flowStatisticsFromFlowTablesOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetFlowStatisticsFromFlowTableInputBuilder input = - new GetFlowStatisticsFromFlowTableInputBuilder(); - input.setMatch(createMatch()); - - mdSwitchOF10.getFlowStatisticsFromFlowTable(input.build()).get(); - mdSwitchOF13.getFlowStatisticsFromFlowTable(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - private static Match createMatch() { - MatchBuilder matchBuilder = new MatchBuilder(); - EthernetMatchBuilder ethernetMatchBuilder = new EthernetMatchBuilder(); - EthernetDestinationBuilder ethernetDestinationBuilder = new EthernetDestinationBuilder(); - ethernetDestinationBuilder.setAddress(new MacAddress("01:23:45:67:89:ab")); - ethernetDestinationBuilder.setMask(new MacAddress("01:23:45:67:89:ab")); - ethernetMatchBuilder.setEthernetDestination(ethernetDestinationBuilder.build()); - EthernetSourceBuilder ethernetSourceBuilder = new EthernetSourceBuilder(); - ethernetSourceBuilder.setAddress(new MacAddress("01:23:45:67:89:ab")); - ethernetSourceBuilder.setMask(new MacAddress("01:23:45:67:89:ab")); - ethernetMatchBuilder.setEthernetSource(ethernetSourceBuilder.build()); - ethernetMatchBuilder.setEthernetType(new EthernetTypeBuilder().setType(new EtherType(42L)).build()); - matchBuilder.setEthernetMatch(ethernetMatchBuilder.build()); - return matchBuilder.build(); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getAggregateFlowStatisticsFromFlowTableForAllFlows(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819. - * GetAggregateFlowStatisticsFromFlowTableForAllFlowsInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetAggregateFlowStatisticsFromFlowTableForAllFlows() throws InterruptedException, - ExecutionException { - GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder aggregateFlowStatisticsOutput = - new GetAggregateFlowStatisticsFromFlowTableForAllFlowsOutputBuilder(); - aggregateFlowStatisticsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetAggregateFlowStatisticsFromFlowTableForAllFlowsInputBuilder input = - new GetAggregateFlowStatisticsFromFlowTableForAllFlowsInputBuilder(); - input.setTableId(new org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId((short) 42)); - - mdSwitchOF10.getAggregateFlowStatisticsFromFlowTableForAllFlows(input.build()).get(); - mdSwitchOF13.getAggregateFlowStatisticsFromFlowTableForAllFlows(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getAggregateFlowStatisticsFromFlowTableForGivenMatch(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819. - * GetAggregateFlowStatisticsFromFlowTableForGivenMatchInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetAggregateFlowStatisticsFromFlowTableForGivenMatch() throws InterruptedException, - ExecutionException { - GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder aggregateFlowStatisticsForMatchOutput = - new GetAggregateFlowStatisticsFromFlowTableForGivenMatchOutputBuilder(); - aggregateFlowStatisticsForMatchOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetAggregateFlowStatisticsFromFlowTableForGivenMatchInputBuilder input = - new GetAggregateFlowStatisticsFromFlowTableForGivenMatchInputBuilder(); - input.setMatch(createMatch()); - input.setCookie(new FlowCookie(BigInteger.valueOf(123456))); - input.setCookieMask(new FlowCookie(BigInteger.valueOf(123456))); - input.setOutGroup(44L); - input.setOutPort(BigInteger.valueOf(12563)); - - mdSwitchOF10.getAggregateFlowStatisticsFromFlowTableForGivenMatch(input.build()).get(); - mdSwitchOF13.getAggregateFlowStatisticsFromFlowTableForGivenMatch(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getFlowTablesStatistics(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215. - * GetFlowTablesStatisticsInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetFlowTablesStatistics() throws InterruptedException, ExecutionException { - GetFlowTablesStatisticsOutputBuilder flowTableStatisticsOutput = - new GetFlowTablesStatisticsOutputBuilder(); - flowTableStatisticsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetFlowTablesStatisticsInputBuilder input = new GetFlowTablesStatisticsInputBuilder(); - - mdSwitchOF10.getFlowTablesStatistics(input.build()).get(); - mdSwitchOF13.getFlowTablesStatistics(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getAllQueuesStatisticsFromAllPorts(org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216. - * GetAllQueuesStatisticsFromAllPortsInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetAllQueuesStatisticsFromAllPorts() throws InterruptedException, ExecutionException { - GetAllQueuesStatisticsFromAllPortsOutputBuilder allQueuesStatisticsAllPortsOutput = - new GetAllQueuesStatisticsFromAllPortsOutputBuilder(); - allQueuesStatisticsAllPortsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetAllQueuesStatisticsFromAllPortsInputBuilder input = - new GetAllQueuesStatisticsFromAllPortsInputBuilder(); - - mdSwitchOF10.getAllQueuesStatisticsFromAllPorts(input.build()).get(); - mdSwitchOF13.getAllQueuesStatisticsFromAllPorts(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getAllQueuesStatisticsFromGivenPort(org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216. - * GetAllQueuesStatisticsFromGivenPortInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetAllQueuesStatisticsFromGivenPort() throws InterruptedException, ExecutionException { - GetAllQueuesStatisticsFromGivenPortOutputBuilder allQueuesStatisticsGivenPortsOutput = - new GetAllQueuesStatisticsFromGivenPortOutputBuilder(); - allQueuesStatisticsGivenPortsOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetAllQueuesStatisticsFromGivenPortInputBuilder input = - new GetAllQueuesStatisticsFromGivenPortInputBuilder(); - input.setNodeConnectorId(new NodeConnectorId("openflow:12:8")); - - Mockito.when(features.getVersion()).thenReturn((short)1); - mdSwitchOF10.getAllQueuesStatisticsFromGivenPort(input.build()).get(); - Mockito.when(features.getVersion()).thenReturn((short)4); - mdSwitchOF13.getAllQueuesStatisticsFromGivenPort(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl# - * getQueueStatisticsFromGivenPort(org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216. - * GetQueueStatisticsFromGivenPortInput)} - * . - * @throws ExecutionException - * @throws InterruptedException - */ - @Test - public void testGetQueueStatisticsFromGivenPort() throws InterruptedException, ExecutionException { - GetQueueStatisticsFromGivenPortOutputBuilder queuesStatisticsGivenPortOutput = - new GetQueueStatisticsFromGivenPortOutputBuilder(); - queuesStatisticsGivenPortOutput.setTransactionId(new TransactionId(BigInteger.valueOf(42))); - RpcResult result = RpcResultBuilder.success((Void)null).build(); - Mockito.when( - messageDispatchService.multipartRequest(Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - GetQueueStatisticsFromGivenPortInputBuilder input = - new GetQueueStatisticsFromGivenPortInputBuilder(); - input.setNodeConnectorId(new NodeConnectorId("openflow:12:8")); - input.setQueueId(new QueueId(55L)); - - Mockito.when(features.getVersion()).thenReturn((short)1); - mdSwitchOF10.getQueueStatisticsFromGivenPort(input.build()).get(); - Mockito.when(features.getVersion()).thenReturn((short)4); - mdSwitchOF13.getQueueStatisticsFromGivenPort(input.build()).get(); - Mockito.verify(messageDispatchService, Mockito.times(2)).multipartRequest( - Matchers.any(MultipartRequestInput.class), - Matchers.any(SwitchConnectionDistinguisher.class)); - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskUtilTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskUtilTest.java deleted file mode 100644 index ed51e4e73b..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OFRpcTaskUtilTest.java +++ /dev/null @@ -1,101 +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.openflow.md.core.sal; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.when; - -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.ListeningExecutorService; -import java.util.Collection; -import java.util.concurrent.Callable; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.sal.NotificationComposer; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcResult; - -@RunWith(MockitoJUnitRunner.class) -public class OFRpcTaskUtilTest { - - @Mock - private OFRpcTaskContext taskContext; - @Mock - private SwitchConnectionDistinguisher connectionDistinguisher; - @Mock - private SessionContext sessionContext; - @Mock - private IMessageDispatchService messageDispatchService; - @Mock - private GetFeaturesOutput featuresOutput; - @Mock - private ListenableFuture> resultListenableFuture; - @Mock - private ListenableFuture> updateFlowRpcResultListenableFuture; - @Mock - private NotificationProviderService notificationProviderService; - @Mock - private NotificationComposer notificationComposer; - @Mock - ListeningExecutorService executorService; - private ConvertorManager convertorManager; - - - @Before - public void setUp() { - convertorManager = ConvertorManagerFactory.createDefaultManager(); - when(taskContext.getSession()).thenReturn(sessionContext); - when(taskContext.getMessageService()).thenReturn(messageDispatchService); - when(sessionContext.getNextXid()).thenReturn(new Long(10)); - when(sessionContext.getFeatures()).thenReturn(featuresOutput); - when(featuresOutput.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3); - when(messageDispatchService.barrier(Mockito.any(BarrierInput.class), Mockito.any(SwitchConnectionDistinguisher.class))).thenReturn(resultListenableFuture); - when(taskContext.getRpcPool()).thenReturn(executorService); - when(executorService.submit(Mockito.>> any())).thenReturn(updateFlowRpcResultListenableFuture); - } - - - @Test - public void testManageBarrier() throws Exception { - final Collection rpcErrors = OFRpcTaskUtil.manageBarrier(taskContext, true, connectionDistinguisher); - assertNotNull(rpcErrors); - } - - @Test - public void testHookFutureNotification() throws Exception { - final AddFlowInputBuilder flowInputBuilder = new AddFlowInputBuilder(); - final OFRpcTask> addFlowInputRpcResultOFRpcTask = OFRpcTaskFactory.createAddFlowTask(taskContext, flowInputBuilder.build(), connectionDistinguisher, convertorManager); - OFRpcTaskUtil.hookFutureNotification(addFlowInputRpcResultOFRpcTask, updateFlowRpcResultListenableFuture, notificationProviderService, notificationComposer); - } - - @Test - public void testChainFutureBarrier() throws Exception { - final AddFlowInputBuilder flowInputBuilder = new AddFlowInputBuilder(); - flowInputBuilder.setBarrier(true); - final OFRpcTask> addFlowInputRpcResultOFRpcTask = OFRpcTaskFactory.createAddFlowTask(taskContext, flowInputBuilder.build(), connectionDistinguisher, convertorManager); - OFRpcTaskUtil.chainFutureBarrier(addFlowInputRpcResultOFRpcTask, updateFlowRpcResultListenableFuture); - } -} \ No newline at end of file diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OpenflowPluginProviderTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OpenflowPluginProviderTest.java deleted file mode 100644 index 2438d70dad..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/OpenflowPluginProviderTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.sal; - - -import com.google.common.util.concurrent.Futures; -import java.util.ArrayList; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.openflowjava.protocol.spi.connection.SwitchConnectionProvider; - -/** - * @author michal.polkorab - * - */ -public class OpenflowPluginProviderTest { - - @Mock - DataBroker dataBroker; - @Mock - NotificationProviderService notificationProviderService; - @Mock - RpcProviderRegistry rpcProviderRegistry; - @Mock - SwitchConnectionProvider switchProvider; - - OpenflowPluginProvider provider = new OpenflowPluginProvider(); - - /** - * Initializes mocks - */ - @Before - public void startUp() { - MockitoAnnotations.initMocks(this); - provider = new OpenflowPluginProvider(); - } - - /** - * Test {@link OpenflowPluginProvider#initialization()} - */ - @Test - public void testInitialization() { - Mockito.when(switchProvider.startup()).thenReturn(Futures.immediateFuture(Boolean.TRUE)); - ArrayList switchProviders = new ArrayList<>(); - switchProviders.add(switchProvider); - provider.setSwitchConnectionProviders(switchProviders); - provider.setDataBroker(dataBroker); - provider.setNotificationService(notificationProviderService); - provider.setRpcRegistry(rpcProviderRegistry); - provider.initialization(); - - Assert.assertNotNull("Wrong message count dumper", provider.getMessageCountDumper()); - Assert.assertNotNull("Wrong extension converter registrator", provider.getExtensionConverterRegistrator()); - Assert.assertNotNull("Wrong data broker", provider.getDataBroker()); - Assert.assertNotNull("Wrong notification service", provider.getNotificationService()); - Assert.assertNotNull("Wrong rpc registry", provider.getRpcRegistry()); - } -} \ No newline at end of file diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/SalRegistrationManagerTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/SalRegistrationManagerTest.java deleted file mode 100644 index a1df985628..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/sal/SalRegistrationManagerTest.java +++ /dev/null @@ -1,210 +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.openflow.md.core.sal; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListeningExecutorService; -import java.math.BigInteger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.common.api.clustering.EntityOwnershipService; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.AbstractModelDrivenSwitchRegistration; -import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitch; -import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF; -import org.opendaylight.openflowplugin.openflow.md.core.role.OfEntityManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil; -import org.opendaylight.openflowplugin.openflow.md.core.session.SessionContextOFImpl; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; -import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; - -/** - * Created by Martin Bobak mbobak@cisco.com on 8/26/14. - */ -@RunWith(MockitoJUnitRunner.class) -public class SalRegistrationManagerTest { - - - private static final BigInteger dataPathId = BigInteger.ONE; - - private SalRegistrationManager salRegistrationManager; - - private SessionContextOFImpl context; - @Mock - private ConnectionConductor conductor; - @Mock - private IMessageDispatchService messageDispatchService; - @Mock - private GetFeaturesOutput features; - @Mock - private BindingAwareBroker.ProviderContext providerContext; - @Mock - private NotificationEnqueuer notificationEnqueuer; - @Mock - private ListeningExecutorService rpcPool; - @Mock - private NotificationProviderService notificationProviderService; - @Mock - private RpcProviderRegistry rpcProviderRegistry; - @Mock - private DataBroker dataBroker; - @Mock - private EntityOwnershipService entityOwnershipService; - - @Mock - private ModelDrivenSwitchImpl ofSwitch; - - private ModelDrivenSwitch mdSwitchOF13; - - ModelDrivenSwitchRegistration registration; - - @Before - public void setUp() { - OFSessionUtil.getSessionManager().setRpcPool(rpcPool); - Mockito.when(conductor.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_0) - .thenReturn(OFConstants.OFP_VERSION_1_3); - context = new SessionContextOFImpl(); - context.setPrimaryConductor(conductor); - Mockito.when(features.getDatapathId()).thenReturn(BigInteger.valueOf(1)); - Mockito.when(features.getVersion()).thenReturn((short) 1); - context.setFeatures(features); - context.setNotificationEnqueuer(notificationEnqueuer); - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - - OfEntityManager entManager = new OfEntityManager(entityOwnershipService,getConfig()); - mdSwitchOF13 = new ModelDrivenSwitchImpl(null, null, context, convertorManager); - registration = new AbstractModelDrivenSwitchRegistration(mdSwitchOF13) { - @Override - protected void removeRegistration() { - // no-op - } - }; - context.setProviderRegistration(registration); - - UpdateFlowOutputBuilder updateFlowOutput = new UpdateFlowOutputBuilder(); - RpcResult result = RpcResultBuilder.success(updateFlowOutput.build()).build(); - - Mockito.when( - messageDispatchService.flowMod(Matchers.any(FlowModInput.class), - Matchers.any(SwitchConnectionDistinguisher.class))).thenReturn(Futures.immediateFuture(result)); - - salRegistrationManager = new SalRegistrationManager(convertorManager); - salRegistrationManager.setPublishService(notificationProviderService); - salRegistrationManager.setDataService(dataBroker); - salRegistrationManager.setRpcProviderRegistry(rpcProviderRegistry); - salRegistrationManager.setOfEntityManager(entManager); - - salRegistrationManager.init(); - - } - - /** - * free sesion manager - */ - @After - public void tearDown() { - OFSessionUtil.releaseSessionManager(); - } - - /** - * Test for {@link org.opendaylight.openflowplugin.openflow.md.core.sal.SalRegistrationManager#identifierFromDatapathId(java.math.BigInteger)} - */ - @Test - public void testIdentifierFromDatapathId() { - InstanceIdentifier node = SalRegistrationManager.identifierFromDatapathId(dataPathId); - assertNotNull(node); - assertEquals("NodeKey [_id=Uri [_value=openflow:1]]", ((KeyedInstanceIdentifier) node).getKey().toString()); - } - - /** - * Test for {@link org.opendaylight.openflowplugin.openflow.md.core.sal.SalRegistrationManager#nodeKeyFromDatapathId(java.math.BigInteger)} - */ - @Test - public void testNodeKeyFromDatapathId() { - NodeKey nodeKey = SalRegistrationManager.nodeKeyFromDatapathId(dataPathId); - assertNotNull(nodeKey); - assertEquals("openflow:1", nodeKey.getId().getValue()); - } - - /** - * Test for {@link org.opendaylight.openflowplugin.openflow.md.core.sal.SalRegistrationManager#nodeIdFromDatapathId(java.math.BigInteger)} - */ - @Test - public void testNodeIdFromDatapathId() { - NodeId nodeId = SalRegistrationManager.nodeIdFromDatapathId(dataPathId); - assertNotNull(nodeId); - assertEquals("openflow:1", nodeId.getValue()); - } - - /** - * Test for {@link SalRegistrationManager#getSessionManager()} - */ - @Test - public void testGetSessionManager() { - assertNotNull(salRegistrationManager.getPublishService()); - } - - - /** - * Test for {@link org.opendaylight.openflowplugin.openflow.md.core.sal.SalRegistrationManager#onSessionRemoved(org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext)} - */ - @Test - public void testOnSessionRemoved() { -// assertNotNull(context.getProviderRegistration()); -// salRegistrationManager.onSessionAdded(null,context); -// salRegistrationManager.onSessionRemoved(context); -// assertNull(context.getProviderRegistration()); - } - - /** - * Test for {@link org.opendaylight.openflowplugin.openflow.md.core.sal.SalRegistrationManager#onSessionAdded(org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF, org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext)} - */ - public void testOnAdded() { - SwitchSessionKeyOF switchSessionKeyOF = new SwitchSessionKeyOF(); - salRegistrationManager.onSessionAdded(switchSessionKeyOF, context); - } - - public OpenflowPluginConfig getConfig(){ - OpenflowPluginConfig.OpenflowPluginConfigBuilder cfgBuilder = - new OpenflowPluginConfig.OpenflowPluginConfigBuilder(); - cfgBuilder.setSkipTableFeatures(true); - return cfgBuilder.build(); - - } -} - diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/ExtensionSessionManagerImplTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/ExtensionSessionManagerImplTest.java new file mode 100644 index 0000000000..7e92a7ad55 --- /dev/null +++ b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/ExtensionSessionManagerImplTest.java @@ -0,0 +1,46 @@ +/** + * 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.openflow.md.core.session; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterManager; +import org.opendaylight.openflowplugin.extension.api.core.session.ExtensionSessionManager; + +/** + * test of {@link ExtensionSessionManagerImpl} + */ +@RunWith(MockitoJUnitRunner.class) +public class ExtensionSessionManagerImplTest { + + @Mock + private ExtensionConverterManager extensionConverterManager; + + private ExtensionSessionManager sm; + + + /** + * prepare session manager + */ + @Before + public void setUp() { + sm = ExtensionSessionManagerImpl.getInstance(); + } + + @Test + public void setExtensionConverterProvider() { + sm.setExtensionConverterProvider(extensionConverterManager); + assertEquals(extensionConverterManager, sm.getExtensionConverterProvider()); + } + +} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/MessageDispatchServiceImplTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/MessageDispatchServiceImplTest.java deleted file mode 100644 index 65762de41e..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/MessageDispatchServiceImplTest.java +++ /dev/null @@ -1,819 +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.openflow.md.core.session; - -import java.math.BigInteger; -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.Future; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionReadyListener; -import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandler; -import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration; -import org.opendaylight.openflowjava.protocol.api.extensibility.AlienMessageListener; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.ModelDrivenSwitchRegistration; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.ErrorHandler; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.IMessageDispatchService; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF; -import org.opendaylight.openflowplugin.api.openflow.md.queue.QueueProcessor; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ControllerRole; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.EchoReplyInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetConfigOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetQueueConfigOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GroupModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MeterModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OpenflowProtocolListener; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketOutInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetAsyncInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.SetConfigInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SystemNotificationsListener; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.opendaylight.yangtools.yang.common.RpcError; -import org.opendaylight.yangtools.yang.common.RpcResult; - -/** - * test for {@link MessageDispatchServiceImpl} - */ -public class MessageDispatchServiceImplTest { - - MockSessionContext session; - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - session = new MockSessionContext(0); - - } - - /** - * Test barrier message for null cookie - * - * @throws Exception - */ - @Test - public void testBarrierMessageForPrimary() throws Exception { - MockConnectionConductor conductor = new MockConnectionConductor(1); - SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey(); - BarrierInputBuilder barrierMsg = new BarrierInputBuilder(); - session.getMessageDispatchService().barrier(barrierMsg.build(), cookie); - Assert.assertEquals(MessageType.BARRIER, session.getPrimaryConductor() - .getMessageType()); - } - - /** - * Test experimenter message for null cookie - */ - @Test - public void testExperimenter() { - MockConnectionConductor conductor = new MockConnectionConductor(1); - SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey(); - ExperimenterInputBuilder experimenterInputBuilder = new ExperimenterInputBuilder(); - session.getMessageDispatchService().experimenter( - experimenterInputBuilder.build(), cookie); - Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor() - .getMessageType()); - } - - /** - * Test get async input with null cookie - */ - @Test - public void testGetAsync() { - MockConnectionConductor conductor = new MockConnectionConductor(1); - SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey(); - GetAsyncInputBuilder getAsyncInputBuilder = new GetAsyncInputBuilder(); - session.getMessageDispatchService().getAsync( - getAsyncInputBuilder.build(), cookie); - Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor() - .getMessageType()); - } - - /** - * Test get async output with null cookie - */ - @Test - public void testGetConfig() { - MockConnectionConductor conductor = new MockConnectionConductor(1); - SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey(); - GetConfigInputBuilder getConfigInputBuilder = new GetConfigInputBuilder(); - session.getMessageDispatchService().getConfig( - getConfigInputBuilder.build(), cookie); - Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor() - .getMessageType()); - } - - /** - * Test get features with null cookie - */ - @Test - public void testGetFeatures() { - MockConnectionConductor conductor = new MockConnectionConductor(1); - SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey(); - GetFeaturesInputBuilder getFeaturesInputBuilder = new GetFeaturesInputBuilder(); - session.getMessageDispatchService().getFeatures( - getFeaturesInputBuilder.build(), cookie); - Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor() - .getMessageType()); - } - - /** - * Test get queue config with null cookie - */ - @Test - public void testGetQueueConfig() { - MockConnectionConductor conductor = new MockConnectionConductor(1); - SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey(); - GetQueueConfigInputBuilder getQueueConfigInputBuilder = new GetQueueConfigInputBuilder(); - session.getMessageDispatchService().getQueueConfig( - getQueueConfigInputBuilder.build(), cookie); - Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor() - .getMessageType()); - } - - /** - * Test multipart request with null cookie - */ - @Test - public void testGetMultipart() { - MockConnectionConductor conductor = new MockConnectionConductor(1); - SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey(); - MultipartRequestInputBuilder multipartRequestInputBuilder = new MultipartRequestInputBuilder(); - session.getMessageDispatchService().multipartRequest( - multipartRequestInputBuilder.build(), cookie); - Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor() - .getMessageType()); - } - - /** - * Test role request with null cookie - */ - @Test - public void testRoleRequest() { - MockConnectionConductor conductor = new MockConnectionConductor(1); - SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey(); - RoleRequestInputBuilder roleRequestInputBuilder = new RoleRequestInputBuilder(); - session.getMessageDispatchService().roleRequest( - roleRequestInputBuilder.build(), cookie); - Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor() - .getMessageType()); - } - - /** - * Test table mod with null cookie - */ - @Test - public void testTableMod() { - MockConnectionConductor conductor = new MockConnectionConductor(1); - SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey(); - TableModInputBuilder tableModInputBuilder = new TableModInputBuilder(); - session.getMessageDispatchService().tableMod( - tableModInputBuilder.build(), cookie); - Assert.assertEquals(MessageType.TABLEMOD, session.getPrimaryConductor() - .getMessageType()); - } - - /** - * Test packet out message for primary connection - * - * @throws Exception - */ - @Test - public void testPacketOutMessageForPrimary() throws Exception { - session.getMessageDispatchService().packetOut(null, null); - Assert.assertEquals(MessageType.PACKETOUT, session - .getPrimaryConductor().getMessageType()); - } - - /** - * Test packet out message for auxiliary connection - * - * @throws Exception - */ - @Test - public void testPacketOutMessageForAuxiliary() throws Exception { - MockConnectionConductor conductor = new MockConnectionConductor(1); - SwitchConnectionDistinguisher cookie = conductor.getAuxiliaryKey(); - session.addAuxiliaryConductor(cookie, conductor); - session.getMessageDispatchService().packetOut(null, cookie); - Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor() - .getMessageType()); - conductor = (MockConnectionConductor) session - .getAuxiliaryConductor(cookie); - Assert.assertEquals(MessageType.PACKETOUT, conductor.getMessageType()); - } - - /** - * Test packet out message when multiple auxiliary connection exist - * - * @throws Exception - */ - @Test - public void testPacketOutMessageForMultipleAuxiliary() throws Exception { - MockConnectionConductor conductor1 = new MockConnectionConductor(1); - SwitchConnectionDistinguisher cookie1 = conductor1.getAuxiliaryKey(); - session.addAuxiliaryConductor(cookie1, conductor1); - MockConnectionConductor conductor2 = new MockConnectionConductor(2); - SwitchConnectionDistinguisher cookie2 = conductor2.getAuxiliaryKey(); - session.addAuxiliaryConductor(cookie2, conductor2); - MockConnectionConductor conductor3 = new MockConnectionConductor(3); - SwitchConnectionDistinguisher cookie3 = conductor3.getAuxiliaryKey(); - session.addAuxiliaryConductor(cookie3, conductor3); - PacketOutInputBuilder builder = new PacketOutInputBuilder(); - // send message - session.getMessageDispatchService().packetOut(builder.build(), cookie2); - - Assert.assertEquals(MessageType.NONE, session.getPrimaryConductor() - .getMessageType()); - - conductor3 = (MockConnectionConductor) session - .getAuxiliaryConductor(cookie3); - Assert.assertEquals(MessageType.NONE, conductor3.getMessageType()); - - conductor2 = (MockConnectionConductor) session - .getAuxiliaryConductor(cookie2); - Assert.assertEquals(MessageType.PACKETOUT, conductor2.getMessageType()); - - conductor1 = (MockConnectionConductor) session - .getAuxiliaryConductor(cookie1); - Assert.assertEquals(MessageType.NONE, conductor1.getMessageType()); - - } - - /** - * Test for invalid session - * - * @throws Exception - */ - @Test - public void testInvalidSession() throws Exception { - session.setValid(false); - Future> resultFuture = session - .getMessageDispatchService().packetOut(null, null); - if (resultFuture.isDone()) { - RpcResult rpcResult = resultFuture.get(); - Assert.assertTrue(!rpcResult.getErrors().isEmpty()); - - Iterator it = rpcResult.getErrors().iterator(); - RpcError rpcError = it.next(); - - Assert.assertTrue(rpcError.getApplicationTag().equals( - OFConstants.APPLICATION_TAG)); - Assert.assertTrue(rpcError.getTag().equals( - OFConstants.ERROR_TAG_TIMEOUT)); - Assert.assertTrue(rpcError.getErrorType().equals( - RpcError.ErrorType.TRANSPORT)); - } - } - -} - -class MockSessionContext implements SessionContext { - private MockConnectionConductor conductor; - private Map map; - private IMessageDispatchService messageService; - private boolean isValid = true; - private ModelDrivenSwitchRegistration registration; - private int seed; - private SwitchSessionKeyOF sessionKey; - - MockSessionContext(int conductorNum) { - conductor = new MockConnectionConductor(conductorNum); - map = new HashMap<>(); - messageService = new MessageDispatchServiceImpl(this); - sessionKey = new SwitchSessionKeyOF(); - sessionKey.setDatapathId(new BigInteger("0")); - } - - @Override - public MockConnectionConductor getPrimaryConductor() { - // TODO Auto-generated method stub - return conductor; - } - - @Override - public GetFeaturesOutput getFeatures() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ConnectionConductor getAuxiliaryConductor( - SwitchConnectionDistinguisher auxiliaryKey) { - - return map.get(auxiliaryKey); - } - - @Override - public Set> getAuxiliaryConductors() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void addAuxiliaryConductor( - SwitchConnectionDistinguisher auxiliaryKey, - ConnectionConductor conductorArg) { - map.put(auxiliaryKey, conductorArg); - } - - @Override - public ConnectionConductor removeAuxiliaryConductor( - SwitchConnectionDistinguisher connectionCookie) { - return map.remove(connectionCookie); - } - - @Override - public boolean isValid() { - // TODO Auto-generated method stub - return isValid; - } - - @Override - public void setValid(boolean valid) { - isValid = valid; - } - - @Override - public SwitchSessionKeyOF getSessionKey() { - return sessionKey; - } - - @Override - public IMessageDispatchService getMessageDispatchService() { - // TODO Auto-generated method stub - return messageService; - } - - @Override - public Long getNextXid() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map getPhysicalPorts() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Set getPorts() { - // TODO Auto-generated method stub - return null; - } - - @Override - public PortGrouping getPhysicalPort(Long portNumber) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Boolean getPortBandwidth(Long portNumber) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean isPortEnabled(long portNumber) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean isPortEnabled(PortGrouping port) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List getEnabledPorts() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Map getPortsBandwidth() { - // TODO Auto-generated method stub - return null; - } - - @Override - public ModelDrivenSwitchRegistration getProviderRegistration() { - return registration; - } - - @Override - public void setProviderRegistration(ModelDrivenSwitchRegistration registration) { - this.registration = registration; - } - - @Override - public int getSeed() { - return seed; - } - - /** - * @param seed - * the seed to set - */ - public void setSeed(int seed) { - this.seed = seed; - } - - @Override - public NotificationEnqueuer getNotificationEnqueuer() { - return conductor; - } - - @Override - public ControllerRole getRoleOnDevice() { - return null; - } - - @Override - public void setRoleOnDevice(ControllerRole roleOnDevice) { - // NOOP - } -} - -class MockConnectionConductor implements ConnectionConductor, - NotificationEnqueuer { - - private int conductorNum; - private MockConnectionAdapter adapter; - - public MockConnectionConductor(int conductorNumber) { - conductorNum = conductorNumber; - adapter = new MockConnectionAdapter(); - } - - @Override - public void init() { - // TODO Auto-generated method stub - - } - - @Override - public Short getVersion() { - // TODO Auto-generated method stub - return null; - } - - @Override - public CONDUCTOR_STATE getConductorState() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void setConductorState(CONDUCTOR_STATE conductorState) { - // TODO Auto-generated method stub - - } - - @Override - public Future disconnect() { - // TODO Auto-generated method stub - return null; - } - - @Override - public void setSessionContext(SessionContext context) { - // TODO Auto-generated method stub - - } - - @Override - public void setConnectionCookie(SwitchConnectionDistinguisher auxiliaryKey) { - // TODO Auto-generated method stub - - } - - @Override - public SessionContext getSessionContext() { - // TODO Auto-generated method stub - return null; - } - - @Override - public SwitchConnectionDistinguisher getAuxiliaryKey() { - if (0 != conductorNum) { - SwitchConnectionCookieOFImpl key = new SwitchConnectionCookieOFImpl(); - key.setAuxiliaryId((short) conductorNum); - key.init(42); - return key; - } - return null; - } - - @Override - public ConnectionAdapter getConnectionAdapter() { - // TODO Auto-generated method stub - return adapter; - } - - public MessageType getMessageType() { - return adapter.getMessageType(); - } - - @Override - public void setQueueProcessor( - QueueProcessor queueKeeper) { - // NOOP - } - - @Override - public void setErrorHandler(ErrorHandler errorHandler) { - // NOOP - } - - @Override - public void setId(int conductorId) { - // NOOP - } - - @Override - public void enqueueNotification(NotificationQueueWrapper notification) { - // NOOP - } -} - -enum MessageType { - NONE, BARRIER, FLOWMOD, TABLEMOD, PACKETOUT; -} - -class MockConnectionAdapter implements ConnectionAdapter { - - private MessageType messageType; - private ConnectionReadyListener connectionReadyListener; - private boolean packetInFiltering; - - public MockConnectionAdapter() { - setMessageType(MessageType.NONE); - } - - @Override - public Future> barrier(BarrierInput input) { - setMessageType(MessageType.BARRIER); - return null; - } - - @Override - public Future> echo(EchoInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> echoReply(EchoReplyInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> experimenter(ExperimenterInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> flowMod(FlowModInput input) { - setMessageType(MessageType.FLOWMOD); - return null; - } - - @Override - public Future> getAsync(GetAsyncInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> getConfig(GetConfigInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> getFeatures( - GetFeaturesInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> getQueueConfig( - GetQueueConfigInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> groupMod(GroupModInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> hello(HelloInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> meterMod(MeterModInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> packetOut(PacketOutInput input) { - setMessageType(MessageType.PACKETOUT); - return null; - } - - @Override - public Future> portMod(PortModInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> roleRequest( - RoleRequestInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> setAsync(SetAsyncInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> setConfig(SetConfigInput input) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Future> tableMod(TableModInput input) { - setMessageType(MessageType.TABLEMOD); - return null; - } - - @Override - public Future disconnect() { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean isAlive() { - // TODO Auto-generated method stub - return false; - } - - @Override - public void setMessageListener(OpenflowProtocolListener messageListener) { - // TODO Auto-generated method stub - - } - - @Override - public void setSystemListener(SystemNotificationsListener systemListener) { - // TODO Auto-generated method stub - - } - - @Override - public void setAlienMessageListener(AlienMessageListener alienMessageListener) { - - } - - @Override - public void checkListeners() { - // TODO Auto-generated method stub - - } - - /** - * @return the messageType - */ - public MessageType getMessageType() { - return messageType; - } - - /** - * @param messageType - * the messageType to set - */ - public void setMessageType(MessageType messageType) { - this.messageType = messageType; - } - - @Override - public void fireConnectionReadyNotification() { - connectionReadyListener.onConnectionReady(); - } - - @Override - public void setConnectionReadyListener( - ConnectionReadyListener connectionReadyListener) { - this.connectionReadyListener = connectionReadyListener; - } - - @Override - public Future> multipartRequest(MultipartRequestInput input) { - // TODO Auto-generated method stub - return null; - } - - /* - * (non-Javadoc) - * - * @see - * org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter - * #getRemoteAddress() - */ - @Override - public InetSocketAddress getRemoteAddress() { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean isAutoRead() { - // TODO Auto-generated method stub - return false; - } - - @Override - public OutboundQueueHandlerRegistration registerOutboundQueueHandler(final T t, final int i, final long l) { - return null; - } - - @Override - public void setAutoRead(boolean arg0) { - // TODO Auto-generated method stub - - } - - @Override - public void setPacketInFiltering(boolean packetInFiltering) { - this.packetInFiltering = packetInFiltering; - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/OFRoleManagerTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/OFRoleManagerTest.java deleted file mode 100644 index c1ff9bcfb8..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/OFRoleManagerTest.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.openflow.md.core.session; - -import com.google.common.util.concurrent.Futures; -import java.math.BigInteger; -import java.util.Collections; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ControllerRole; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; - -/** - * - */ -@RunWith(MockitoJUnitRunner.class) -public class OFRoleManagerTest { - - @Mock - private SessionManager sessionManager; - @Mock - private SessionContext session; - @Mock - private GetFeaturesOutput features; - @Mock - private ConnectionConductor primaryConductor; - @Mock - private ConnectionAdapter connectionAdapter; - - private OFRoleManager manager; - private RoleRequestOutput roleRequestOutput; - private BarrierOutput barrierOutput; - private BigInteger generationId = BigInteger.TEN; - - /** - * prepare values - */ - @Before - public void setUp() { - Mockito.when(session.getFeatures()).thenReturn(features); - Mockito.when(features.getVersion()).thenReturn(Short.valueOf((short) 42)); - Mockito.when(session.getNextXid()).thenReturn(84L); - Mockito.when(session.getPrimaryConductor()).thenReturn(primaryConductor); - Mockito.when(primaryConductor.getConnectionAdapter()).thenReturn(connectionAdapter); - roleRequestOutput = new RoleRequestOutputBuilder() - .setGenerationId(generationId) - .setRole(ControllerRole.OFPCRROLESLAVE) - .setVersion((short) 42) - .setXid(21L) - .build(); - barrierOutput = new BarrierOutputBuilder() - .setVersion((short) 42) - .setXid(1L) - .build(); - - manager = new OFRoleManager(sessionManager); - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager#manageRoleChange(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole)}. - *
- * session lot is empty is invalid - */ - @Test - public void testManageRoleChangeFail1() { - manager.manageRoleChange(OfpRole.BECOMESLAVE); - Mockito.verify(connectionAdapter, Mockito.never()).roleRequest(Matchers.any(RoleRequestInput.class)); - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager#manageRoleChange(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole)}. - *
- * available session is invalid - */ - @Test - public void testManageRoleChangeFail2() { - Mockito.when(sessionManager.getAllSessions()).thenReturn(Collections.singleton(session)); - manager.manageRoleChange(OfpRole.BECOMESLAVE); - Mockito.verify(connectionAdapter, Mockito.never()).roleRequest(Matchers.any(RoleRequestInput.class)); - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager#manageRoleChange(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole)}. - *
- * device bound to valid session is not answering - */ - @Test - public void testManageRoleChangeFail3() { - Mockito.when(session.isValid()).thenReturn(true); - Mockito.when(sessionManager.getAllSessions()).thenReturn(Collections.singleton(session)); -// manager.manageRoleChange(OfpRole.BECOMESLAVE); -// Mockito.verify(connectionAdapter, Mockito.times(1)).roleRequest(Matchers.any(RoleRequestInput.class)); - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager#manageRoleChange(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole)}. - */ - @Test - public void testManageRoleChangeOK() { - Mockito.when(session.isValid()).thenReturn(true); - Mockito.when(sessionManager.getAllSessions()).thenReturn(Collections.singleton(session)); - Mockito.when(connectionAdapter.roleRequest(Matchers.any(RoleRequestInput.class))) - .thenReturn(Futures.immediateFuture(RpcResultBuilder.success(roleRequestOutput).build())); - Mockito.when(connectionAdapter.barrier(Matchers.any(BarrierInput.class))) - .thenReturn(Futures.immediateFuture(RpcResultBuilder.success(barrierOutput).build())); - - //manager.manageRoleChange(OfpRole.BECOMESLAVE); - - ArgumentCaptor roleRequestCaptor = ArgumentCaptor.forClass(RoleRequestInput.class); - //Mockito.verify(connectionAdapter, Mockito.times(2)).roleRequest(roleRequestCaptor.capture()); - -// List values = roleRequestCaptor.getAllValues(); -// Assert.assertEquals(ControllerRole.OFPCRROLENOCHANGE, values.get(0).getRole()); -// Assert.assertEquals(0L, values.get(0).getGenerationId().longValue()); -// Assert.assertEquals(ControllerRole.OFPCRROLESLAVE, values.get(1).getRole()); -// Assert.assertEquals(11L, values.get(1).getGenerationId().longValue()); - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/PortFeaturesUtilTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/PortFeaturesUtilTest.java deleted file mode 100644 index b76beb0813..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/PortFeaturesUtilTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.session; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeaturesV10; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessageBuilder; -/** - * @author jsebin - */ -public class PortFeaturesUtilTest { - - private PortStatusMessageBuilder portStatusMessageBuilder; - private PortFeaturesUtil portUtil; - - - /** - * initialization of {@link org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessageBuilder.PortStatusMessageBuilder} - * and {@link PortFeaturesUtil} - * @throws Exception - */ - @Before - public void setUp() throws Exception { - portStatusMessageBuilder = new PortStatusMessageBuilder(); - portUtil = PortFeaturesUtil.getInstance(); - } - - /** - * @throws Exception - */ - @After - public void tearDown() throws Exception { - portStatusMessageBuilder = null; - portUtil = null; - } - - /** - * Test method for - * {@link PortFeaturesUtil#getPortBandwidth()} for OF 1.0 version - * and features - * . - */ - @Test - public void testFeaturesV10() { - PortFeaturesV10 features = new PortFeaturesV10(true, true, true, false, true, false, true, true, true, false, true, false); - portStatusMessageBuilder.setReason(PortReason.OFPPRMODIFY).setVersion((short) 1).setCurrentFeaturesV10(features); - - Assert.assertNotNull(portUtil.getPortBandwidth(portStatusMessageBuilder.build())); - } - - /** - * Test method for - * {@link PortFeaturesUtil#getPortBandwidth()} for OF 1.3 version - * and features - * . - */ - @Test - public void testFeaturesV13() { - PortFeatures features = new PortFeatures(true, true, true, false, true, false, true, true, true, false, true, false, false, true, false, false); - portStatusMessageBuilder.setReason(PortReason.OFPPRMODIFY).setVersion((short) 4).setCurrentFeatures(features); - - Assert.assertNotNull(portUtil.getPortBandwidth(portStatusMessageBuilder.build())); - } - - /** - * Test method for - * {@link PortFeaturesUtil#getPortBandwidth()} for malformed features - * - at least one feature is null - * . - */ - @Test - public void testFeaturesMalformed() { - PortFeaturesV10 features = new PortFeaturesV10(true, true, true, true, true, true, false, false, false, false, true, null); - portStatusMessageBuilder.setReason(PortReason.OFPPRMODIFY).setVersion((short) 1).setCurrentFeaturesV10(features); - - Assert.assertNull(portUtil.getPortBandwidth(portStatusMessageBuilder.build())); - } - - /** - * Test method for - * {@link PortFeaturesUtil#getPortBandwidth()} for mismatch between - * port version and port features - * . - */ - @Test - public void testFeaturesVersionMismatch() { - PortFeatures features = new PortFeatures(true, true, true, false, true, false, true, true, true, false, true, false, false, true, false, false); - portStatusMessageBuilder.setReason(PortReason.OFPPRMODIFY).setVersion((short) 1).setCurrentFeatures(features); - - Assert.assertNull(portUtil.getPortBandwidth(portStatusMessageBuilder.build())); - } - - /** - * Test method for - * {@link PortFeaturesUtil#getPortBandwidth()} for nonexisting port version - * . - */ - @Test - public void testFeaturesNonexistingVersion() { - PortFeatures features = new PortFeatures(true, true, true, false, true, false, true, true, true, false, true, false, false, true, false, false); - portStatusMessageBuilder.setReason(PortReason.OFPPRMODIFY).setVersion((short) 0).setCurrentFeatures(features); - - Assert.assertNull(portUtil.getPortBandwidth(portStatusMessageBuilder.build())); - } - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/SessionManagerOFImplTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/SessionManagerOFImplTest.java deleted file mode 100644 index 9a94c3a6ce..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/SessionManagerOFImplTest.java +++ /dev/null @@ -1,151 +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.openflow.md.core.session; - -import static org.mockito.Matchers.any; - -import com.google.common.util.concurrent.ListeningExecutorService; -import java.math.BigInteger; -import java.net.InetSocketAddress; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration; -import org.opendaylight.controller.sal.binding.api.NotificationProviderService; -import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationEnqueuer; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionManager; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SwitchSessionKeyOF; -import org.opendaylight.openflowplugin.openflow.md.core.role.OfEntityManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.ModelDrivenSwitchImpl; -import org.opendaylight.openflowplugin.openflow.md.core.sal.SalRegistrationManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder; -import org.opendaylight.yangtools.yang.binding.RpcService; - -/** - * test of {@link SessionManagerOFImpl} - */ -@RunWith(MockitoJUnitRunner.class) -public class SessionManagerOFImplTest { - - private SessionManager sm; - private SwitchSessionKeyOF sessionKey; - @Mock - private SessionContext context; - @Mock - private ConnectionConductor primaryConductor; - @Mock - private ListeningExecutorService rpcPool; - @Mock - private NotificationProviderService notificationProviderService; - @Mock - private RpcProviderRegistry rpcProviderRegistry; - @Mock - private NotificationEnqueuer notificationEnqueuer; - @Mock - private ConnectionAdapter connectionAdapter; - @Mock - private DataBroker dataService; - - @Mock - private OfEntityManager entManager; - - @Mock - private ModelDrivenSwitchImpl ofSwitch; - - - /** - * prepare session manager - */ - @Before - public void setUp() { - // context - Mockito.when(context.getPrimaryConductor()).thenReturn(primaryConductor); - Mockito.when(context.getNotificationEnqueuer()).thenReturn(notificationEnqueuer); - - // provider context - registration responder - Mockito.when(rpcProviderRegistry.addRoutedRpcImplementation(Matchers.> any(), any(RpcService.class))) - .then(new Answer>() { - @Override - public RoutedRpcRegistration answer(final InvocationOnMock invocation) { - final Object[] args = invocation.getArguments(); - final RoutedRpcRegistration registration = Mockito.mock(RoutedRpcRegistration.class); - Mockito.when(registration.getInstance()).thenReturn((RpcService) args[1]); - return registration; - } - }); - - // session listener - prepare registration and notification mockery - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - final SalRegistrationManager sessionListener = new SalRegistrationManager(convertorManager); - sessionListener.setPublishService(notificationProviderService); - sessionListener.setRpcProviderRegistry(rpcProviderRegistry); - sessionListener.setDataService(dataService); - sessionListener.setOfEntityManager(entManager); - - // session manager (mimic SalRegistrationManager.onSessionInitiated()) - sm = SessionManagerOFImpl.getInstance(); - sm.setRpcPool(rpcPool); - sm.registerSessionListener(sessionListener); - sm.setNotificationProviderService(notificationProviderService); - - // session key - switch id - sessionKey = new SwitchSessionKeyOF(); - sessionKey.setDatapathId(BigInteger.valueOf(42)); - } - - /** - * free session manager - */ - @After - public void tearDown() { - SessionManagerOFImpl.releaseInstance(); - sessionKey = null; - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.session.SessionManagerOFImpl#addSessionContext(SwitchSessionKeyOF, SessionContext)}. - */ - @Test - public void testAddSessionContext() { - // prepare mocks and values - final GetFeaturesOutputBuilder featuresBld = new GetFeaturesOutputBuilder().setDatapathId(BigInteger.valueOf(42)); - featuresBld.setVersion((short) 123); - Mockito.when(context.getFeatures()).thenReturn(featuresBld.build()); - Mockito.when(primaryConductor.getConnectionAdapter()).thenReturn(connectionAdapter); - Mockito.when(connectionAdapter.getRemoteAddress()).thenReturn(new InetSocketAddress("10.1.2.3", 4242)); - - //test target - sm.addSessionContext(sessionKey, context); - - //capture - //ArgumentCaptor notifCaptor = ArgumentCaptor.forClass(NotificationQueueWrapper.class); - //Mockito.verify(notificationEnqueuer).enqueueNotification(notifCaptor.capture()); - //check - //Notification notification = notifCaptor.getValue().getNotification(); - //Assert.assertEquals(NodeUpdated.class, notification.getImplementedInterface()); - //FlowCapableNodeUpdated fcNodeUpdate = ((NodeUpdated) notification).getAugmentation(FlowCapableNodeUpdated.class); - - //Assert.assertNotNull(fcNodeUpdate); - //Assert.assertEquals("10.1.2.3", fcNodeUpdate.getIpAddress().getIpv4Address().getValue()); - } - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/SwitchConnectionCookieOFImplTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/SwitchConnectionCookieOFImplTest.java deleted file mode 100644 index 7debd4681f..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/session/SwitchConnectionCookieOFImplTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.session; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author mirehak - */ -public class SwitchConnectionCookieOFImplTest { - - private static final Logger LOG = LoggerFactory - .getLogger(SwitchConnectionCookieOFImplTest.class); - - private SwitchConnectionCookieOFImpl switchConnectionKey; - - private int seed; - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - seed = 4242; - switchConnectionKey = createSwitchSessionKey((short) 42); - } - - /** - * @param datapathId - * @return - */ - private static SwitchConnectionCookieOFImpl createSwitchSessionKey(short auxiliary) { - SwitchConnectionCookieOFImpl key = new SwitchConnectionCookieOFImpl(); - key.setAuxiliaryId(auxiliary); - return key; - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl#getId()} - * . - */ - @Test - public void testGetId() { - switchConnectionKey.init(seed); - LOG.debug("testKey.id: " + Long.toHexString(switchConnectionKey.getCookie())); - long expected = 710033450L; - Assert.assertEquals(expected, switchConnectionKey.getCookie()); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl#initUUID()} - * . - */ - @Test - public void testInitId1() { - try { - switchConnectionKey.setAuxiliaryId((short) 0); - switchConnectionKey.init(seed); - Assert.fail("init should fail with no datapathId"); - } catch (Exception e) { - // expected - } - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl#equals(Object)} - * , - * {@link org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl#hashCode()} - * . - */ - @Test - public void testHashAndEquals() { - // insert equal keys - SwitchConnectionCookieOFImpl key1 = createSwitchSessionKey((short) 42); - key1.init(seed); - - SwitchConnectionCookieOFImpl key2 = createSwitchSessionKey((short) 42); - key2.init(seed); - - SwitchConnectionCookieOFImpl key3 = createSwitchSessionKey((short) 43); - key3.init(seed); - SwitchConnectionCookieOFImpl key4 = createSwitchSessionKey((short) 21); - key4.init(seed); - - Map keyLot = new HashMap<>(); - keyLot.put(key1, System.identityHashCode(key1)); - Assert.assertEquals(1, keyLot.size()); - keyLot.put(key2, System.identityHashCode(key2)); - Assert.assertEquals(1, keyLot.size()); - keyLot.put(key3, System.identityHashCode(key3)); - Assert.assertEquals(2, keyLot.size()); - keyLot.put(key4, System.identityHashCode(key4)); - Assert.assertEquals(3, keyLot.size()); - - // lookup using inited key - Assert.assertEquals(System.identityHashCode(key2), keyLot.get(key1) - .intValue()); - Assert.assertEquals(System.identityHashCode(key2), keyLot.get(key2) - .intValue()); - Assert.assertEquals(System.identityHashCode(key3), keyLot.get(key3) - .intValue()); - Assert.assertEquals(System.identityHashCode(key4), keyLot.get(key4) - .intValue()); - - // lookup using not inited key - SwitchConnectionCookieOFImpl keyWithoutInit = createSwitchSessionKey((short) 42); - Assert.assertNull(keyLot.get(keyWithoutInit)); - - // creating brand new key and lookup - SwitchConnectionCookieOFImpl keyWithInit = createSwitchSessionKey((short) 43); - keyWithInit.init(seed); - Assert.assertEquals(System.identityHashCode(key3), - keyLot.get(keyWithInit).intValue()); - - // lookup with key containing encoded part only - LOG.debug("key3.id: " + Long.toHexString(key3.getCookie())); - SwitchConnectionCookieOFImpl keyWithoutDPID = new SwitchConnectionCookieOFImpl(734546075L); - Assert.assertEquals(System.identityHashCode(key3), - keyLot.get(keyWithoutDPID).intValue()); - } - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorTranslatorTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorTranslatorTest.java deleted file mode 100644 index 6742557193..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorTranslatorTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * Copyright (c) 2013, 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.openflow.md.core.translator; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.when; - -import java.lang.reflect.Method; -import java.math.BigInteger; -import java.util.List; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.BaseNodeErrorNotification; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class ErrorTranslatorTest { - - private final ErrorTranslator errorTranslator = new ErrorTranslator(); - private final ErrorMessageBuilder builder = new ErrorMessageBuilder();; - private static final BigInteger DATAPATH_ID = BigInteger.valueOf(0x7777L); - private static Logger LOG = LoggerFactory - .getLogger(ErrorTranslatorTest.class); - - @Mock - SwitchConnectionDistinguisher cookie; - @Mock - SessionContext sc; - @Mock - GetFeaturesOutput features; - - /** - * startup method - */ - @Before - public void setUp() { - builder.setCode(21); - builder.setXid(42L); - builder.setData(new byte[]{42}); - - MockitoAnnotations.initMocks(this); - when(sc.getFeatures()).thenReturn(features); - when(features.getDatapathId()).thenReturn(DATAPATH_ID); - } - - - @Test - public void testTranslate() { - builder.setType(1); - List data = errorTranslator.translate(cookie, sc, builder.build()); - assertNotNull(data); - Assert.assertEquals(1, data.size()); - DataObject obj = data.get(0); - Assert.assertTrue(obj instanceof BaseNodeErrorNotification); - BaseNodeErrorNotification nodeError = (BaseNodeErrorNotification)obj; - NodeRef expectedNode = new NodeRef( - InventoryDataServiceUtil.identifierFromDatapathId(DATAPATH_ID)); - Assert.assertEquals(expectedNode, nodeError.getNode()); - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.translator.ErrorTranslator#getGranularNodeErrors(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType, NodeRef)}. - * - * @throws Exception - */ - @Test - public void testGetGranularNodeErrors() throws Exception { - BigInteger dpid = BigInteger.valueOf(0x1122334455667788L); - NodeRef node = new NodeRef( - InventoryDataServiceUtil.identifierFromDatapathId(dpid)); - for (ErrorType eType : ErrorType.values()) { - builder.setType(eType.getIntValue()); - ErrorMessage errorMessage = errorTranslator.getGranularNodeErrors(builder.build(), eType, node); - LOG.debug("translating errorMessage of type {}", eType); - assertNotNull("translated error is null", errorMessage); - Assert.assertEquals(21, errorMessage.getCode().intValue()); - Assert.assertEquals(eType, errorMessage.getType()); - Method getNode = errorMessage.getClass().getMethod("getNode"); - getNode.setAccessible(true); - Assert.assertEquals(node, getNode.invoke(errorMessage)); - Method getXid = errorMessage.getClass().getMethod("getTransactionId", new Class[0]); - getXid.setAccessible(true); - TransactionId xid = (TransactionId) getXid.invoke(errorMessage, new Object[0]); - Assert.assertEquals(42L, xid.getValue().longValue()); - assertNotNull("data is null", errorMessage.getData()); - } - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.translator.ErrorTranslator#decodeErrorType(int)}. - */ - @Test - public void testDecodeErrorType() { - for (ErrorType eType : ErrorType.values()) { - ErrorType result = errorTranslator.decodeErrorType(eType.getIntValue()); - Assert.assertEquals(eType, result); - } - } - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorTranslatorV10Test.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorTranslatorV10Test.java deleted file mode 100644 index 6950cd4565..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/ErrorTranslatorV10Test.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright (c) 2013, 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.openflow.md.core.translator; - -import java.lang.reflect.Method; -import java.math.BigInteger; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessageBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * - */ -public class ErrorTranslatorV10Test { - - private ErrorV10Translator errorTranslator; - private static Logger LOG = LoggerFactory - .getLogger(ErrorTranslatorV10Test.class); - - /** - * startup method - */ - @Before - public void setUp() { - errorTranslator = new ErrorV10Translator(); - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.translator.ErrorTranslator#getGranularNodeErrors(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ErrorMessage, org.opendaylight.yang.gen.v1.urn.opendaylight.flow.errors.rev131116.ErrorType, NodeRef)}. - * @throws Exception - */ - @Test - public void testGetGranularNodeErrors() throws Exception { - BigInteger dpid = BigInteger.valueOf(0x1122334455L); - NodeRef node = new NodeRef( - InventoryDataServiceUtil.identifierFromDatapathId(dpid)); - for (ErrorType eType : ErrorType.values()) { - ErrorMessageBuilder builder = new ErrorMessageBuilder(); - builder.setType(eType.getIntValue()); - builder.setCode(21); - builder.setXid(42L); - builder.setData(new byte[]{42}); - - ErrorMessage errorMessage = errorTranslator.getGranularNodeErrors(builder.build(), eType, node); - LOG.debug("translating errorMessage of type {}", eType); - Assert.assertNotNull("translated error is null", errorMessage); - Assert.assertEquals(21, errorMessage.getCode().intValue()); - Assert.assertEquals(eType, errorMessage.getType()); - Method getNode = errorMessage.getClass().getMethod("getNode"); - getNode.setAccessible(true); - Assert.assertEquals(node, getNode.invoke(errorMessage)); - Method getXid = errorMessage.getClass().getMethod("getTransactionId", new Class[0]); - getXid.setAccessible(true); - TransactionId xid = (TransactionId) getXid.invoke(errorMessage, new Object[0]); - Assert.assertEquals(42L, xid.getValue().longValue()); - Assert.assertNotNull("data is null", errorMessage.getData()); - } - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.core.translator.ErrorTranslator#decodeErrorType(int)}. - */ - @Test - public void testDecodeErrorType() { - for (ErrorType eType : ErrorType.values()) { - ErrorType result = errorTranslator.decodeErrorType(eType.getIntValue()); - int expectedType = -1; - switch (eType.getIntValue()) { - case 3: - expectedType = 5; - break; - case 4: - expectedType = 7; - break; - case 5: - expectedType = 9; - break; - default: - expectedType = eType.getIntValue(); - } - - Assert.assertEquals(expectedType, result.getIntValue()); - } - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FeaturesV10ToNodeConnectorUpdatedTranslatorTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FeaturesV10ToNodeConnectorUpdatedTranslatorTest.java deleted file mode 100644 index c537a6b916..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FeaturesV10ToNodeConnectorUpdatedTranslatorTest.java +++ /dev/null @@ -1,145 +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.openflow.md.core.translator; - -import static org.mockito.Mockito.when; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import junit.framework.TestCase; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ActionTypeV10; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.CapabilitiesV10; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortConfig; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortState; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPort; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPortBuilder; -import org.opendaylight.yangtools.yang.binding.Augmentation; -import org.opendaylight.yangtools.yang.binding.DataContainer; -import org.opendaylight.yangtools.yang.binding.DataObject; - -@RunWith(MockitoJUnitRunner.class) -public class FeaturesV10ToNodeConnectorUpdatedTranslatorTest extends TestCase { - - private static final FeaturesV10ToNodeConnectorUpdatedTranslator FEATURES_V_10_TO_NODE_CONNECTOR_UPDATED_TRANSLATOR = new FeaturesV10ToNodeConnectorUpdatedTranslator(); - private static final PortFeatures PORT_FEATURES = new PortFeatures(true, false, false, false, false, false, false, false, false, false, true, true, false, false, false, false); - - @Mock - SwitchConnectionDistinguisher switchConnectionDistinguisher; - private static final PortConfig PORT_CONFIG = new PortConfig(true, false, false, false); - @Mock - SessionContext sessionContext; - @Mock - GetFeaturesOutput featuresOutput; - - @Test - /** - * Test method for basic functionality of {@link FeaturesV10ToNodeConnectorUpdatedTranslator#translate(org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher, org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext, org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader)} - */ - public void testTranslate() throws Exception { - - when(sessionContext.getFeatures()).thenReturn(featuresOutput); - when(featuresOutput.getDatapathId()).thenReturn(BigInteger.valueOf(42)); - List data = FEATURES_V_10_TO_NODE_CONNECTOR_UPDATED_TRANSLATOR.translate(switchConnectionDistinguisher, sessionContext, new MockOfHeader()); - assertNotNull(data); - assertEquals(10, data.size()); - } - - private final class MockOfHeader implements OfHeader, GetFeaturesOutput { - - @Override - public Short getVersion() { - return OFConstants.OFP_VERSION_1_3; - } - - @Override - public Long getXid() { - return new Long(1); - } - - @Override - public Class getImplementedInterface() { - return GetFeaturesOutput.class; - } - - @Override - public > E getAugmentation(final Class eClass) { - return null; - } - - @Override - public BigInteger getDatapathId() { - return null; - } - - @Override - public Long getBuffers() { - return null; - } - - @Override - public Short getTables() { - return null; - } - - @Override - public Short getAuxiliaryId() { - return null; - } - - @Override - public Capabilities getCapabilities() { - return null; - } - - @Override - public Long getReserved() { - return null; - } - - @Override - public CapabilitiesV10 getCapabilitiesV10() { - return null; - } - - @Override - public ActionTypeV10 getActionsV10() { - return null; - } - - @Override - public List getPhyPort() { - List phyPorts = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - PhyPortBuilder phyPortBuilder = new PhyPortBuilder(); - phyPortBuilder.setAdvertisedFeatures(PORT_FEATURES); - phyPortBuilder.setConfig(PORT_CONFIG); - phyPortBuilder.setCurrentFeatures(PORT_FEATURES); - phyPortBuilder.setPeerFeatures(PORT_FEATURES); - phyPortBuilder.setState(PortState.getDefaultInstance("live")); - phyPortBuilder.setSupportedFeatures(PORT_FEATURES); - phyPortBuilder.setPortNo(new Long(42)); - phyPorts.add(phyPortBuilder.build()); - } - return phyPorts; - } - } - -} \ No newline at end of file diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FlowRemovedTranslatorTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FlowRemovedTranslatorTest.java deleted file mode 100644 index 56a8cbf54b..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/FlowRemovedTranslatorTest.java +++ /dev/null @@ -1,624 +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.openflow.md.core.translator; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.when; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion; -import org.opendaylight.openflowplugin.openflow.md.core.extension.ExtensionConverterManagerImpl; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.openflowplugin.openflow.md.core.session.SessionManagerOFImpl; -import org.opendaylight.openflowplugin.openflow.md.util.ByteUtil; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Dscp; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address; -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.Ipv6FlowLabel; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.mod.removed.Match; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.ProtocolMatchFields; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.EthernetMatch; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Icmpv4Match; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.IpMatch; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Tunnel; -import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.VlanMatch; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.EtherType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Ipv6ExthdrFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortNumber; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpOp; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpSha; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpSpa; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpTha; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.ArpTpa; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.EthSrc; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.EthType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv4Code; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv4Type; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv6Code; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Icmpv6Type; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.InPhyPort; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.InPort; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.IpProto; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv4Dst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv4Src; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Dst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Exthdr; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Flabel; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6NdSll; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6NdTarget; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6NdTll; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Ipv6Src; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.Metadata; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MplsBos; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MplsLabel; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.PbbIsid; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.SctpDst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.TcpDst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.TunnelId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.UdpDst; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.UdpSrc; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.VlanPcp; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntry; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntryBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpOpCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpShaCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpSpaCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpThaCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ArpTpaCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.EthDstCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.EthSrcCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.EthTypeCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv4CodeCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv4TypeCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv6CodeCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Icmpv6TypeCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.InPhyPortCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.InPortCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.IpDscpCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.IpEcnCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.IpProtoCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv4DstCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv4SrcCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6DstCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6ExthdrCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6FlabelCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6NdSllCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6NdTargetCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6NdTllCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.Ipv6SrcCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MetadataCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MplsBosCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MplsLabelCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.MplsTcCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.PbbIsidCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.SctpDstCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.SctpSrcCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.TcpDstCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.TcpSrcCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.TunnelIdCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.UdpDstCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.UdpSrcCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.VlanPcpCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.VlanVidCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.arp.op._case.ArpOpBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.arp.sha._case.ArpShaBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.arp.spa._case.ArpSpaBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.arp.tha._case.ArpThaBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.arp.tpa._case.ArpTpaBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.eth.dst._case.EthDstBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.eth.src._case.EthSrcBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.eth.type._case.EthTypeBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.icmpv4.code._case.Icmpv4CodeBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.icmpv4.type._case.Icmpv4TypeBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.icmpv6.code._case.Icmpv6CodeBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.icmpv6.type._case.Icmpv6TypeBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.in.phy.port._case.InPhyPortBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.in.port._case.InPortBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ip.dscp._case.IpDscpBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ip.ecn._case.IpEcnBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ip.proto._case.IpProtoBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv4.dst._case.Ipv4DstBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv4.src._case.Ipv4SrcBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.dst._case.Ipv6DstBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.exthdr._case.Ipv6ExthdrBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.flabel._case.Ipv6FlabelBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.nd.sll._case.Ipv6NdSllBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.nd.target._case.Ipv6NdTargetBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.nd.tll._case.Ipv6NdTllBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.ipv6.src._case.Ipv6SrcBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.mpls.bos._case.MplsBosBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.mpls.label._case.MplsLabelBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.mpls.tc._case.MplsTcBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.pbb.isid._case.PbbIsidBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.sctp.dst._case.SctpDstBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.sctp.src._case.SctpSrcBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.tcp.dst._case.TcpDstBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.tcp.src._case.TcpSrcBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.tunnel.id._case.TunnelIdBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.udp.dst._case.UdpDstBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.udp.src._case.UdpSrcBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.vlan.pcp._case.VlanPcpBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.vlan.vid._case.VlanVidBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yangtools.yang.binding.DataObject; - -@RunWith(MockitoJUnitRunner.class) -public class FlowRemovedTranslatorTest { - - private FlowRemovedTranslator flowRemovedTranslator; - private static final BigInteger DATA_PATH_ID = BigInteger.valueOf(42); - public static final Ipv6Address IPV_6_ADDRESS = new Ipv6Address("2001:0DB8:AC10:FE01:0000:0000:0000:0000"); - private static final byte[] IPV_6_ADDRESS_MASK = ByteUtil.unsignedIntToBytes(new Long(64)); - private static final Ipv4Address IPV_4_ADDRESS = new Ipv4Address("10.0.0.1"); - private static final byte[] IPV_4_ADDRESS_MASK = ByteUtil.unsignedIntToBytes(new Long(8)); - - @Mock - SwitchConnectionDistinguisher switchConnectionDistinguisher; - - @Mock - SessionContext sessionContext; - - @Mock - FlowRemovedMessage msg; - - @Mock - ConnectionConductor connectionConductor; - - @Mock - GetFeaturesOutput featuresOutput; - - private static final MacAddress MAC_ADDRESS = new MacAddress("00:01:02:03:04:05"); - - - private static List fieldClassesAndAugmentations = new ArrayList<>(); - - - private static void setupClassAndAugmentationMap() { - - - MatchEntryBuilder matchEntryBuilder = new MatchEntryBuilder(); - InPortBuilder portBuilder = new InPortBuilder(); - portBuilder.setPortNumber(new PortNumber((long) 42)); - InPortCaseBuilder inPortCaseBuilder = new InPortCaseBuilder(); - inPortCaseBuilder.setInPort(portBuilder.build()); - matchEntryBuilder.setMatchEntryValue(inPortCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(InPort.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - InPhyPortBuilder inPhyPortBuilder = new InPhyPortBuilder(); - PortNumber portNumber = new PortNumber((long) 42); - inPhyPortBuilder.setPortNumber(portNumber); - InPhyPortCaseBuilder inPhyPortCaseBuilder = new InPhyPortCaseBuilder(); - inPhyPortCaseBuilder.setInPhyPort(inPhyPortBuilder.build()); - matchEntryBuilder.setMatchEntryValue(inPhyPortCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(InPhyPort.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - MetadataCaseBuilder metadataCaseBuilder = new MetadataCaseBuilder(); - org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.metadata._case.MetadataBuilder metadataBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entry.value.grouping.match.entry.value.metadata._case.MetadataBuilder(); - metadataBuilder.setMetadata(new byte[0]); - metadataBuilder.setMask(new byte[0]); - metadataCaseBuilder.setMetadata(metadataBuilder.build()); - matchEntryBuilder.setMatchEntryValue(metadataCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Metadata.class); - matchEntryBuilder.setHasMask(false); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - - EthTypeBuilder ethTypeBuilder = new EthTypeBuilder(); - ethTypeBuilder.setEthType(new EtherType(6)); - EthTypeCaseBuilder ethTypeCaseBuilder = new EthTypeCaseBuilder(); - ethTypeCaseBuilder.setEthType(ethTypeBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ethTypeCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(EthType.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - VlanVidBuilder vlanVidBuilder = new VlanVidBuilder(); - vlanVidBuilder.setCfiBit(true); - vlanVidBuilder.setVlanVid(42); - VlanVidCaseBuilder vlanVidCaseBuilder = new VlanVidCaseBuilder(); - vlanVidCaseBuilder.setVlanVid(vlanVidBuilder.build()); - matchEntryBuilder.setMatchEntryValue(vlanVidCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.VlanVid.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - VlanPcpBuilder vlanPcpBuilder = new VlanPcpBuilder(); - vlanPcpBuilder.setVlanPcp((short) 7); - VlanPcpCaseBuilder vlanPcpCaseBuilder = new VlanPcpCaseBuilder(); - vlanPcpCaseBuilder.setVlanPcp(vlanPcpBuilder.build()); - matchEntryBuilder.setMatchEntryValue(vlanPcpCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(VlanPcp.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - IpDscpBuilder ipDscpBuilder = new IpDscpBuilder(); - ipDscpBuilder.setDscp(new Dscp((short) 10)); - IpDscpCaseBuilder ipDscpCaseBuilder = new IpDscpCaseBuilder(); - ipDscpCaseBuilder.setIpDscp(ipDscpBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ipDscpCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.IpDscp.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - IpEcnBuilder ipEcnBuilder = new IpEcnBuilder(); - ipEcnBuilder.setEcn((short) 10); - IpEcnCaseBuilder ipEcnCaseBuilder = new IpEcnCaseBuilder(); - ipEcnCaseBuilder.setIpEcn(ipEcnBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ipEcnCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.IpEcn.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - IpProtoBuilder ipProtoBuilder = new IpProtoBuilder(); - ipProtoBuilder.setProtocolNumber(OFConstants.OFP_VERSION_1_3); - IpProtoCaseBuilder ipProtoCaseBuilder = new IpProtoCaseBuilder(); - ipProtoCaseBuilder.setIpProto(ipProtoBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ipProtoCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(IpProto.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - TcpSrcBuilder tcpSrcBuilder = new TcpSrcBuilder(); - org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber port = new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber(43); - tcpSrcBuilder.setPort(port); - TcpSrcCaseBuilder tcpSrcCaseBuilder = new TcpSrcCaseBuilder(); - tcpSrcCaseBuilder.setTcpSrc(tcpSrcBuilder.build()); - matchEntryBuilder.setMatchEntryValue(tcpSrcCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.TcpSrc.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - TcpDstBuilder tcpDstBuilder = new TcpDstBuilder(); - tcpDstBuilder.setPort(port); - TcpDstCaseBuilder tcpDstCaseBuilder = new TcpDstCaseBuilder(); - tcpDstCaseBuilder.setTcpDst(tcpDstBuilder.build()); - matchEntryBuilder.setMatchEntryValue(tcpDstCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(TcpDst.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - UdpSrcBuilder udpSrcBuilder = new UdpSrcBuilder(); - udpSrcBuilder.setPort(port); - UdpSrcCaseBuilder udpSrcCaseBuilder = new UdpSrcCaseBuilder(); - udpSrcCaseBuilder.setUdpSrc(udpSrcBuilder.build()); - matchEntryBuilder.setMatchEntryValue(udpSrcCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(UdpSrc.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - UdpDstBuilder udpDstBuilder = new UdpDstBuilder(); - udpDstBuilder.setPort(port); - UdpDstCaseBuilder udpDstCaseBuilder = new UdpDstCaseBuilder(); - udpDstCaseBuilder.setUdpDst(udpDstBuilder.build()); - matchEntryBuilder.setMatchEntryValue(udpDstCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(UdpDst.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - SctpSrcBuilder sctpSrcBuilder = new SctpSrcBuilder(); - sctpSrcBuilder.setPort(port); - SctpSrcCaseBuilder sctpSrcCaseBuilder = new SctpSrcCaseBuilder(); - sctpSrcCaseBuilder.setSctpSrc(sctpSrcBuilder.build()); - matchEntryBuilder.setMatchEntryValue(sctpSrcCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.SctpSrc.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - SctpDstBuilder sctpDstBuilder = new SctpDstBuilder(); - sctpDstBuilder.setPort(port); - SctpDstCaseBuilder sctpDstCaseBuilder = new SctpDstCaseBuilder(); - sctpDstCaseBuilder.setSctpDst(sctpDstBuilder.build()); - matchEntryBuilder.setMatchEntryValue(sctpDstCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(SctpDst.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - Icmpv4TypeBuilder icmpv4TypeBuilder = new Icmpv4TypeBuilder(); - icmpv4TypeBuilder.setIcmpv4Type((short) 10); - Icmpv4TypeCaseBuilder icmpv4TypeCaseBuilder = new Icmpv4TypeCaseBuilder(); - icmpv4TypeCaseBuilder.setIcmpv4Type(icmpv4TypeBuilder.build()); - matchEntryBuilder.setMatchEntryValue(icmpv4TypeCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Icmpv4Type.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - Icmpv4CodeBuilder icmpv4CodeBuilder = new Icmpv4CodeBuilder(); - icmpv4CodeBuilder.setIcmpv4Code((short) 10); - Icmpv4CodeCaseBuilder icmpv4CodeCaseBuilder = new Icmpv4CodeCaseBuilder(); - icmpv4CodeCaseBuilder.setIcmpv4Code(icmpv4CodeBuilder.build()); - matchEntryBuilder.setMatchEntryValue(icmpv4CodeCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Icmpv4Code.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - Icmpv6TypeBuilder icmpv6TypeBuilder = new Icmpv6TypeBuilder(); - icmpv6TypeBuilder.setIcmpv6Type((short) 10); - Icmpv6TypeCaseBuilder icmpv6TypeCaseBuilder = new Icmpv6TypeCaseBuilder(); - icmpv6TypeCaseBuilder.setIcmpv6Type(icmpv6TypeBuilder.build()); - matchEntryBuilder.setMatchEntryValue(icmpv6TypeCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Icmpv6Type.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - Icmpv6CodeBuilder icmpv6CodeBuilder = new Icmpv6CodeBuilder(); - icmpv6CodeBuilder.setIcmpv6Code((short) 10); - Icmpv6CodeCaseBuilder icmpv6CodeCaseBuilder = new Icmpv6CodeCaseBuilder(); - icmpv6CodeCaseBuilder.setIcmpv6Code(icmpv6CodeBuilder.build()); - matchEntryBuilder.setMatchEntryValue(icmpv6CodeCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Icmpv6Code.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - ArpOpBuilder arpOpBuilder = new ArpOpBuilder(); - arpOpBuilder.setOpCode(42); - ArpOpCaseBuilder arpOpCaseBuilder = new ArpOpCaseBuilder(); - arpOpCaseBuilder.setArpOp(arpOpBuilder.build()); - matchEntryBuilder.setMatchEntryValue(arpOpCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(ArpOp.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - ArpShaBuilder arpShaBuilder = new ArpShaBuilder(); - arpShaBuilder.setMacAddress(MAC_ADDRESS); - ArpShaCaseBuilder arpShaCaseBuilder = new ArpShaCaseBuilder(); - arpShaCaseBuilder.setArpSha(arpShaBuilder.build()); - matchEntryBuilder.setMatchEntryValue(arpShaCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(ArpSha.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - ArpThaBuilder arpThaBuilder = new ArpThaBuilder(); - arpThaBuilder.setMacAddress(MAC_ADDRESS); - ArpThaCaseBuilder arpThaCaseBuilder = new ArpThaCaseBuilder(); - arpThaCaseBuilder.setArpTha(arpThaBuilder.build()); - matchEntryBuilder.setMatchEntryValue(arpThaCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(ArpTha.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - EthDstBuilder ethDstBuilder = new EthDstBuilder(); - ethDstBuilder.setMacAddress(MAC_ADDRESS); - EthDstCaseBuilder ethDstCaseBuilder = new EthDstCaseBuilder(); - ethDstCaseBuilder.setEthDst(ethDstBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ethDstCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.EthDst.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - EthSrcBuilder ethSrcBuilder = new EthSrcBuilder(); - ethSrcBuilder.setMacAddress(MAC_ADDRESS); - EthSrcCaseBuilder ethSrcCaseBuilder = new EthSrcCaseBuilder(); - ethSrcCaseBuilder.setEthSrc(ethSrcBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ethSrcCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(EthSrc.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - - Ipv6FlabelBuilder ipv6FlabelBuilder = new Ipv6FlabelBuilder(); - ipv6FlabelBuilder.setIpv6Flabel(new Ipv6FlowLabel((long) 42)); - Ipv6FlabelCaseBuilder ipv6FlabelCaseBuilder = new Ipv6FlabelCaseBuilder(); - ipv6FlabelCaseBuilder.setIpv6Flabel(ipv6FlabelBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ipv6FlabelCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Ipv6Flabel.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - Ipv6NdTargetBuilder ipv6NdTargetBuilder = new Ipv6NdTargetBuilder(); - ipv6NdTargetBuilder.setIpv6Address(IPV_6_ADDRESS); - Ipv6NdTargetCaseBuilder ipv6NdTargetCaseBuilder = new Ipv6NdTargetCaseBuilder(); - ipv6NdTargetCaseBuilder.setIpv6NdTarget(ipv6NdTargetBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ipv6NdTargetCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Ipv6NdTarget.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - Ipv6NdSllBuilder ipv6NdSllBuilder = new Ipv6NdSllBuilder(); - ipv6NdSllBuilder.setMacAddress(MAC_ADDRESS); - Ipv6NdSllCaseBuilder ipv6NdSllCaseBuilder = new Ipv6NdSllCaseBuilder(); - ipv6NdSllCaseBuilder.setIpv6NdSll(ipv6NdSllBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ipv6NdSllCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Ipv6NdSll.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - Ipv6NdTllBuilder ipv6NdTllBuilder = new Ipv6NdTllBuilder(); - ipv6NdTllBuilder.setMacAddress(MAC_ADDRESS); - Ipv6NdTllCaseBuilder ipv6NdTllCaseBuilder = new Ipv6NdTllCaseBuilder(); - ipv6NdTllCaseBuilder.setIpv6NdTll(ipv6NdTllBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ipv6NdTllCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Ipv6NdTll.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - Ipv6ExthdrBuilder ipv6ExthdrBuilder = new Ipv6ExthdrBuilder(); - Ipv6ExthdrFlags ipv6ExthdrFlags = new Ipv6ExthdrFlags(true, true, true, true, true, true, true, true, true); - ipv6ExthdrBuilder.setPseudoField(ipv6ExthdrFlags); - ipv6ExthdrBuilder.setMask(IPV_6_ADDRESS_MASK); - Ipv6ExthdrCaseBuilder ipv6ExthdrCaseBuilder = new Ipv6ExthdrCaseBuilder(); - ipv6ExthdrCaseBuilder.setIpv6Exthdr(ipv6ExthdrBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ipv6ExthdrCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Ipv6Exthdr.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - MplsLabelBuilder mplsLabelBuilder = new MplsLabelBuilder(); - mplsLabelBuilder.setMplsLabel((long) 42); - MplsLabelCaseBuilder mplsLabelCaseBuilder = new MplsLabelCaseBuilder(); - mplsLabelCaseBuilder.setMplsLabel(mplsLabelBuilder.build()); - matchEntryBuilder.setMatchEntryValue(mplsLabelCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(MplsLabel.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - MplsTcBuilder mplsTcBuilder = new MplsTcBuilder(); - mplsTcBuilder.setTc((short) 0); - MplsTcCaseBuilder mplsTcCaseBuilder = new MplsTcCaseBuilder(); - mplsTcCaseBuilder.setMplsTc(mplsTcBuilder.build()); - matchEntryBuilder.setMatchEntryValue(mplsTcCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.MplsTc.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - MplsBosBuilder mplsBosBuilder = new MplsBosBuilder(); - mplsBosBuilder.setBos(false); - MplsBosCaseBuilder mplsBosCaseBuilder = new MplsBosCaseBuilder(); - mplsBosCaseBuilder.setMplsBos(mplsBosBuilder.build()); - matchEntryBuilder.setMatchEntryValue(mplsBosCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(MplsBos.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - PbbIsidBuilder pbbIsidBuilder = new PbbIsidBuilder(); - pbbIsidBuilder.setIsid((long) 42); - PbbIsidCaseBuilder pbbIsidCaseBuilder = new PbbIsidCaseBuilder(); - pbbIsidCaseBuilder.setPbbIsid(pbbIsidBuilder.build()); - matchEntryBuilder.setMatchEntryValue(pbbIsidCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(PbbIsid.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - TunnelIdBuilder tunnelIdBuilder = new TunnelIdBuilder(); - tunnelIdBuilder.setMask(new byte[0]); - tunnelIdBuilder.setTunnelId(new byte[42]); - TunnelIdCaseBuilder tunnelIdCaseBuilder = new TunnelIdCaseBuilder(); - tunnelIdCaseBuilder.setTunnelId(tunnelIdBuilder.build()); - matchEntryBuilder.setMatchEntryValue(tunnelIdCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(TunnelId.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - ArpTpaBuilder arpTpaBuilder = new ArpTpaBuilder(); - arpTpaBuilder.setIpv4Address(IPV_4_ADDRESS); - arpTpaBuilder.setMask(new byte[0]); - ArpTpaCaseBuilder arpTpaCaseBuilder = new ArpTpaCaseBuilder(); - arpTpaCaseBuilder.setArpTpa(arpTpaBuilder.build()); - matchEntryBuilder.setMatchEntryValue(arpTpaCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(ArpTpa.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - ArpSpaBuilder arpSpaBuilder = new ArpSpaBuilder(); - arpSpaBuilder.setMask(new byte[0]); - arpSpaBuilder.setIpv4Address(IPV_4_ADDRESS); - ArpSpaCaseBuilder arpSpaCaseBuilder = new ArpSpaCaseBuilder(); - arpSpaCaseBuilder.setArpSpa(arpSpaBuilder.build()); - matchEntryBuilder.setMatchEntryValue(arpSpaCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(ArpSpa.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - Ipv4SrcBuilder ipv4SrcBuilder = new Ipv4SrcBuilder(); - ipv4SrcBuilder.setIpv4Address(IPV_4_ADDRESS); - ipv4SrcBuilder.setMask(IPV_4_ADDRESS_MASK); - Ipv4SrcCaseBuilder ipv4SrcCaseBuilder = new Ipv4SrcCaseBuilder(); - ipv4SrcCaseBuilder.setIpv4Src(ipv4SrcBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ipv4SrcCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Ipv4Src.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - Ipv4DstBuilder ipv4DstBuilder = new Ipv4DstBuilder(); - ipv4DstBuilder.setIpv4Address(IPV_4_ADDRESS); - ipv4DstBuilder.setMask(IPV_4_ADDRESS_MASK); - Ipv4DstCaseBuilder ipv4DstCaseBuilder = new Ipv4DstCaseBuilder(); - ipv4DstCaseBuilder.setIpv4Dst(ipv4DstBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ipv4DstCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Ipv4Dst.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - - Ipv6SrcBuilder ipv6SrcBuilder = new Ipv6SrcBuilder(); - ipv6SrcBuilder.setIpv6Address(IPV_6_ADDRESS); - ipv6SrcBuilder.setMask(IPV_6_ADDRESS_MASK); - Ipv6SrcCaseBuilder ipv6SrcCaseBuilder = new Ipv6SrcCaseBuilder(); - ipv6SrcCaseBuilder.setIpv6Src(ipv6SrcBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ipv6SrcCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Ipv6Src.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - - Ipv6DstBuilder ipv6DstBuilder = new Ipv6DstBuilder(); - ipv6DstBuilder.setIpv6Address(IPV_6_ADDRESS); - ipv6DstBuilder.setMask(IPV_6_ADDRESS_MASK); - Ipv6DstCaseBuilder ipv6DstCaseBuilder = new Ipv6DstCaseBuilder(); - ipv6DstCaseBuilder.setIpv6Dst(ipv6DstBuilder.build()); - matchEntryBuilder.setMatchEntryValue(ipv6DstCaseBuilder.build()); - matchEntryBuilder.setOxmMatchField(Ipv6Dst.class); - fieldClassesAndAugmentations.add(matchEntryBuilder.build()); - } - - - @Before - public void setup() { - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - flowRemovedTranslator = new FlowRemovedTranslator(convertorManager); - when(sessionContext.getPrimaryConductor()).thenReturn(connectionConductor); - when(connectionConductor.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3); - when(sessionContext.getFeatures()).thenReturn(featuresOutput); - when(featuresOutput.getDatapathId()).thenReturn(DATA_PATH_ID); - ExtensionConverterManagerImpl extensionConverterProvider = new ExtensionConverterManagerImpl(); - //extensionConverterProvider.registerMatchConvertor() - SessionManagerOFImpl.getInstance().setExtensionConverterProvider(extensionConverterProvider); - } - - @Test - public void testTranslate() throws Exception { - List dataObjectList = flowRemovedTranslator.translate(switchConnectionDistinguisher, sessionContext, msg); - assertNotNull(dataObjectList); - } - - @Test - public void testFromMatch() throws Exception { - setupClassAndAugmentationMap(); - org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.MatchBuilder matchBuilder = new MatchBuilder(); - matchBuilder.setMatchEntry(fieldClassesAndAugmentations); - Match match = flowRemovedTranslator.fromMatch(matchBuilder.build(), DATA_PATH_ID, OpenflowVersion.OF13); - assertNotNull(match); - assertEthernetMatch(match.getEthernetMatch()); - assertIcmpV4Match(match.getIcmpv4Match()); - - assertEquals("openflow:42:42", match.getInPhyPort().getValue()); - assertEquals("openflow:42:42", match.getInPort().getValue()); - assertIpMatch(match.getIpMatch()); - - assertNotNull(match.getLayer3Match()); - assertNotNull(match.getLayer4Match()); - - assertProtocolMatchFields(match.getProtocolMatchFields()); - - assertMetada(match.getMetadata()); - - assertTunnelMatch(match.getTunnel()); - - assertVlanMatch(match.getVlanMatch()); - } - - private static void assertTunnelMatch(final Tunnel tunnel) { - assertEquals(0, tunnel.getTunnelId().intValue()); - } - - private static void assertVlanMatch(final VlanMatch vlanMatch) { - assertEquals(true, vlanMatch.getVlanId().isVlanIdPresent()); - assertEquals(new Integer(42), vlanMatch.getVlanId().getVlanId().getValue()); - - assertEquals((short) 7, vlanMatch.getVlanPcp().getValue().shortValue()); - } - - private static void assertMetada(final org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.Metadata metadata) { - assertEquals(0, metadata.getMetadata().intValue()); - } - - private static void assertProtocolMatchFields(final ProtocolMatchFields protocolMatchFields) { - assertEquals((short) 0, protocolMatchFields.getMplsBos().shortValue()); - assertEquals(42, protocolMatchFields.getMplsLabel().longValue()); - assertEquals((short) 0, protocolMatchFields.getMplsTc().shortValue()); - assertEquals(42, protocolMatchFields.getPbb().getPbbIsid().longValue()); - } - - private static void assertIpMatch(final IpMatch ipMatch) { - assertEquals(10, ipMatch.getIpDscp().getValue().longValue()); - assertEquals(10, ipMatch.getIpEcn().shortValue()); - assertEquals(4, ipMatch.getIpProtocol().shortValue()); - } - - private static void assertIcmpV4Match(final Icmpv4Match icmpv4Match) { - assertEquals(10, icmpv4Match.getIcmpv4Code().longValue()); - assertEquals(10, icmpv4Match.getIcmpv4Type().longValue()); - } - - private static void assertEthernetMatch(final EthernetMatch ethernetMatch) { - assertEquals(MAC_ADDRESS, ethernetMatch.getEthernetDestination().getAddress()); - assertEquals(MAC_ADDRESS, ethernetMatch.getEthernetSource().getAddress()); - assertEquals(new Long(6), ethernetMatch.getEthernetType().getType().getValue()); - } - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartMessageDescToNodeUpdatedTranslatorTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartMessageDescToNodeUpdatedTranslatorTest.java deleted file mode 100644 index 908475c22e..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartMessageDescToNodeUpdatedTranslatorTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.translator; - -import static org.mockito.Mockito.when; - -import java.math.BigInteger; -import java.util.List; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyDescCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.desc._case.MultipartReplyDescBuilder; -import org.opendaylight.yangtools.yang.binding.DataObject; - -/** - * @author michal.polkorab - * - */ -public class MultiPartMessageDescToNodeUpdatedTranslatorTest { - - @Mock SwitchConnectionDistinguisher cookie; - @Mock SessionContext sc; - @Mock GetFeaturesOutput features; - - MultiPartMessageDescToNodeUpdatedTranslator translator = new MultiPartMessageDescToNodeUpdatedTranslator(); - - /** - * Initializes mocks - */ - @Before - public void startUp() { - MockitoAnnotations.initMocks(this); - when(sc.getFeatures()).thenReturn(features); - when(features.getDatapathId()).thenReturn(new BigInteger("42")); - } - - /** - * Test {@link MultiPartMessageDescToNodeUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with wrong inputs - */ - @Test - public void testWrongInputs() { - HelloMessageBuilder helloBuilder = new HelloMessageBuilder(); - HelloMessage helloMessage = helloBuilder.build(); - List list = translator.translate(cookie, sc, helloMessage); - Assert.assertEquals("Wrong output", 0, list.size()); - - MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder(); - builder.setType(MultipartType.OFPMPFLOW); - MultipartReplyMessage message = builder.build(); - list = translator.translate(cookie, sc, message); - Assert.assertEquals("Wrong output", 0, list.size()); - } - - /** - * Test {@link MultiPartMessageDescToNodeUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with correct input - */ - @Test - public void testCorrectInput() { - MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder(); - builder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - builder.setXid(12345L); - builder.setType(MultipartType.OFPMPDESC); - builder.setFlags(new MultipartRequestFlags(false)); - - MultipartReplyDescCaseBuilder caseBuilder = new MultipartReplyDescCaseBuilder(); - MultipartReplyDescBuilder descBuilder = new MultipartReplyDescBuilder(); - descBuilder.setMfrDesc("Collaboration ltd."); - descBuilder.setHwDesc("Simple switch"); - descBuilder.setSwDesc("Best software ever inside"); - descBuilder.setSerialNum("123456789"); - descBuilder.setDpDesc("0000000000000001"); - caseBuilder.setMultipartReplyDesc(descBuilder.build()); - builder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = builder.build(); - - List list = translator.translate(cookie, sc, message); - Assert.assertEquals("Wrong output", 1, list.size()); - NodeUpdated nodeUpdated = (NodeUpdated) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", nodeUpdated.getId().getValue()); - FlowCapableNodeUpdated flowCapable = nodeUpdated.getAugmentation(FlowCapableNodeUpdated.class); - Assert.assertEquals("Wrong manufacturer", "Collaboration ltd.", flowCapable.getManufacturer()); - Assert.assertEquals("Wrong hardware", "Simple switch", flowCapable.getHardware()); - Assert.assertEquals("Wrong software", "Best software ever inside", flowCapable.getSoftware()); - Assert.assertEquals("Wrong serial number", "123456789", flowCapable.getSerialNumber()); - Assert.assertEquals("Wrong datapath description", "0000000000000001", flowCapable.getDescription()); - } -} \ No newline at end of file diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartReplyPortToNodeConnectorUpdatedTranslatorTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartReplyPortToNodeConnectorUpdatedTranslatorTest.java deleted file mode 100644 index 8caa537167..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultiPartReplyPortToNodeConnectorUpdatedTranslatorTest.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.translator; - -import static org.mockito.Mockito.when; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnectorUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortConfig; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortState; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyPortDescCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.MultipartReplyPortDescBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.multipart.reply.port.desc.Ports; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.multipart.reply.port.desc.PortsBuilder; -import org.opendaylight.yangtools.yang.binding.DataObject; - -/** - * @author michal.polkorab - * - */ -public class MultiPartReplyPortToNodeConnectorUpdatedTranslatorTest { - - @Mock SwitchConnectionDistinguisher cookie; - @Mock SessionContext sc; - @Mock GetFeaturesOutput features; - - MultiPartReplyPortToNodeConnectorUpdatedTranslator translator = new MultiPartReplyPortToNodeConnectorUpdatedTranslator(); - - /** - * Initializes mocks - */ - @Before - public void startUp() { - MockitoAnnotations.initMocks(this); - when(sc.getFeatures()).thenReturn(features); - when(features.getDatapathId()).thenReturn(new BigInteger("42")); - } - - /** - * Test {@link MultiPartReplyPortToNodeConnectorUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with wrong inputs - */ - @Test - public void testWrongInputs() { - HelloMessageBuilder helloBuilder = new HelloMessageBuilder(); - HelloMessage helloMessage = helloBuilder.build(); - List list = translator.translate(cookie, sc, helloMessage); - Assert.assertEquals("Wrong output", 0, list.size()); - - MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder(); - builder.setType(MultipartType.OFPMPFLOW); - MultipartReplyMessage message = builder.build(); - list = translator.translate(cookie, sc, message); - Assert.assertEquals("Wrong output", 0, list.size()); - } - - /** - * Test {@link MultiPartReplyPortToNodeConnectorUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with correct input (no ports) - */ - @Test - public void testEmptyPortDescWithCorrectInput() { - MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder(); - builder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - builder.setXid(12345L); - builder.setType(MultipartType.OFPMPPORTDESC); - builder.setFlags(new MultipartRequestFlags(false)); - - MultipartReplyPortDescCaseBuilder caseBuilder = new MultipartReplyPortDescCaseBuilder(); - MultipartReplyPortDescBuilder descBuilder = new MultipartReplyPortDescBuilder(); - List ports = new ArrayList<>(); - descBuilder.setPorts(ports); - caseBuilder.setMultipartReplyPortDesc(descBuilder.build()); - builder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = builder.build(); - - List list = translator.translate(cookie, sc, message); - Assert.assertEquals("Wrong output", 0, list.size()); - } - - /** - * Test {@link MultiPartReplyPortToNodeConnectorUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with correct input - */ - @Test - public void testPortDescWithCorrectInput() { - MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder(); - builder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - builder.setXid(12345L); - builder.setType(MultipartType.OFPMPPORTDESC); - builder.setFlags(new MultipartRequestFlags(false)); - - MultipartReplyPortDescCaseBuilder caseBuilder = new MultipartReplyPortDescCaseBuilder(); - MultipartReplyPortDescBuilder descBuilder = new MultipartReplyPortDescBuilder(); - List ports = new ArrayList<>(); - PortsBuilder portBuilder = new PortsBuilder(); - portBuilder.setPortNo(5L); - portBuilder.setHwAddr(new MacAddress("06:07:08:09:0A:0B")); - portBuilder.setName("MultipartPortDesc port"); - portBuilder.setConfig(new PortConfig(true, false, true, false)); - portBuilder.setState(new PortState(true, false, true)); - portBuilder.setCurrentFeatures(new PortFeatures(false, true, false, true, - false, true, false, true, false, true, false, true, false, true, false, true)); - portBuilder.setAdvertisedFeatures(new PortFeatures(true, false, true, false, true, - false, true, false, true, false, true, false, true, false, true, false)); - portBuilder.setSupportedFeatures(new PortFeatures(false, false, false, false, false, - false, false, false, false, false, false, false, false, false, false, false)); - portBuilder.setPeerFeatures(new PortFeatures(true, true, true, true, true, - true, true, true, true, true, true, true, true, true, true, true)); - portBuilder.setCurrSpeed(12L); - portBuilder.setMaxSpeed(13L); - ports.add(portBuilder.build()); - portBuilder = new PortsBuilder(); - portBuilder.setPortNo(50L); - portBuilder.setHwAddr(new MacAddress("05:06:07:08:09:0A")); - portBuilder.setName("MultipartPortDesc port"); - portBuilder.setConfig(new PortConfig(false, true, false, true)); - portBuilder.setState(new PortState(false, true, false)); - portBuilder.setCurrentFeatures(null); - portBuilder.setAdvertisedFeatures(null); - portBuilder.setSupportedFeatures(null); - portBuilder.setPeerFeatures(null); - portBuilder.setCurrSpeed(120L); - portBuilder.setMaxSpeed(130L); - ports.add(portBuilder.build()); - descBuilder.setPorts(ports); - caseBuilder.setMultipartReplyPortDesc(descBuilder.build()); - builder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = builder.build(); - - List list = translator.translate(cookie, sc, message); - Assert.assertEquals("Wrong output", 2, list.size()); - NodeConnectorUpdated nodeUpdated = (NodeConnectorUpdated) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42:5", nodeUpdated.getId().getValue()); - FlowCapableNodeConnectorUpdated flowCapable = nodeUpdated.getAugmentation(FlowCapableNodeConnectorUpdated.class); - Assert.assertEquals("Wrong port number", 5, flowCapable.getPortNumber().getUint32().intValue()); - Assert.assertEquals("Wrong hardware address", new MacAddress("06:07:08:09:0A:0B"), flowCapable.getHardwareAddress()); - Assert.assertEquals("Wrong name", "MultipartPortDesc port", flowCapable.getName()); - Assert.assertEquals("Wrong config", true, flowCapable.getConfiguration().isNOFWD()); - Assert.assertEquals("Wrong config", false, flowCapable.getConfiguration().isNOPACKETIN()); - Assert.assertEquals("Wrong config", true, flowCapable.getConfiguration().isNORECV()); - Assert.assertEquals("Wrong config", false, flowCapable.getConfiguration().isPORTDOWN()); - Assert.assertEquals("Wrong state", true, flowCapable.getState().isBlocked()); - Assert.assertEquals("Wrong state", false, flowCapable.getState().isLinkDown()); - Assert.assertEquals("Wrong state", true, flowCapable.getState().isLive()); - Assert.assertEquals("Wrong current features", new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port - .rev130925.PortFeatures(false, true, false, true, false, true, false, false, true, false, true, false, - true, true, false, true), flowCapable.getCurrentFeature()); - Assert.assertEquals("Wrong advertised features", new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port - .rev130925.PortFeatures(true, false, true, false, true, false, true, true, false, true, false, true, - false, false, true, false), flowCapable.getAdvertisedFeatures()); - Assert.assertEquals("Wrong supported features", new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port - .rev130925.PortFeatures(false, false, false, false, false, false, false, false, false, false, false, false, - false, false, false, false), flowCapable.getSupported()); - Assert.assertEquals("Wrong peer features", new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port - .rev130925.PortFeatures(true, true, true, true, true, true, true, true, true, true, true, true, - true, true, true, true), flowCapable.getPeerFeatures()); - Assert.assertEquals("Wrong current speed", 12, flowCapable.getCurrentSpeed().intValue()); - Assert.assertEquals("Wrong max speed", 13, flowCapable.getMaximumSpeed().intValue()); - nodeUpdated = (NodeConnectorUpdated) list.get(1); - Assert.assertEquals("Wrong node-id", "openflow:42:50", nodeUpdated.getId().getValue()); - flowCapable = nodeUpdated.getAugmentation(FlowCapableNodeConnectorUpdated.class); - Assert.assertEquals("Wrong port number", 50, flowCapable.getPortNumber().getUint32().intValue()); - Assert.assertEquals("Wrong hardware address", new MacAddress("05:06:07:08:09:0A"), flowCapable.getHardwareAddress()); - Assert.assertEquals("Wrong name", "MultipartPortDesc port", flowCapable.getName()); - Assert.assertEquals("Wrong config", false, flowCapable.getConfiguration().isNOFWD()); - Assert.assertEquals("Wrong config", true, flowCapable.getConfiguration().isNOPACKETIN()); - Assert.assertEquals("Wrong config", false, flowCapable.getConfiguration().isNORECV()); - Assert.assertEquals("Wrong config", true, flowCapable.getConfiguration().isPORTDOWN()); - Assert.assertEquals("Wrong state", false, flowCapable.getState().isBlocked()); - Assert.assertEquals("Wrong state", true, flowCapable.getState().isLinkDown()); - Assert.assertEquals("Wrong state", false, flowCapable.getState().isLive()); - Assert.assertEquals("Wrong current features", null, flowCapable.getCurrentFeature()); - Assert.assertEquals("Wrong advertised features", null, flowCapable.getAdvertisedFeatures()); - Assert.assertEquals("Wrong supported features", null, flowCapable.getSupported()); - Assert.assertEquals("Wrong peer features", null, flowCapable.getPeerFeatures()); - Assert.assertEquals("Wrong current speed", 120, flowCapable.getCurrentSpeed().intValue()); - Assert.assertEquals("Wrong max speed", 130, flowCapable.getMaximumSpeed().intValue()); - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTableFeaturesToTableUpdatedTranslatorTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTableFeaturesToTableUpdatedTranslatorTest.java deleted file mode 100644 index bb046425da..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTableFeaturesToTableUpdatedTranslatorTest.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.translator; - -import static org.mockito.Mockito.when; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants; -import org.opendaylight.openflowplugin.api.OFConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.augments.rev150225.NextTableRelatedTableFeatureProperty; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.augments.rev150225.NextTableRelatedTableFeaturePropertyBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.augments.rev150225.table.features.properties.container.table.feature.properties.NextTableIds; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.augments.rev150225.table.features.properties.container.table.feature.properties.NextTableIdsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.TableConfig; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.TableFeaturesPropType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableFeaturesCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.MultipartReplyTableFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.multipart.reply.table.features.TableFeatures; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.multipart.reply.table.features.TableFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.table.features.properties.grouping.TableFeatureProperties; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.table.features.properties.grouping.TableFeaturePropertiesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.TableUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.feature.prop.type.table.feature.prop.type.NextTable; -import org.opendaylight.yangtools.yang.binding.DataObject; - -/** - * @author michal.polkorab - * - */ -@RunWith(MockitoJUnitRunner.class) -public class MultipartReplyTableFeaturesToTableUpdatedTranslatorTest { - - @Mock SwitchConnectionDistinguisher cookie; - @Mock SessionContext sc; - @Mock GetFeaturesOutput features; - @Mock ConnectionConductor conductor; - - MultipartReplyTableFeaturesToTableUpdatedTranslator translator; - - /** - * Initializes mocks - */ - @Before - public void startUp() { - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - translator = new MultipartReplyTableFeaturesToTableUpdatedTranslator(convertorManager); - when(sc.getPrimaryConductor()).thenReturn(conductor); - when(sc.getFeatures()).thenReturn(features); - when(conductor.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3); - when(features.getDatapathId()).thenReturn(new BigInteger("42")); - } - - /** - * Test {@link MultipartReplyTableFeaturesToTableUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with wrong inputs - */ - @Test - public void testWrongInputs() { - HelloMessageBuilder helloBuilder = new HelloMessageBuilder(); - HelloMessage helloMessage = helloBuilder.build(); - List list = translator.translate(cookie, sc, helloMessage); - Assert.assertEquals("Wrong output", 0, list.size()); - - MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder(); - builder.setType(MultipartType.OFPMPFLOW); - MultipartReplyMessage message = builder.build(); - list = translator.translate(cookie, sc, message); - Assert.assertEquals("Wrong output", 0, list.size()); - } - - /** - * Test {@link MultipartReplyTableFeaturesToTableUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with correct inputs (no table features) - */ - @Test - public void testEmptyTableFeaturesWithCorrectInput() { - MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder(); - builder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - builder.setXid(12345L); - builder.setType(MultipartType.OFPMPTABLEFEATURES); - builder.setFlags(new MultipartRequestFlags(false)); - - MultipartReplyTableFeaturesCaseBuilder caseBuilder = new MultipartReplyTableFeaturesCaseBuilder(); - MultipartReplyTableFeaturesBuilder featuresBuilder = new MultipartReplyTableFeaturesBuilder(); - List features = new ArrayList<>(); - featuresBuilder.setTableFeatures(features); - caseBuilder.setMultipartReplyTableFeatures(featuresBuilder.build()); - builder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = builder.build(); - - List list = translator.translate(cookie, sc, message); - Assert.assertEquals("Wrong output", 1, list.size()); - TableUpdated tableUpdated = (TableUpdated) list.get(0); - Assert.assertEquals("Wrong table features size", 0, tableUpdated.getTableFeatures().size()); - } - - /** - * Test {@link MultipartReplyTableFeaturesToTableUpdatedTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with correct inputs - */ - @Test - public void testTableFeaturesWithCorrectInput() { - MultipartReplyMessageBuilder builder = new MultipartReplyMessageBuilder(); - builder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - builder.setXid(12345L); - builder.setType(MultipartType.OFPMPTABLEFEATURES); - builder.setFlags(new MultipartRequestFlags(false)); - - MultipartReplyTableFeaturesCaseBuilder caseBuilder = new MultipartReplyTableFeaturesCaseBuilder(); - MultipartReplyTableFeaturesBuilder featuresBuilder = new MultipartReplyTableFeaturesBuilder(); - List features = new ArrayList<>(); - - TableFeaturesBuilder tableFeatBuilder = new TableFeaturesBuilder(); - tableFeatBuilder.setTableId((short) 2); - tableFeatBuilder.setName("Fastest table in the world"); - byte[] metadataMatch = new byte[]{0, 1, 2, 3, 4, 5, 6, 7}; - tableFeatBuilder.setMetadataMatch(metadataMatch); - byte[] metadataWrite = new byte[]{1, 2, 3, 4, 5, 6, 7, 8}; - tableFeatBuilder.setMetadataWrite(metadataWrite); - tableFeatBuilder.setConfig(new TableConfig(false)); - tableFeatBuilder.setMaxEntries(10L); - List properties = new ArrayList<>(); - TableFeaturePropertiesBuilder propBuilder = new TableFeaturePropertiesBuilder(); - propBuilder.setType(TableFeaturesPropType.OFPTFPTNEXTTABLES); - NextTableRelatedTableFeaturePropertyBuilder tableBuilder = new NextTableRelatedTableFeaturePropertyBuilder(); - List tableIds = new ArrayList<>(); - NextTableIdsBuilder nextTableIdsBuilder = new NextTableIdsBuilder(); - nextTableIdsBuilder.setTableId((short) 9); - tableIds.add(nextTableIdsBuilder.build()); - nextTableIdsBuilder = new NextTableIdsBuilder(); - nextTableIdsBuilder.setTableId((short) 10); - tableIds.add(nextTableIdsBuilder.build()); - nextTableIdsBuilder = new NextTableIdsBuilder(); - nextTableIdsBuilder.setTableId((short) 11); - tableIds.add(nextTableIdsBuilder.build()); - tableBuilder.setNextTableIds(tableIds); - propBuilder.addAugmentation(NextTableRelatedTableFeatureProperty.class, tableBuilder.build()); - properties.add(propBuilder.build()); - tableFeatBuilder.setTableFeatureProperties(properties); - features.add(tableFeatBuilder.build()); - featuresBuilder.setTableFeatures(features); - caseBuilder.setMultipartReplyTableFeatures(featuresBuilder.build()); - builder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = builder.build(); - - List list = translator.translate(cookie, sc, message); - Assert.assertEquals("Wrong output", 1, list.size()); - TableUpdated tableUpdated = (TableUpdated) list.get(0); - Assert.assertEquals("Wrong table features size", 1, tableUpdated.getTableFeatures().size()); - org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features - .TableFeatures feature = tableUpdated.getTableFeatures().get(0); - Assert.assertEquals("Wrong table-id", 2, feature.getTableId().intValue()); - Assert.assertEquals("Wrong table name", "Fastest table in the world", feature.getName()); - Assert.assertEquals("Wrong metadata match", new BigInteger(metadataMatch), feature.getMetadataMatch()); - Assert.assertEquals("Wrong metadata write", new BigInteger(metadataWrite), feature.getMetadataWrite()); - Assert.assertEquals("Wrong config", false, feature.getConfig().isDEPRECATEDMASK()); - Assert.assertEquals("Wrong max entries", 10, feature.getMaxEntries().intValue()); - Assert.assertEquals("Wrong properties size", 1, feature.getTableProperties().getTableFeatureProperties().size()); - org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.table.features.table.properties - .TableFeatureProperties property = feature.getTableProperties().getTableFeatureProperties().get(0); - Assert.assertEquals("Wrong property type", "org.opendaylight.yang.gen.v1.urn.opendaylight.table.types" - + ".rev131026.table.feature.prop.type.table.feature.prop.type.NextTable", - property.getTableFeaturePropType().getImplementedInterface().getName()); - NextTable nextTableProperty = (NextTable) property.getTableFeaturePropType(); - Assert.assertEquals("Wrong next tables size", 3, nextTableProperty.getTables().getTableIds().size()); - Assert.assertEquals("Wrong next tables size", 9, nextTableProperty.getTables().getTableIds().get(0).intValue()); - Assert.assertEquals("Wrong next tables size", 10, nextTableProperty.getTables().getTableIds().get(1).intValue()); - Assert.assertEquals("Wrong next tables size", 11, nextTableProperty.getTables().getTableIds().get(2).intValue()); - } -} \ No newline at end of file diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorFifthTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorFifthTest.java deleted file mode 100644 index 6413795b4f..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorFifthTest.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.translator; - -import static org.mockito.Mockito.when; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterConfigStatsUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterStatisticsUpdated; -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.meter.band.headers.MeterBandHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MeterBandType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MeterFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MeterId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.meter.band.header.meter.band.MeterBandDropCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.meter.band.header.meter.band.MeterBandDscpRemarkCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.meter.band.header.meter.band.meter.band.drop._case.MeterBandDropBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.meter.band.header.meter.band.meter.band.dscp.remark._case.MeterBandDscpRemarkBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterConfigCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter._case.MultipartReplyMeterBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter._case.multipart.reply.meter.MeterStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter._case.multipart.reply.meter.MeterStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter._case.multipart.reply.meter.meter.stats.MeterBandStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter._case.multipart.reply.meter.meter.stats.MeterBandStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.config._case.MultipartReplyMeterConfigBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.config._case.multipart.reply.meter.config.MeterConfig; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.config._case.multipart.reply.meter.config.MeterConfigBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.config._case.multipart.reply.meter.config.meter.config.Bands; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.config._case.multipart.reply.meter.config.meter.config.BandsBuilder; -import org.opendaylight.yangtools.yang.binding.DataObject; - -/** - * @author michal.polkorab - */ -@RunWith(MockitoJUnitRunner.class) -public class MultipartReplyTranslatorFifthTest { - - @Mock - SwitchConnectionDistinguisher cookie; - @Mock - SessionContext sc; - @Mock - ConnectionConductor conductor; - @Mock - GetFeaturesOutput features; - - MultipartReplyTranslator translator; - - /** - * Initializes mocks - */ - @Before - public void startUp() { - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - translator = new MultipartReplyTranslator(convertorManager); - MockitoAnnotations.initMocks(this); - when(sc.getPrimaryConductor()).thenReturn(conductor); - when(conductor.getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID); - when(sc.getFeatures()).thenReturn(features); - when(features.getDatapathId()).thenReturn(new BigInteger("42")); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with empty meter stats - */ - @Test - public void testEmptyMeterStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPMETER); - - MultipartReplyMeterCaseBuilder caseBuilder = new MultipartReplyMeterCaseBuilder(); - MultipartReplyMeterBuilder meterBuilder = new MultipartReplyMeterBuilder(); - List meterStats = new ArrayList<>(); - meterBuilder.setMeterStats(meterStats); - caseBuilder.setMultipartReplyMeter(meterBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - MeterStatisticsUpdated statUpdate = (MeterStatisticsUpdated) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong meter stats size", 0, statUpdate.getMeterStats().size()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with meter stats - */ - @Test - public void testMeterStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPMETER); - - MultipartReplyMeterCaseBuilder caseBuilder = new MultipartReplyMeterCaseBuilder(); - MultipartReplyMeterBuilder meterBuilder = new MultipartReplyMeterBuilder(); - List meterStats = new ArrayList<>(); - MeterStatsBuilder builder = new MeterStatsBuilder(); - builder.setMeterId(new MeterId(15L)); - builder.setFlowCount(16L); - builder.setPacketInCount(new BigInteger("17")); - builder.setByteInCount(new BigInteger("18")); - builder.setDurationSec(19L); - builder.setDurationNsec(20L); - List meterBands = new ArrayList<>(); - MeterBandStatsBuilder meterStatsBuilder = new MeterBandStatsBuilder(); - meterStatsBuilder.setPacketBandCount(new BigInteger("21")); - meterStatsBuilder.setByteBandCount(new BigInteger("22")); - meterBands.add(meterStatsBuilder.build()); - meterStatsBuilder = new MeterBandStatsBuilder(); - meterStatsBuilder.setPacketBandCount(new BigInteger("23")); - meterStatsBuilder.setByteBandCount(new BigInteger("24")); - meterBands.add(meterStatsBuilder.build()); - builder.setMeterBandStats(meterBands); - meterStats.add(builder.build()); - builder = new MeterStatsBuilder(); - builder.setMeterId(new MeterId(150L)); - builder.setFlowCount(160L); - builder.setPacketInCount(new BigInteger("170")); - builder.setByteInCount(new BigInteger("180")); - builder.setDurationSec(190L); - builder.setDurationNsec(200L); - meterBands = new ArrayList<>(); - builder.setMeterBandStats(meterBands); - meterStats.add(builder.build()); - meterBuilder.setMeterStats(meterStats); - caseBuilder.setMultipartReplyMeter(meterBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - MeterStatisticsUpdated statUpdate = (MeterStatisticsUpdated) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong group stats size", 2, statUpdate.getMeterStats().size()); - org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.statistics.reply - .MeterStats stat = statUpdate.getMeterStats().get(0); - Assert.assertEquals("Wrong meter-id", 15, stat.getMeterId().getValue().intValue()); - Assert.assertEquals("Wrong flow count", 16, stat.getFlowCount().getValue().intValue()); - Assert.assertEquals("Wrong packet in count", 17, stat.getPacketInCount().getValue().intValue()); - Assert.assertEquals("Wrong byte in count", 18, stat.getByteInCount().getValue().intValue()); - Assert.assertEquals("Wrong duration sec", 19, stat.getDuration().getSecond().getValue().intValue()); - Assert.assertEquals("Wrong duration n sec", 20, stat.getDuration().getNanosecond().getValue().intValue()); - Assert.assertEquals("Wrong meter band stats size", 2, stat.getMeterBandStats().getBandStat().size()); - Assert.assertEquals("Wrong band id", 0, stat.getMeterBandStats().getBandStat().get(0) - .getBandId().getValue().intValue()); - Assert.assertEquals("Wrong packet band count", 21, stat.getMeterBandStats().getBandStat().get(0) - .getPacketBandCount().getValue().intValue()); - Assert.assertEquals("Wrong byte band count", 22, stat.getMeterBandStats().getBandStat().get(0) - .getByteBandCount().getValue().intValue()); - Assert.assertEquals("Wrong band id", 1, stat.getMeterBandStats().getBandStat().get(1) - .getBandId().getValue().intValue()); - Assert.assertEquals("Wrong packet band count", 23, stat.getMeterBandStats().getBandStat().get(1) - .getPacketBandCount().getValue().intValue()); - Assert.assertEquals("Wrong byte band count", 24, stat.getMeterBandStats().getBandStat().get(1) - .getByteBandCount().getValue().intValue()); - stat = statUpdate.getMeterStats().get(1); - Assert.assertEquals("Wrong meter-id", 150, stat.getMeterId().getValue().intValue()); - Assert.assertEquals("Wrong flow count", 160, stat.getFlowCount().getValue().intValue()); - Assert.assertEquals("Wrong packet in count", 170, stat.getPacketInCount().getValue().intValue()); - Assert.assertEquals("Wrong byte in count", 180, stat.getByteInCount().getValue().intValue()); - Assert.assertEquals("Wrong duration sec", 190, stat.getDuration().getSecond().getValue().intValue()); - Assert.assertEquals("Wrong duration n sec", 200, stat.getDuration().getNanosecond().getValue().intValue()); - Assert.assertEquals("Wrong meter band stats size", 0, stat.getMeterBandStats().getBandStat().size()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with empty meter config stats - */ - @Test - public void testEmptyMeterConfigStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPMETERCONFIG); - - MultipartReplyMeterConfigCaseBuilder caseBuilder = new MultipartReplyMeterConfigCaseBuilder(); - MultipartReplyMeterConfigBuilder meterBuilder = new MultipartReplyMeterConfigBuilder(); - List meterStats = new ArrayList<>(); - meterBuilder.setMeterConfig(meterStats); - caseBuilder.setMultipartReplyMeterConfig(meterBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - MeterConfigStatsUpdated statUpdate = (MeterConfigStatsUpdated) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong meter config stats size", 0, statUpdate.getMeterConfigStats().size()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with meter config stats - */ - @Test - public void testMeterConfigStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPMETERCONFIG); - - MultipartReplyMeterConfigCaseBuilder caseBuilder = new MultipartReplyMeterConfigCaseBuilder(); - MultipartReplyMeterConfigBuilder meterBuilder = new MultipartReplyMeterConfigBuilder(); - List meterStats = new ArrayList<>(); - MeterConfigBuilder builder = new MeterConfigBuilder(); - builder.setFlags(new MeterFlags(false, true, false, true)); - builder.setMeterId(new MeterId(20L)); - List bands = new ArrayList<>(); - BandsBuilder bandBuilder = new BandsBuilder(); - MeterBandDropCaseBuilder dropCaseBuilder = new MeterBandDropCaseBuilder(); - MeterBandDropBuilder dropBuilder = new MeterBandDropBuilder(); - dropBuilder.setType(MeterBandType.OFPMBTDROP); - dropBuilder.setRate(21L); - dropBuilder.setBurstSize(22L); - dropCaseBuilder.setMeterBandDrop(dropBuilder.build()); - bandBuilder.setMeterBand(dropCaseBuilder.build()); - bands.add(bandBuilder.build()); - bandBuilder = new BandsBuilder(); - MeterBandDscpRemarkCaseBuilder dscpCaseBuilder = new MeterBandDscpRemarkCaseBuilder(); - MeterBandDscpRemarkBuilder dscpBuilder = new MeterBandDscpRemarkBuilder(); - dscpBuilder.setType(MeterBandType.OFPMBTDSCPREMARK); - dscpBuilder.setRate(23L); - dscpBuilder.setBurstSize(24L); - dscpBuilder.setPrecLevel((short) 25); - dscpCaseBuilder.setMeterBandDscpRemark(dscpBuilder.build()); - bandBuilder.setMeterBand(dscpCaseBuilder.build()); - bands.add(bandBuilder.build()); - builder.setBands(bands); - meterStats.add(builder.build()); - builder = new MeterConfigBuilder(); - builder.setFlags(new MeterFlags(true, false, true, false)); - builder.setMeterId(new MeterId(26L)); - bands = new ArrayList<>(); - builder.setBands(bands); - meterStats.add(builder.build()); - meterBuilder.setMeterConfig(meterStats); - caseBuilder.setMultipartReplyMeterConfig(meterBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - MeterConfigStatsUpdated statUpdate = (MeterConfigStatsUpdated) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong meter config stats size", 2, statUpdate.getMeterConfigStats().size()); - MeterConfigStats stat = statUpdate.getMeterConfigStats().get(0); - Assert.assertEquals("Wrong flag", false, stat.getFlags().isMeterBurst()); - Assert.assertEquals("Wrong flag", false, stat.getFlags().isMeterPktps()); - Assert.assertEquals("Wrong flag", true, stat.getFlags().isMeterKbps()); - Assert.assertEquals("Wrong flag", true, stat.getFlags().isMeterStats()); - Assert.assertEquals("Wrong meter-id", 20, stat.getMeterId().getValue().intValue()); - Assert.assertEquals("Wrong bands size", 2, stat.getMeterBandHeaders().getMeterBandHeader().size()); - MeterBandHeader header = stat.getMeterBandHeaders().getMeterBandHeader().get(0); - Assert.assertEquals("Wrong band type", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter" - + ".types.rev130918.band.type.band.type.Drop", header.getBandType().getImplementedInterface().getName()); - Assert.assertEquals("Wrong band rate", 21, header.getBandRate().intValue()); - Assert.assertEquals("Wrong band burst size", 22, header.getBandBurstSize().intValue()); - Assert.assertEquals("Wrong flag", true, header.getMeterBandTypes().getFlags().isOfpmbtDrop()); - Assert.assertEquals("Wrong flag", false, header.getMeterBandTypes().getFlags().isOfpmbtDscpRemark()); - Assert.assertEquals("Wrong flag", false, header.getMeterBandTypes().getFlags().isOfpmbtExperimenter()); - header = stat.getMeterBandHeaders().getMeterBandHeader().get(1); - Assert.assertEquals("Wrong band type", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter" - + ".types.rev130918.band.type.band.type.DscpRemark", header.getBandType().getImplementedInterface().getName()); - Assert.assertEquals("Wrong band rate", 23, header.getBandRate().intValue()); - Assert.assertEquals("Wrong band burst size", 24, header.getBandBurstSize().intValue()); - Assert.assertEquals("Wrong flag", false, header.getMeterBandTypes().getFlags().isOfpmbtDrop()); - Assert.assertEquals("Wrong flag", true, header.getMeterBandTypes().getFlags().isOfpmbtDscpRemark()); - Assert.assertEquals("Wrong flag", false, header.getMeterBandTypes().getFlags().isOfpmbtExperimenter()); - stat = statUpdate.getMeterConfigStats().get(1); - Assert.assertEquals("Wrong flag", true, stat.getFlags().isMeterBurst()); - Assert.assertEquals("Wrong flag", true, stat.getFlags().isMeterPktps()); - Assert.assertEquals("Wrong flag", false, stat.getFlags().isMeterKbps()); - Assert.assertEquals("Wrong flag", false, stat.getFlags().isMeterStats()); - Assert.assertEquals("Wrong meter-id", 26, stat.getMeterId().getValue().intValue()); - Assert.assertEquals("Wrong bands size", 0, stat.getMeterBandHeaders().getMeterBandHeader().size()); - } -} \ No newline at end of file diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorFirstTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorFirstTest.java deleted file mode 100644 index f4051a80c8..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorFirstTest.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.translator; - -import static org.mockito.Mockito.when; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowsStatisticsUpdate; -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.types.rev131026.flow.Match; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.instruction.rev130731.instructions.grouping.Instruction; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.FlowModFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.OxmMatchType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntry; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.MatchBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyFlowCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.flow._case.MultipartReplyFlowBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.flow._case.multipart.reply.flow.FlowStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.flow._case.multipart.reply.flow.FlowStatsBuilder; -import org.opendaylight.yangtools.yang.binding.DataObject; - -/** - * @author michal.polkorab - * - */ -@RunWith(MockitoJUnitRunner.class) -public class MultipartReplyTranslatorFirstTest { - - @Mock SwitchConnectionDistinguisher cookie; - @Mock SessionContext sc; - @Mock ConnectionConductor conductor; - @Mock GetFeaturesOutput features; - - MultipartReplyTranslator translator; - - /** - * Initializes mocks - */ - @Before - public void startUp() { - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - translator = new MultipartReplyTranslator(convertorManager); - when(sc.getPrimaryConductor()).thenReturn(conductor); - when(conductor.getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID); - when(sc.getFeatures()).thenReturn(features); - when(features.getDatapathId()).thenReturn(new BigInteger("42")); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with null and incorrect message - */ - @Test - public void test() { - List list = translator.translate(cookie, sc, null); - - Assert.assertEquals("Wrong list size", 0, list.size()); - HelloMessageBuilder helloBuilder = new HelloMessageBuilder(); - list = translator.translate(cookie, sc, helloBuilder.build()); - Assert.assertEquals("Wrong list size", 0, list.size()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with experimenter MultipartReply message - */ - @Test - public void testExperimenterCase() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPEXPERIMENTER); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 0, list.size()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with empty flow stats - */ - @Test - public void testEmptyFlowCase() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPFLOW); - - MultipartReplyFlowCaseBuilder caseBuilder = new MultipartReplyFlowCaseBuilder(); - MultipartReplyFlowBuilder flowBuilder = new MultipartReplyFlowBuilder(); - List flowStats = new ArrayList<>(); - flowBuilder.setFlowStats(flowStats); - caseBuilder.setMultipartReplyFlow(flowBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - FlowsStatisticsUpdate flowUpdate = (FlowsStatisticsUpdate) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", flowUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, flowUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, flowUpdate.getTransactionId().getValue().intValue()); - List mapList = flowUpdate.getFlowAndStatisticsMapList(); - Assert.assertEquals("Wrong flow stats size", 0, mapList.size()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with experimenter MultipartReply message - */ - @Test - public void testFlowCase() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPFLOW); - - MultipartReplyFlowCaseBuilder caseBuilder = new MultipartReplyFlowCaseBuilder(); - MultipartReplyFlowBuilder flowBuilder = new MultipartReplyFlowBuilder(); - List flowStats = new ArrayList<>(); - FlowStatsBuilder statsBuilder = new FlowStatsBuilder(); - statsBuilder.setTableId((short) 1); - statsBuilder.setDurationSec(2L); - statsBuilder.setDurationNsec(3L); - statsBuilder.setPriority(4); - statsBuilder.setIdleTimeout(5); - statsBuilder.setHardTimeout(6); - FlowModFlags flags = new FlowModFlags(true, false, true, false, true); - statsBuilder.setFlags(flags); - statsBuilder.setCookie(new BigInteger("7")); - statsBuilder.setPacketCount(new BigInteger("8")); - statsBuilder.setByteCount(new BigInteger("9")); - MatchBuilder matchBuilder = new MatchBuilder(); - matchBuilder.setType(OxmMatchType.class); - matchBuilder.setMatchEntry(new ArrayList()); - statsBuilder.setMatch(matchBuilder.build()); - statsBuilder.setInstruction(new ArrayList()); - flowStats.add(statsBuilder.build()); - statsBuilder = new FlowStatsBuilder(); - statsBuilder.setTableId((short) 10); - statsBuilder.setDurationSec(20L); - statsBuilder.setDurationNsec(30L); - statsBuilder.setPriority(40); - statsBuilder.setIdleTimeout(50); - statsBuilder.setHardTimeout(60); - flags = new FlowModFlags(false, true, false, true, false); - statsBuilder.setFlags(flags); - statsBuilder.setCookie(new BigInteger("70")); - statsBuilder.setPacketCount(new BigInteger("80")); - statsBuilder.setByteCount(new BigInteger("90")); - matchBuilder = new MatchBuilder(); - matchBuilder.setType(OxmMatchType.class); - matchBuilder.setMatchEntry(new ArrayList()); - statsBuilder.setMatch(matchBuilder.build()); - statsBuilder.setInstruction(new ArrayList()); - flowStats.add(statsBuilder.build()); - flowBuilder.setFlowStats(flowStats); - caseBuilder.setMultipartReplyFlow(flowBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - FlowsStatisticsUpdate flowUpdate = (FlowsStatisticsUpdate) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", flowUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, flowUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, flowUpdate.getTransactionId().getValue().intValue()); - List mapList = flowUpdate.getFlowAndStatisticsMapList(); - Assert.assertEquals("Wrong flow stats size", 2, mapList.size()); - FlowAndStatisticsMapList stat = mapList.get(0); - Assert.assertEquals("Wrong table-id", 1, stat.getTableId().intValue()); - Assert.assertEquals("Wrong duration sec", 2, stat.getDuration().getSecond().getValue().intValue()); - Assert.assertEquals("Wrong duration n sec", 3, stat.getDuration().getNanosecond().getValue().intValue()); - Assert.assertEquals("Wrong priority", 4, stat.getPriority().intValue()); - Assert.assertEquals("Wrong idle-timeout", 5, stat.getIdleTimeout().intValue()); - Assert.assertEquals("Wrong hard-timeout", 6, stat.getHardTimeout().intValue()); - org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowModFlags expectedFlags = - new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026 - .FlowModFlags(!flags.isOFPFFCHECKOVERLAP(), !flags.isOFPFFNOBYTCOUNTS(), !flags.isOFPFFNOPKTCOUNTS(), - !flags.isOFPFFRESETCOUNTS(), !flags.isOFPFFSENDFLOWREM()); - Assert.assertEquals("Wrong flags", expectedFlags, stat.getFlags()); - Assert.assertEquals("Wrong cookie", 7, stat.getCookie().getValue().intValue()); - Assert.assertEquals("Wrong packet count", 8, stat.getPacketCount().getValue().intValue()); - Assert.assertEquals("Wrong byte count", 9, stat.getByteCount().getValue().intValue()); - org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder emptyMatchBuilder = - new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder(); - Match emptyMatch = emptyMatchBuilder.build(); - Assert.assertEquals("Wrong match", emptyMatch, stat.getMatch()); - Assert.assertEquals("Wrong instructions", 0, stat.getInstructions().getInstruction().size()); - stat = mapList.get(1); - Assert.assertEquals("Wrong table-id", 10, stat.getTableId().intValue()); - Assert.assertEquals("Wrong duration sec", 20, stat.getDuration().getSecond().getValue().intValue()); - Assert.assertEquals("Wrong duration n sec", 30, stat.getDuration().getNanosecond().getValue().intValue()); - Assert.assertEquals("Wrong priority", 40, stat.getPriority().intValue()); - Assert.assertEquals("Wrong idle-timeout", 50, stat.getIdleTimeout().intValue()); - Assert.assertEquals("Wrong hard-timeout", 60, stat.getHardTimeout().intValue()); - expectedFlags = new org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026 - .FlowModFlags(flags.isOFPFFCHECKOVERLAP(), flags.isOFPFFNOBYTCOUNTS(), flags.isOFPFFNOPKTCOUNTS(), - flags.isOFPFFRESETCOUNTS(), flags.isOFPFFSENDFLOWREM()); - Assert.assertEquals("Wrong flags", expectedFlags, stat.getFlags()); - Assert.assertEquals("Wrong cookie", 70, stat.getCookie().getValue().intValue()); - Assert.assertEquals("Wrong packet count", 80, stat.getPacketCount().getValue().intValue()); - Assert.assertEquals("Wrong byte count", 90, stat.getByteCount().getValue().intValue()); - Assert.assertEquals("Wrong match", emptyMatch, stat.getMatch()); - Assert.assertEquals("Wrong instructions", 0, stat.getInstructions().getInstruction().size()); - } -} \ No newline at end of file diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorFourthTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorFourthTest.java deleted file mode 100644 index 412b67cbcb..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorFourthTest.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.translator; - -import static org.mockito.Mockito.when; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupDescStatsUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupStatisticsUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.desc.stats.reply.GroupDescStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.action.rev150203.action.grouping.action.choice.DecMplsTtlCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.action.rev150203.action.grouping.action.choice.PopPbbCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.action.rev150203.actions.grouping.Action; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.action.rev150203.actions.grouping.ActionBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.GroupId; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.GroupType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortNumber; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.buckets.grouping.BucketsList; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.buckets.grouping.BucketsListBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupDescCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group._case.MultipartReplyGroupBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group._case.multipart.reply.group.GroupStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group._case.multipart.reply.group.GroupStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group._case.multipart.reply.group.group.stats.BucketStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group._case.multipart.reply.group.group.stats.BucketStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.desc._case.MultipartReplyGroupDescBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.desc._case.multipart.reply.group.desc.GroupDesc; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.desc._case.multipart.reply.group.desc.GroupDescBuilder; -import org.opendaylight.yangtools.yang.binding.DataObject; - -/** - * @author michal.polkorab - * - */ -@RunWith(MockitoJUnitRunner.class) -public class MultipartReplyTranslatorFourthTest { - - @Mock SwitchConnectionDistinguisher cookie; - @Mock SessionContext sc; - @Mock ConnectionConductor conductor; - @Mock GetFeaturesOutput features; - - MultipartReplyTranslator translator; - - /** - * Initializes mocks - */ - @Before - public void startUp() { - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - translator = new MultipartReplyTranslator(convertorManager); - when(sc.getPrimaryConductor()).thenReturn(conductor); - when(conductor.getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID); - when(sc.getFeatures()).thenReturn(features); - when(features.getDatapathId()).thenReturn(new BigInteger("42")); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with empty group stats - */ - @Test - public void testEmptyGroupStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPGROUP); - - MultipartReplyGroupCaseBuilder caseBuilder = new MultipartReplyGroupCaseBuilder(); - MultipartReplyGroupBuilder groupBuilder = new MultipartReplyGroupBuilder(); - List groupStats = new ArrayList<>(); - groupBuilder.setGroupStats(groupStats); - caseBuilder.setMultipartReplyGroup(groupBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - GroupStatisticsUpdated statUpdate = (GroupStatisticsUpdated) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong group stats size", 0, statUpdate.getGroupStats().size()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with group stats - */ - @Test - public void testGroupStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPGROUP); - - MultipartReplyGroupCaseBuilder caseBuilder = new MultipartReplyGroupCaseBuilder(); - MultipartReplyGroupBuilder groupBuilder = new MultipartReplyGroupBuilder(); - List groupStats = new ArrayList<>(); - GroupStatsBuilder builder = new GroupStatsBuilder(); - builder.setGroupId(new GroupId(55L)); - builder.setRefCount(56L); - builder.setPacketCount(new BigInteger("57")); - builder.setByteCount(new BigInteger("58")); - builder.setDurationSec(59L); - builder.setDurationNsec(60L); - List bucketStats = new ArrayList<>(); - BucketStatsBuilder bucketBuilder = new BucketStatsBuilder(); - bucketBuilder.setByteCount(new BigInteger("61")); - bucketBuilder.setPacketCount(new BigInteger("62")); - bucketStats.add(bucketBuilder.build()); - bucketBuilder = new BucketStatsBuilder(); - bucketBuilder.setByteCount(new BigInteger("63")); - bucketBuilder.setPacketCount(new BigInteger("64")); - bucketStats.add(bucketBuilder.build()); - builder.setBucketStats(bucketStats); - groupStats.add(builder.build()); - builder = new GroupStatsBuilder(); - builder.setGroupId(new GroupId(550L)); - builder.setRefCount(560L); - builder.setPacketCount(new BigInteger("570")); - builder.setByteCount(new BigInteger("580")); - builder.setDurationSec(590L); - builder.setDurationNsec(600L); - bucketStats = new ArrayList<>(); - builder.setBucketStats(bucketStats); - groupStats.add(builder.build()); - groupBuilder.setGroupStats(groupStats); - caseBuilder.setMultipartReplyGroup(groupBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - GroupStatisticsUpdated statUpdate = (GroupStatisticsUpdated) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong group stats size", 2, statUpdate.getGroupStats().size()); - org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.statistics.reply - .GroupStats stat = statUpdate.getGroupStats().get(0); - Assert.assertEquals("Wrong group-id", 55, stat.getGroupId().getValue().intValue()); - Assert.assertEquals("Wrong ref count", 56, stat.getRefCount().getValue().intValue()); - Assert.assertEquals("Wrong packet count", 57, stat.getPacketCount().getValue().intValue()); - Assert.assertEquals("Wrong byte count", 58, stat.getByteCount().getValue().intValue()); - Assert.assertEquals("Wrong duration sec", 59, stat.getDuration().getSecond().getValue().intValue()); - Assert.assertEquals("Wrong duration n sec", 60, stat.getDuration().getNanosecond().getValue().intValue()); - Assert.assertEquals("Wrong bucket stats size", 2, stat.getBuckets().getBucketCounter().size()); - Assert.assertEquals("Wrong bucket-id", 0, stat.getBuckets().getBucketCounter().get(0).getBucketId().getValue().intValue()); - Assert.assertEquals("Wrong byte count", 61, stat.getBuckets().getBucketCounter().get(0).getByteCount().getValue().intValue()); - Assert.assertEquals("Wrong packet count", 62, stat.getBuckets().getBucketCounter().get(0).getPacketCount().getValue().intValue()); - Assert.assertEquals("Wrong bucket-id", 1, stat.getBuckets().getBucketCounter().get(1).getBucketId().getValue().intValue()); - Assert.assertEquals("Wrong byte count", 63, stat.getBuckets().getBucketCounter().get(1).getByteCount().getValue().intValue()); - Assert.assertEquals("Wrong packet count", 64, stat.getBuckets().getBucketCounter().get(1).getPacketCount().getValue().intValue()); - stat = statUpdate.getGroupStats().get(1); - Assert.assertEquals("Wrong group-id", 550, stat.getGroupId().getValue().intValue()); - Assert.assertEquals("Wrong ref count", 560, stat.getRefCount().getValue().intValue()); - Assert.assertEquals("Wrong packet count", 570, stat.getPacketCount().getValue().intValue()); - Assert.assertEquals("Wrong byte count", 580, stat.getByteCount().getValue().intValue()); - Assert.assertEquals("Wrong duration sec", 590, stat.getDuration().getSecond().getValue().intValue()); - Assert.assertEquals("Wrong duration n sec", 600, stat.getDuration().getNanosecond().getValue().intValue()); - Assert.assertEquals("Wrong bucket stats size", 0, stat.getBuckets().getBucketCounter().size()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with empty group desc stats - */ - @Test - public void testEmptyGroupDescStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPGROUPDESC); - - MultipartReplyGroupDescCaseBuilder caseBuilder = new MultipartReplyGroupDescCaseBuilder(); - MultipartReplyGroupDescBuilder groupBuilder = new MultipartReplyGroupDescBuilder(); - List groupStats = new ArrayList<>(); - groupBuilder.setGroupDesc(groupStats); - caseBuilder.setMultipartReplyGroupDesc(groupBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - GroupDescStatsUpdated statUpdate = (GroupDescStatsUpdated) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong group stats size", 0, statUpdate.getGroupDescStats().size()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with group desc stats - */ - @Test - public void testGroupDescStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPGROUPDESC); - - MultipartReplyGroupDescCaseBuilder caseBuilder = new MultipartReplyGroupDescCaseBuilder(); - MultipartReplyGroupDescBuilder groupBuilder = new MultipartReplyGroupDescBuilder(); - List groupStats = new ArrayList<>(); - - GroupDescBuilder builder = new GroupDescBuilder(); - builder.setType(GroupType.OFPGTALL); - builder.setGroupId(new GroupId(1L)); - List buckets = new ArrayList<>(); - BucketsListBuilder bucketBuilder = new BucketsListBuilder(); - bucketBuilder.setWeight(28); - bucketBuilder.setWatchPort(new PortNumber(56L)); - bucketBuilder.setWatchGroup(112L); - - List actions = new ArrayList<>(); - ActionBuilder actionBuilder = new ActionBuilder(); - DecMplsTtlCaseBuilder decMplsTtlCaseBuilder = new DecMplsTtlCaseBuilder(); - actionBuilder.setActionChoice(decMplsTtlCaseBuilder.build()); - actions.add(actionBuilder.build()); - - actionBuilder = new ActionBuilder(); - PopPbbCaseBuilder popPbbCaseBuilder = new PopPbbCaseBuilder(); - actionBuilder.setActionChoice(popPbbCaseBuilder.build()); - actions.add(actionBuilder.build()); - - bucketBuilder.setAction(actions); - buckets.add(bucketBuilder.build()); - bucketBuilder = new BucketsListBuilder(); - bucketBuilder.setWeight(280); - bucketBuilder.setWatchPort(new PortNumber(560L)); - bucketBuilder.setWatchGroup(1120L); - actions = new ArrayList<>(); - bucketBuilder.setAction(actions); - buckets.add(bucketBuilder.build()); - builder.setBucketsList(buckets); - groupStats.add(builder.build()); - groupBuilder.setGroupDesc(groupStats); - caseBuilder.setMultipartReplyGroupDesc(groupBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - GroupDescStatsUpdated statUpdate = (GroupDescStatsUpdated) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong group stats size", 1, statUpdate.getGroupDescStats().size()); - GroupDescStats stat = statUpdate.getGroupDescStats().get(0); - Assert.assertEquals("Wrong group-id", 1, stat.getGroupId().getValue().intValue()); - Assert.assertEquals("Wrong group type", GroupTypes.GroupAll, stat.getGroupType()); - Assert.assertEquals("Wrong buckets size", 2, stat.getBuckets().getBucket().size()); - Bucket bucket = stat.getBuckets().getBucket().get(0); - Assert.assertEquals("Wrong weight size", 28, bucket.getWeight().intValue()); - Assert.assertEquals("Wrong watch port size", 56, bucket.getWatchPort().intValue()); - Assert.assertEquals("Wrong watch group size", 112, bucket.getWatchGroup().intValue()); - Assert.assertEquals("Wrong actions size", 2, bucket.getAction().size()); - Assert.assertEquals("Wrong action type", "org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112" - + ".action.action.DecMplsTtlCase", bucket.getAction().get(0).getAction().getImplementedInterface().getName()); - Assert.assertEquals("Wrong action type", "org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112" - + ".action.action.PopPbbActionCase", bucket.getAction().get(1).getAction().getImplementedInterface().getName()); - bucket = stat.getBuckets().getBucket().get(1); - Assert.assertEquals("Wrong weight size", 280, bucket.getWeight().intValue()); - Assert.assertEquals("Wrong watch port size", 560, bucket.getWatchPort().intValue()); - Assert.assertEquals("Wrong watch group size", 1120, bucket.getWatchGroup().intValue()); - Assert.assertEquals("Wrong actions size", 0, bucket.getAction().size()); - } -} \ No newline at end of file diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorSecondTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorSecondTest.java deleted file mode 100644 index 737d2ebbea..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorSecondTest.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.translator; - -import static org.mockito.Mockito.when; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.AggregateFlowStatisticsUpdate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.GroupFeaturesUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.MeterFeaturesUpdated; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ActionType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.GroupCapabilities; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.GroupTypes; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MeterBandTypeBitmap; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MeterFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyAggregateCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupFeaturesCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterFeaturesCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.aggregate._case.MultipartReplyAggregateBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.features._case.MultipartReplyGroupFeaturesBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.features._case.MultipartReplyMeterFeaturesBuilder; -import org.opendaylight.yangtools.yang.binding.DataObject; - -/** - * @author michal.polkorab - * - */ -@RunWith(MockitoJUnitRunner.class) -public class MultipartReplyTranslatorSecondTest { - - @Mock SwitchConnectionDistinguisher cookie; - @Mock SessionContext sc; - @Mock ConnectionConductor conductor; - @Mock GetFeaturesOutput features; - - MultipartReplyTranslator translator; - - /** - * Initializes mocks - */ - @Before - public void startUp() { - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - translator = new MultipartReplyTranslator(convertorManager); - when(sc.getPrimaryConductor()).thenReturn(conductor); - when(conductor.getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID); - when(sc.getFeatures()).thenReturn(features); - when(features.getDatapathId()).thenReturn(new BigInteger("42")); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with aggregate stat - */ - @Test - public void testAggregateCase() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPAGGREGATE); - - MultipartReplyAggregateCaseBuilder caseBuilder = new MultipartReplyAggregateCaseBuilder(); - MultipartReplyAggregateBuilder aggBuilder = new MultipartReplyAggregateBuilder(); - aggBuilder.setByteCount(new BigInteger("52")); - aggBuilder.setFlowCount(6587L); - aggBuilder.setPacketCount(new BigInteger("25")); - caseBuilder.setMultipartReplyAggregate(aggBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - AggregateFlowStatisticsUpdate aggUpdate = (AggregateFlowStatisticsUpdate) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", aggUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, aggUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, aggUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong byte count", 52, aggUpdate.getByteCount().getValue().intValue()); - Assert.assertEquals("Wrong packet count", 25, aggUpdate.getPacketCount().getValue().intValue()); - Assert.assertEquals("Wrong flow count", 6587, aggUpdate.getFlowCount().getValue().intValue()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with group features stat - */ - @Test - public void testGroupFeaturesCase() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPGROUPFEATURES); - - MultipartReplyGroupFeaturesCaseBuilder caseBuilder = new MultipartReplyGroupFeaturesCaseBuilder(); - MultipartReplyGroupFeaturesBuilder featBuilder = new MultipartReplyGroupFeaturesBuilder(); - featBuilder.setTypes(new GroupTypes(true, false, true, false)); - featBuilder.setCapabilities(new GroupCapabilities(false, true, false, true)); - List maxGroups = new ArrayList<>(); - maxGroups.add(1L); - maxGroups.add(2L); - maxGroups.add(3L); - maxGroups.add(4L); - featBuilder.setMaxGroups(maxGroups); - List actionTypes = new ArrayList<>(); - ActionType actionType1 = new ActionType(true, false, true, false, false, false, true, - false, true, false, true, false, true, false, true, false, true); - actionTypes.add(actionType1); - ActionType actionType2 = new ActionType(false, true, false, true, false, true, false, - true, false, true, false, true, false, true, false, true, false); - actionTypes.add(actionType2); - ActionType actionType3 = new ActionType(false, false, false, false, false, false, false, - true, true, true, true, true, true, true, true, true, true); - actionTypes.add(actionType3); - ActionType actionType4 = new ActionType(true, true, true, true, true, true, true, - false, false, false, false, false, false, false, false, false, false); - actionTypes.add(actionType4); - featBuilder.setActionsBitmap(actionTypes); - caseBuilder.setMultipartReplyGroupFeatures(featBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - GroupFeaturesUpdated groupUpdate = (GroupFeaturesUpdated) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", groupUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, groupUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, groupUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong group types size", 2, groupUpdate.getGroupTypesSupported().size()); - Assert.assertEquals("Wrong group type", "org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupAll", - groupUpdate.getGroupTypesSupported().get(0).getName()); - Assert.assertEquals("Wrong group type", "org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupIndirect", - groupUpdate.getGroupTypesSupported().get(1).getName()); - Assert.assertEquals("Wrong group capabilities size", 2, groupUpdate.getGroupCapabilitiesSupported().size()); - Assert.assertEquals("Wrong group capability", "org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.ChainingChecks", - groupUpdate.getGroupCapabilitiesSupported().get(0).getName()); - Assert.assertEquals("Wrong group capability", "org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.SelectWeight", - groupUpdate.getGroupCapabilitiesSupported().get(1).getName()); - Assert.assertEquals("Wrong max groups", maxGroups, groupUpdate.getMaxGroups()); - Assert.assertEquals("Wrong actions bitmap", 137072641, groupUpdate.getActions().get(0).longValue()); - Assert.assertEquals("Wrong actions bitmap", 131336192, groupUpdate.getActions().get(1).longValue()); - Assert.assertEquals("Wrong actions bitmap", 247365632, groupUpdate.getActions().get(2).longValue()); - Assert.assertEquals("Wrong actions bitmap", 21043201, groupUpdate.getActions().get(3).longValue()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with meter features stat - */ - @Test - public void testMeterFeaturesCase() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPMETERFEATURES); - - MultipartReplyMeterFeaturesCaseBuilder caseBuilder = new MultipartReplyMeterFeaturesCaseBuilder(); - MultipartReplyMeterFeaturesBuilder featBuilder = new MultipartReplyMeterFeaturesBuilder(); - featBuilder.setMaxMeter(1L); - featBuilder.setBandTypes(new MeterBandTypeBitmap(true, true)); - featBuilder.setCapabilities(new MeterFlags(true, true, true, true)); - featBuilder.setMaxBands((short) 2); - featBuilder.setMaxColor((short) 3); - caseBuilder.setMultipartReplyMeterFeatures(featBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - MeterFeaturesUpdated megterUpdate = (MeterFeaturesUpdated) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", megterUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, megterUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, megterUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong max meter", 1, megterUpdate.getMaxMeter().getValue().intValue()); - Assert.assertEquals("Wrong max bands", 2, megterUpdate.getMaxBands().intValue()); - Assert.assertEquals("Wrong max color", 3, megterUpdate.getMaxColor().intValue()); - Assert.assertEquals("Wrong capabilities size", 4, megterUpdate.getMeterCapabilitiesSupported().size()); - Assert.assertEquals("Wrong capability", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918" - + ".MeterBurst", megterUpdate.getMeterCapabilitiesSupported().get(0).getName()); - Assert.assertEquals("Wrong capability", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918" - + ".MeterKbps", megterUpdate.getMeterCapabilitiesSupported().get(1).getName()); - Assert.assertEquals("Wrong capability", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918" - + ".MeterPktps", megterUpdate.getMeterCapabilitiesSupported().get(2).getName()); - Assert.assertEquals("Wrong capability", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918" - + ".MeterStats", megterUpdate.getMeterCapabilitiesSupported().get(3).getName()); - Assert.assertEquals("Wrong band types size", 2, megterUpdate.getMeterBandSupported().size()); - Assert.assertEquals("Wrong band type", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterBandDrop", - megterUpdate.getMeterBandSupported().get(0).getName()); - Assert.assertEquals("Wrong band type", "org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterBandDscpRemark", - megterUpdate.getMeterBandSupported().get(1).getName()); - } -} \ No newline at end of file diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorThirdTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorThirdTest.java deleted file mode 100644 index c16ba9d832..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/MultipartReplyTranslatorThirdTest.java +++ /dev/null @@ -1,382 +0,0 @@ -/* - * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.translator; - -import static org.mockito.Mockito.when; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowjava.protocol.api.util.BinContent; -import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager; -import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory; -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.flow.table.and.statistics.map.FlowTableAndStatisticsMap; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortNumberValues; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyPortStatsCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyQueueCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableCaseBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.stats._case.MultipartReplyPortStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.stats._case.multipart.reply.port.stats.PortStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.stats._case.multipart.reply.port.stats.PortStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.queue._case.MultipartReplyQueueBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.queue._case.multipart.reply.queue.QueueStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.queue._case.multipart.reply.queue.QueueStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table._case.MultipartReplyTableBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table._case.multipart.reply.table.TableStats; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table._case.multipart.reply.table.TableStatsBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.NodeConnectorStatisticsUpdate; -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.queue.statistics.rev131216.QueueStatisticsUpdate; -import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.queue.id.and.statistics.map.QueueIdAndStatisticsMap; -import org.opendaylight.yangtools.yang.binding.DataObject; - -/** - * @author michal.polkorab - * - */ -@RunWith(MockitoJUnitRunner.class) -public class MultipartReplyTranslatorThirdTest { - - @Mock SwitchConnectionDistinguisher cookie; - @Mock SessionContext sc; - @Mock ConnectionConductor conductor; - @Mock GetFeaturesOutput features; - - MultipartReplyTranslator translator; - - /** - * Initializes mocks - */ - @Before - public void startUp() { - final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager(); - translator = new MultipartReplyTranslator(convertorManager); - when(sc.getPrimaryConductor()).thenReturn(conductor); - when(conductor.getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID); - when(sc.getFeatures()).thenReturn(features); - when(features.getDatapathId()).thenReturn(new BigInteger("42")); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with empty port stats - */ - @Test - public void testEmptyPortStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPPORTSTATS); - - MultipartReplyPortStatsCaseBuilder caseBuilder = new MultipartReplyPortStatsCaseBuilder(); - MultipartReplyPortStatsBuilder statsBuilder = new MultipartReplyPortStatsBuilder(); - List portStats = new ArrayList<>(); - statsBuilder.setPortStats(portStats); - caseBuilder.setMultipartReplyPortStats(statsBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - NodeConnectorStatisticsUpdate statUpdate = (NodeConnectorStatisticsUpdate) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong port stats size", 0, statUpdate.getNodeConnectorStatisticsAndPortNumberMap().size()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with port stats - */ - @Test - public void testPortStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPPORTSTATS); - - MultipartReplyPortStatsCaseBuilder caseBuilder = new MultipartReplyPortStatsCaseBuilder(); - MultipartReplyPortStatsBuilder statsBuilder = new MultipartReplyPortStatsBuilder(); - List portStats = new ArrayList<>(); - PortStatsBuilder builder = new PortStatsBuilder(); - builder.setPortNo(1L); - builder.setRxPackets(new BigInteger("2")); - builder.setTxPackets(new BigInteger("3")); - builder.setRxBytes(new BigInteger("4")); - builder.setTxBytes(new BigInteger("5")); - builder.setRxDropped(new BigInteger("6")); - builder.setTxDropped(new BigInteger("7")); - builder.setRxErrors(new BigInteger("8")); - builder.setTxErrors(new BigInteger("9")); - builder.setRxFrameErr(new BigInteger("10")); - builder.setRxOverErr(new BigInteger("11")); - builder.setRxCrcErr(new BigInteger("12")); - builder.setCollisions(new BigInteger("13")); - builder.setDurationSec(14L); - builder.setDurationNsec(15L); - portStats.add(builder.build()); - builder = new PortStatsBuilder(); - builder.setPortNo(BinContent.intToUnsignedLong(PortNumberValues.CONTROLLER.getIntValue())); - builder.setRxPackets(new BigInteger("20")); - builder.setTxPackets(new BigInteger("30")); - builder.setRxBytes(new BigInteger("40")); - builder.setTxBytes(new BigInteger("50")); - builder.setRxDropped(new BigInteger("60")); - builder.setTxDropped(new BigInteger("70")); - builder.setRxErrors(new BigInteger("80")); - builder.setTxErrors(new BigInteger("90")); - builder.setRxFrameErr(new BigInteger("100")); - builder.setRxOverErr(new BigInteger("110")); - builder.setRxCrcErr(new BigInteger("120")); - builder.setCollisions(new BigInteger("130")); - portStats.add(builder.build()); - statsBuilder.setPortStats(portStats); - caseBuilder.setMultipartReplyPortStats(statsBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - NodeConnectorStatisticsUpdate statUpdate = (NodeConnectorStatisticsUpdate) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong port stats size", 2, statUpdate.getNodeConnectorStatisticsAndPortNumberMap().size()); - NodeConnectorStatisticsAndPortNumberMap stat = statUpdate.getNodeConnectorStatisticsAndPortNumberMap().get(0); - Assert.assertEquals("Wrong port number", "openflow:42:1", stat.getNodeConnectorId().getValue()); - Assert.assertEquals("Wrong rx packets", 2, stat.getPackets().getReceived().intValue()); - Assert.assertEquals("Wrong tx packets", 3, stat.getPackets().getTransmitted().intValue()); - Assert.assertEquals("Wrong rx bytes", 4, stat.getBytes().getReceived().intValue()); - Assert.assertEquals("Wrong tx bytes", 5, stat.getBytes().getTransmitted().intValue()); - Assert.assertEquals("Wrong rx dropped", 6, stat.getReceiveDrops().intValue()); - Assert.assertEquals("Wrong tx dropped", 7, stat.getTransmitDrops().intValue()); - Assert.assertEquals("Wrong rx errors", 8, stat.getReceiveErrors().intValue()); - Assert.assertEquals("Wrong tx errors", 9, stat.getTransmitErrors().intValue()); - Assert.assertEquals("Wrong rx frame error", 10, stat.getReceiveFrameError().intValue()); - Assert.assertEquals("Wrong rx over error", 11, stat.getReceiveOverRunError().intValue()); - Assert.assertEquals("Wrong rx crc error", 12, stat.getReceiveCrcError().intValue()); - Assert.assertEquals("Wrong collision count", 13, stat.getCollisionCount().intValue()); - Assert.assertEquals("Wrong duration sec", 14, stat.getDuration().getSecond().getValue().intValue()); - Assert.assertEquals("Wrong duration n sec", 15, stat.getDuration().getNanosecond().getValue().intValue()); - stat = statUpdate.getNodeConnectorStatisticsAndPortNumberMap().get(1); - Assert.assertEquals("Wrong port number", "openflow:42:CONTROLLER", stat.getNodeConnectorId().getValue()); - Assert.assertEquals("Wrong rx packets", 20, stat.getPackets().getReceived().intValue()); - Assert.assertEquals("Wrong tx packets", 30, stat.getPackets().getTransmitted().intValue()); - Assert.assertEquals("Wrong rx bytes", 40, stat.getBytes().getReceived().intValue()); - Assert.assertEquals("Wrong tx bytes", 50, stat.getBytes().getTransmitted().intValue()); - Assert.assertEquals("Wrong rx dropped", 60, stat.getReceiveDrops().intValue()); - Assert.assertEquals("Wrong tx dropped", 70, stat.getTransmitDrops().intValue()); - Assert.assertEquals("Wrong rx errors", 80, stat.getReceiveErrors().intValue()); - Assert.assertEquals("Wrong tx errors", 90, stat.getTransmitErrors().intValue()); - Assert.assertEquals("Wrong rx frame error", 100, stat.getReceiveFrameError().intValue()); - Assert.assertEquals("Wrong rx over error", 110, stat.getReceiveOverRunError().intValue()); - Assert.assertEquals("Wrong rx crc error", 120, stat.getReceiveCrcError().intValue()); - Assert.assertEquals("Wrong collision count", 130, stat.getCollisionCount().intValue()); - Assert.assertEquals("Wrong duration sec", null, stat.getDuration().getSecond()); - Assert.assertEquals("Wrong duration n sec", null, stat.getDuration().getNanosecond()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with empty table stats - */ - @Test - public void testEmptyTableStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPTABLE); - - MultipartReplyTableCaseBuilder caseBuilder = new MultipartReplyTableCaseBuilder(); - MultipartReplyTableBuilder statsBuilder = new MultipartReplyTableBuilder(); - List tableStats = new ArrayList<>(); - statsBuilder.setTableStats(tableStats); - caseBuilder.setMultipartReplyTable(statsBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - FlowTableStatisticsUpdate statUpdate = (FlowTableStatisticsUpdate) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong table stats size", 0, statUpdate.getFlowTableAndStatisticsMap().size()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with table stats - */ - @Test - public void testTableStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPTABLE); - - MultipartReplyTableCaseBuilder caseBuilder = new MultipartReplyTableCaseBuilder(); - MultipartReplyTableBuilder statsBuilder = new MultipartReplyTableBuilder(); - List tableStats = new ArrayList<>(); - TableStatsBuilder builder = new TableStatsBuilder(); - builder.setTableId((short) 1); - builder.setActiveCount(2L); - builder.setLookupCount(new BigInteger("3")); - builder.setMatchedCount(new BigInteger("4")); - tableStats.add(builder.build()); - builder = new TableStatsBuilder(); - builder.setTableId((short) 10); - builder.setActiveCount(20L); - builder.setLookupCount(new BigInteger("30")); - builder.setMatchedCount(new BigInteger("40")); - tableStats.add(builder.build()); - statsBuilder.setTableStats(tableStats); - caseBuilder.setMultipartReplyTable(statsBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - FlowTableStatisticsUpdate statUpdate = (FlowTableStatisticsUpdate) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong table stats size", 2, statUpdate.getFlowTableAndStatisticsMap().size()); - FlowTableAndStatisticsMap stat = statUpdate.getFlowTableAndStatisticsMap().get(0); - Assert.assertEquals("Wrong table-id", 1, stat.getTableId().getValue().intValue()); - Assert.assertEquals("Wrong active count", 2, stat.getActiveFlows().getValue().intValue()); - Assert.assertEquals("Wrong lookup count", 3, stat.getPacketsLookedUp().getValue().intValue()); - Assert.assertEquals("Wrong matched count", 4, stat.getPacketsMatched().getValue().intValue()); - stat = statUpdate.getFlowTableAndStatisticsMap().get(1); - Assert.assertEquals("Wrong table-id", 10, stat.getTableId().getValue().intValue()); - Assert.assertEquals("Wrong active count", 20, stat.getActiveFlows().getValue().intValue()); - Assert.assertEquals("Wrong lookup count", 30, stat.getPacketsLookedUp().getValue().intValue()); - Assert.assertEquals("Wrong matched count", 40, stat.getPacketsMatched().getValue().intValue()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with empty queue stats - */ - @Test - public void testEmptyQueueStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPQUEUE); - - MultipartReplyQueueCaseBuilder caseBuilder = new MultipartReplyQueueCaseBuilder(); - MultipartReplyQueueBuilder statsBuilder = new MultipartReplyQueueBuilder(); - List queueStats = new ArrayList<>(); - statsBuilder.setQueueStats(queueStats); - caseBuilder.setMultipartReplyQueue(statsBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - QueueStatisticsUpdate statUpdate = (QueueStatisticsUpdate) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong queue stats size", 0, statUpdate.getQueueIdAndStatisticsMap().size()); - } - - /** - * Test {@link MultipartReplyTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * with queue stats - */ - @Test - public void testQueueStats() { - MultipartReplyMessageBuilder mpBuilder = new MultipartReplyMessageBuilder(); - mpBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - mpBuilder.setXid(123L); - mpBuilder.setFlags(new MultipartRequestFlags(false)); - mpBuilder.setType(MultipartType.OFPMPQUEUE); - - MultipartReplyQueueCaseBuilder caseBuilder = new MultipartReplyQueueCaseBuilder(); - MultipartReplyQueueBuilder statsBuilder = new MultipartReplyQueueBuilder(); - List queueStats = new ArrayList<>(); - QueueStatsBuilder builder = new QueueStatsBuilder(); - builder.setPortNo(BinContent.intToUnsignedLong(PortNumberValues.FLOOD.getIntValue())); - builder.setQueueId(2L); - builder.setTxPackets(new BigInteger("3")); - builder.setTxBytes(new BigInteger("4")); - builder.setTxErrors(new BigInteger("5")); - builder.setDurationSec(6L); - builder.setDurationNsec(7L); - queueStats.add(builder.build()); - builder = new QueueStatsBuilder(); - builder.setPortNo(BinContent.intToUnsignedLong(PortNumberValues.INPORT.getIntValue())); - builder.setQueueId(20L); - builder.setTxPackets(new BigInteger("30")); - builder.setTxBytes(new BigInteger("40")); - builder.setTxErrors(new BigInteger("50")); - builder.setDurationSec(60L); - builder.setDurationNsec(70L); - queueStats.add(builder.build()); - statsBuilder.setQueueStats(queueStats); - caseBuilder.setMultipartReplyQueue(statsBuilder.build()); - mpBuilder.setMultipartReplyBody(caseBuilder.build()); - MultipartReplyMessage message = mpBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 1, list.size()); - QueueStatisticsUpdate statUpdate = (QueueStatisticsUpdate) list.get(0); - Assert.assertEquals("Wrong node-id", "openflow:42", statUpdate.getId().getValue()); - Assert.assertEquals("Wrong more-replies", false, statUpdate.isMoreReplies()); - Assert.assertEquals("Wrong transaction-id", 123, statUpdate.getTransactionId().getValue().intValue()); - Assert.assertEquals("Wrong queue stats size", 2, statUpdate.getQueueIdAndStatisticsMap().size()); - QueueIdAndStatisticsMap stat = statUpdate.getQueueIdAndStatisticsMap().get(0); - Assert.assertEquals("Wrong port number", "openflow:42:FLOOD", stat.getNodeConnectorId().getValue()); - Assert.assertEquals("Wrong queue-id", 2, stat.getQueueId().getValue().intValue()); - Assert.assertEquals("Wrong tx packets", 3, stat.getTransmittedPackets().getValue().intValue()); - Assert.assertEquals("Wrong tx bytes", 4, stat.getTransmittedBytes().getValue().intValue()); - Assert.assertEquals("Wrong tx errors", 5, stat.getTransmissionErrors().getValue().intValue()); - Assert.assertEquals("Wrong duration sec", 6, stat.getDuration().getSecond().getValue().intValue()); - Assert.assertEquals("Wrong duration n sec", 7, stat.getDuration().getNanosecond().getValue().intValue()); - stat = statUpdate.getQueueIdAndStatisticsMap().get(1); - Assert.assertEquals("Wrong port number", "openflow:42:IN_PORT", stat.getNodeConnectorId().getValue()); - Assert.assertEquals("Wrong queue-id", 20, stat.getQueueId().getValue().intValue()); - Assert.assertEquals("Wrong tx packets", 30, stat.getTransmittedPackets().getValue().intValue()); - Assert.assertEquals("Wrong tx bytes", 40, stat.getTransmittedBytes().getValue().intValue()); - Assert.assertEquals("Wrong tx errors", 50, stat.getTransmissionErrors().getValue().intValue()); - Assert.assertEquals("Wrong duration sec", 60, stat.getDuration().getSecond().getValue().intValue()); - Assert.assertEquals("Wrong duration n sec", 70, stat.getDuration().getNanosecond().getValue().intValue()); - } -} \ No newline at end of file diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/NotificationPlainTranslatorTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/NotificationPlainTranslatorTest.java deleted file mode 100644 index bba3605a89..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/NotificationPlainTranslatorTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2014 Pantheon Technologies s.r.o. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the 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.openflow.md.core.translator; - -import java.math.BigInteger; -import java.util.List; - -import static org.mockito.Mockito.when; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.NotificationQueueWrapper; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yangtools.yang.binding.DataObject; - -/** - * @author michal.polkorab - * - */ -public class NotificationPlainTranslatorTest { - - @Mock SwitchConnectionDistinguisher cookie; - @Mock SessionContext sc; - @Mock GetFeaturesOutput features; - - NotificationPlainTranslator translator = new NotificationPlainTranslator(); - - /** - * Initializes mocks - */ - @Before - public void startUp() { - MockitoAnnotations.initMocks(this); - } - - /** - * Tests {@link NotificationPlainTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - */ - @Test - public void testIncorrectInput() { - HelloMessageBuilder helloBuilder = new HelloMessageBuilder(); - HelloMessage message = helloBuilder.build(); - - List list = translator.translate(cookie, sc, message); - - Assert.assertEquals("Wrong list size", 0, list.size()); - } - - /** - * Tests {@link NotificationPlainTranslator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - */ - @Test - public void test() { - when(sc.getFeatures()).thenReturn(features); - when(features.getDatapathId()).thenReturn(new BigInteger("64")); - HelloMessageBuilder helloBuilder = new HelloMessageBuilder(); - helloBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID); - helloBuilder.setXid(42L); - HelloMessage message = helloBuilder.build(); - NotificationQueueWrapper wrapper = new NotificationQueueWrapper(message, message.getVersion()); - - List list = translator.translate(cookie, sc, wrapper); - - Assert.assertEquals("Wrong list size", 1, list.size()); - HelloMessage hello = (HelloMessage) list.get(0); - Assert.assertEquals("Wrong output", 4, hello.getVersion().intValue()); - Assert.assertEquals("Wrong output", 42, hello.getXid().intValue()); - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PacketInV10TranslatorTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PacketInV10TranslatorTest.java deleted file mode 100644 index 336f101cbd..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/core/translator/PacketInV10TranslatorTest.java +++ /dev/null @@ -1,269 +0,0 @@ -/** - * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - */ - -package org.opendaylight.openflowplugin.openflow.md.core.translator; - -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowjava.protocol.api.util.EncodeConstants; -import org.opendaylight.openflowplugin.api.openflow.md.core.IMDMessageTranslator; -import org.opendaylight.openflowplugin.api.openflow.md.core.SwitchConnectionDistinguisher; -import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion; -import org.opendaylight.openflowplugin.openflow.md.core.ConnectionConductorImpl; -import org.opendaylight.openflowplugin.openflow.md.core.session.SessionContextOFImpl; -import org.opendaylight.openflowplugin.openflow.md.core.session.SwitchConnectionCookieOFImpl; -import org.opendaylight.openflowplugin.openflow.md.queue.QueueProcessorLightImpl; -import org.opendaylight.openflowplugin.openflow.md.util.InventoryDataServiceUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PacketInReason; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessageBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceivedBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.SendToController; -import org.opendaylight.yangtools.yang.binding.DataObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Created by Jakub Toth jatoth@cisco.com on 3/10/14. - */ -@RunWith(MockitoJUnitRunner.class) -public class PacketInV10TranslatorTest { - private static final Logger LOG = LoggerFactory - .getLogger(PacketInV10TranslatorTest.class); - - @Mock - private SessionContext sc; - @Mock - private ConnectionConductorImpl conductor; - @Mock - private GetFeaturesOutput features; - - private SwitchConnectionDistinguisher cookie; - private byte[] data; - - /** - * Initializes mocks - */ - @Before - public void startUp() { - when(sc.getPrimaryConductor()).thenReturn(conductor); - when(conductor.getVersion()).thenReturn((short) EncodeConstants.OF10_VERSION_ID); - when(sc.getFeatures()).thenReturn(features); - when(features.getDatapathId()).thenReturn(new BigInteger("42")); - - cookie = settingCookie(); - data = messageData(); - } - - /** - * test - * {@link PacketInV10Translator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * - all parameteres are null - translates packetIn from OF-API model to - * MD-SAL model, supports OF-1.0 - */ - @Test - public void testTranslateWithAllNullParam() { - SwitchConnectionDistinguisher cookieNull = null; - SessionContext sessionContext = null; - OfHeader msg = null; - - PacketInV10Translator packetInV10Translator = new PacketInV10Translator(); - - List salPacketIn = packetInV10Translator.translate(cookieNull, - sessionContext, msg); - - Assert.assertEquals(true, salPacketIn.isEmpty()); - - LOG.info("Test with all null parameters done."); - } - - /** - * test - * {@link PacketInV10Translator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * - DPID is null- translates packetIn from OF-API model to MD-SAL model, - * supports OF-1.0 - */ - @Test - public void testTranslateDPIDNull() { - SessionContext sessionContextOFImpl = new SessionContextOFImpl(); - - PacketInMessage message = createPacketInMessage(data, null); - - PacketInV10Translator packetInV10Translator = new PacketInV10Translator(); - - List salPacketIn = packetInV10Translator.translate(cookie, - sessionContextOFImpl, message); - - Assert.assertEquals(true, salPacketIn.isEmpty()); - LOG.info("Test with null DPID parameter done."); - } - - /** - * test - * {@link PacketInV10Translator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * - inPort is null- translates packetIn from OF-API model to MD-SAL model, - * supports OF-1.0 - */ - @Test - public void testTranslateInPortNull() { - BigInteger datapathId = dataPathId(); - - GetFeaturesOutputBuilder featuresBuilder = new GetFeaturesOutputBuilder(); - featuresBuilder.setDatapathId(datapathId); - - SessionContextOFImpl sessionContextOFImpl = new SessionContextOFImpl(); - sessionContextOFImpl.setFeatures(featuresBuilder.build()); - - PacketInMessage message = createPacketInMessage(data, null); - - PacketInV10Translator packetInV10Translator = new PacketInV10Translator(); - - List salPacketIn = packetInV10Translator.translate(cookie, - sessionContextOFImpl, message); - - Assert.assertEquals(true, salPacketIn.isEmpty()); - - LOG.info("Test with null inPort parameter done."); - } - - /** - * test - * {@link PacketInV10Translator#translate(SwitchConnectionDistinguisher, SessionContext, OfHeader)} - * - translates packetIn from OF-API model to MD-SAL model, supports OF-1.0 - * - * @throws IOException - */ - @Test - public void testTranslate() { - BigInteger datapathId = dataPathId(); - - PacketInMessage message = createPacketInMessage(data, 5); - - GetFeaturesOutput featuresOutput = createGetFeatureOutput(datapathId); - initConnectionConductor(conductor, featuresOutput); - SessionContextOFImpl sessionContextOFImpl = new SessionContextOFImpl(); - sessionContextOFImpl.setFeatures(featuresOutput); - sessionContextOFImpl.setPrimaryConductor(conductor); - PacketInV10Translator packetInV10Translator = new PacketInV10Translator(); - List salPacketIn = packetInV10Translator.translate(cookie, - sessionContextOFImpl, message); - - Assert.assertEquals(Collections.singletonList(new PacketReceivedBuilder() - .setIngress(InventoryDataServiceUtil.nodeConnectorRefFromDatapathIdPortno(datapathId, (long) message.getInPort(), OpenflowVersion.OF10)) - .setPacketInReason(SendToController.class) - .setPayload(data) - .build()).toString(), salPacketIn.toString()); - - LOG.debug("Test translate done."); - } - - /** - * create datapathID - * - * @return BigInteger - */ - private static BigInteger dataPathId() { - byte[] datapathIdByte = new byte[EncodeConstants.SIZE_OF_LONG_IN_BYTES]; - for (int i = 0; i < datapathIdByte.length; i++) { - datapathIdByte[i] = 1; - } - return new BigInteger(1, datapathIdByte); - } - - /** - * generate message from string to byte[] - * - * @return byte[] - */ - private static byte[] messageData() { - String string = new String("sendOutputMsg_TEST"); - return string.getBytes(); - } - - /** - * create PacketInMessage with setting Version, InPort, Data, Reason - * - * @param data - * @param port - * @return PacketInMessage - */ - private static PacketInMessage createPacketInMessage(final byte[] data, - final java.lang.Integer port) { - PacketInReason reason = PacketInReason.OFPRACTION; - return new PacketInMessageBuilder() - .setVersion((short) EncodeConstants.OF10_VERSION_ID) - .setInPort(port).setData(data).setReason(reason).build(); - - } - - /** - * create cookie - * - * @return SwitchConnectionDistinguisher - */ - private static SwitchConnectionDistinguisher settingCookie() { - SwitchConnectionCookieOFImpl key = new SwitchConnectionCookieOFImpl(); - key.setAuxiliaryId((short) 1); - key.init(42); - return key; - } - - /** - * create GetFeatureOutput - * - * @param datapathId - * @return GetFeaturesOutput - */ - private static GetFeaturesOutput createGetFeatureOutput(final BigInteger datapathId) { - return new GetFeaturesOutputBuilder().setDatapathId(datapathId) - .setVersion((short) 0x01).build(); - } - - /** - * init connectionConductor - * - * @param connectionConductor - * @param featuresOutput - */ - private static void initConnectionConductor( - final ConnectionConductorImpl connectionConductor, - final GetFeaturesOutput featuresOutput) { - TranslatorKey paramK = new TranslatorKey(1, PacketInMessage.class.getSimpleName()); - Collection>> coll = new ArrayList<>(); - coll.add(new PacketInV10Translator()); - Map>>> translatorMapping = new HashMap<>(); - translatorMapping.put(paramK, coll); - - QueueProcessorLightImpl queueProcessor = new QueueProcessorLightImpl(); - queueProcessor.setTranslatorMapping(translatorMapping); - queueProcessor.init(); - connectionConductor.setQueueProcessor(queueProcessor); - connectionConductor.init(); - connectionConductor - .onHandshakeSuccessful(featuresOutput, (short) 0x01); - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/InventoryDataServiceUtilTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/InventoryDataServiceUtilTest.java index fa4fa11baa..474fe1b1c3 100644 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/InventoryDataServiceUtilTest.java +++ b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/InventoryDataServiceUtilTest.java @@ -8,34 +8,19 @@ package org.opendaylight.openflowplugin.openflow.md.util; import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.when; -import com.google.common.base.Optional; -import com.google.common.util.concurrent.Futures; + import java.math.BigInteger; -import java.util.List; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.controller.md.sal.binding.api.DataBroker; -import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction; -import org.opendaylight.controller.md.sal.binding.api.WriteTransaction; -import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.openflowplugin.api.openflow.md.util.OpenflowVersion; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFSessionUtil; -import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdatedBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId; 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.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.openflow.common.types.rev130731.PortNumberValuesV10; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; @@ -49,70 +34,6 @@ public class InventoryDataServiceUtilTest { private static final long PORT_NO = PortNumberValuesV10.CONTROLLER.getIntValue(); private static final BigInteger PATH_ID = BigInteger.TEN; - @Mock - DataBroker dataBroker; - @Mock - ReadOnlyTransaction readOnlyTransaction; - @Mock - WriteTransaction writeTransaction; - @Mock - Nodes nodes; - @Mock - Node node; - - - @Before - public void setupEnvironment() { - when(dataBroker.newReadOnlyTransaction()).thenReturn(readOnlyTransaction); - when(readOnlyTransaction.read(Mockito.any(LogicalDatastoreType.class), Mockito.>any())).thenReturn(Futures.immediateCheckedFuture(Optional.of(nodes))); - - OFSessionUtil.getSessionManager().setDataBroker(dataBroker); - - } - - @Test - /** - * Primitive test method for {@link InventoryDataServiceUtil#putNodeConnector(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId, org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector)} ()}. - */ - public void testPutNodeConnector(){ - when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction); - - NodeId nodeId = new NodeId("1"); - NodeConnectorBuilder nodeConnectorBuilder = new NodeConnectorBuilder(); - NodeConnectorId nodeConnectorId = new NodeConnectorId("1"); - nodeConnectorBuilder.setId(nodeConnectorId ); - nodeConnectorBuilder.setKey(new NodeConnectorKey(nodeConnectorId )); - InventoryDataServiceUtil.putNodeConnector(nodeId, nodeConnectorBuilder.build()); - } - - /** - * Primitive test method for {@link InventoryDataServiceUtil#readNode(org.opendaylight.yangtools.yang.binding.InstanceIdentifier)} ()}. - */ - @Test - public void testReadNode(){ - when(readOnlyTransaction.read(Mockito.any(LogicalDatastoreType.class), Mockito.>any())).thenReturn(Futures.immediateCheckedFuture(Optional.of(node))); - InstanceIdentifier instanceId = InstanceIdentifier.create(Node.class); - Node node = InventoryDataServiceUtil.readNode(instanceId); - assertNotNull(node); - } - /** - * Test method for {@link InventoryDataServiceUtil#checkForNodes()}. - */ - @Test - public void testCheckForNodes() { - Nodes nodes = InventoryDataServiceUtil.checkForNodes(); - assertNotNull(nodes); - } - - /** - * Test method for {@link InventoryDataServiceUtil#readAllNodes()}. - */ - @Test - public void testReadAllNodes() { - List nodes = InventoryDataServiceUtil.readAllNodes(); - assertNotNull(nodes); - } - /** * Test method for {@link InventoryDataServiceUtil#nodeUpdatedBuilderFromDataPathId(BigInteger datapathId)}. */ diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/PollableQueuesPriorityZipperTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/PollableQueuesPriorityZipperTest.java deleted file mode 100644 index a6a8da250e..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/PollableQueuesPriorityZipperTest.java +++ /dev/null @@ -1,90 +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.openflow.md.util; - -import java.util.ArrayList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.LinkedBlockingQueue; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.openflowplugin.api.openflow.md.util.PollableQueuesPriorityZipper; - -import com.google.common.collect.Lists; - -/** - * test for {@link PollableQueuesPriorityZipper} - */ -public class PollableQueuesPriorityZipperTest { - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.api.openflow.md.util.PollableQueuesPriorityZipper#poll()} - * . - */ - @Test - public void testPoll3() { - Queue l1 = new LinkedBlockingQueue(Lists.newArrayList( - "1", "2", "3")); - Queue l2 = new LinkedBlockingQueue(Lists.newArrayList( - "a", "b", "c", "d")); - Queue l3 = new LinkedBlockingQueue(Lists.newArrayList( - "A", "B")); - - PollableQueuesPriorityZipper zipper = new PollableQueuesPriorityZipper<>(); - zipper.setPrioritizedSource(l1); - zipper.addSource(l2); - zipper.addSource(l3); - - String[] expected = new String[] { "1", "2", "3", "a", "A", "b", "B", - "c", "d", null, "XXX" }; - List result = new ArrayList<>(); - while (true) { - String data = zipper.poll(); - result.add(data); - if (data == null) { - break; - } - } - l1.offer("XXX"); - result.add(zipper.poll()); - Assert.assertArrayEquals(expected, result.toArray()); - } - - /** - * Test method for - * {@link org.opendaylight.openflowplugin.api.openflow.md.util.PollableQueuesPriorityZipper#poll()} - * . - */ - @Test - public void testPoll2() { - Queue l1 = new LinkedBlockingQueue(Lists.newArrayList( - "1", "2", "3")); - Queue l3 = new LinkedBlockingQueue(Lists.newArrayList( - "A", "B")); - - PollableQueuesPriorityZipper zipper = new PollableQueuesPriorityZipper<>(); - zipper.setPrioritizedSource(l1); - zipper.addSource(l3); - - String[] expected = new String[] { "1", "2", "3", "A", "B", null, "XXX" }; - List result = new ArrayList<>(); - while (true) { - String data = zipper.poll(); - result.add(data); - if (data == null) { - break; - } - } - l1.offer("XXX"); - result.add(zipper.poll()); - Assert.assertArrayEquals(expected, result.toArray()); - } - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/PollableQueuesZipperTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/PollableQueuesZipperTest.java deleted file mode 100644 index 2d99296ae3..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/PollableQueuesZipperTest.java +++ /dev/null @@ -1,56 +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.openflow.md.util; - -import java.util.ArrayList; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.LinkedBlockingQueue; - -import org.junit.Assert; -import org.junit.Test; -import org.opendaylight.openflowplugin.api.openflow.md.util.PollableQueuesZipper; - -import com.google.common.collect.Lists; - -/** - * test for {@link PollableQueuesZipper} - */ -public class PollableQueuesZipperTest { - - /** - * Test method for {@link org.opendaylight.openflowplugin.api.openflow.md.util.PollableQueuesZipper#poll()}. - */ - @Test - public void testPoll() { - Queue l1 = new LinkedBlockingQueue(Lists.newArrayList("1", "2", "3")); - Queue l2 = new LinkedBlockingQueue(Lists.newArrayList("a", "b", "c", "d")); - Queue l3 = new LinkedBlockingQueue(Lists.newArrayList("A", "B")); - - PollableQueuesZipper zipper = new PollableQueuesZipper<>(); - zipper.addSource(l1); - zipper.addSource(l2); - zipper.addSource(l3); - - String[] expected = new String[] { - "1", "a", "A", "2", "b", "B", "3", "c", "d", null, "XXX" - }; - List result = new ArrayList<>(); - while (true) { - String data = zipper.poll(); - result.add(data); - if (data == null) { - break; - } - } - l1.offer("XXX"); - result.add(zipper.poll()); - Assert.assertArrayEquals(expected, result.toArray()); - } - -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/RoleUtilTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/RoleUtilTest.java deleted file mode 100644 index e46c040f43..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/RoleUtilTest.java +++ /dev/null @@ -1,190 +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.openflow.md.util; - -import java.math.BigInteger; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext; -import org.opendaylight.openflowplugin.openflow.md.core.session.OFRoleManager; -import org.opendaylight.openflowplugin.openflow.md.core.session.RolePushException; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.ControllerRole; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequest; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestInput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutput; -import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.RoleRequestOutputBuilder; -import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole; -import org.opendaylight.yangtools.yang.common.RpcResult; -import org.opendaylight.yangtools.yang.common.RpcResultBuilder; - -import com.google.common.util.concurrent.Futures; - -/** - * testing {@link RoleUtil} - */ -@RunWith(MockitoJUnitRunner.class) -public class RoleUtilTest { - - @Mock - private SessionContext session; - @Mock - private GetFeaturesOutput features; - @Mock - private ConnectionConductor primaryConductor; - @Mock - private ConnectionAdapter connectionAdapter; - - private final BigInteger generationId = BigInteger.TEN; - private RoleRequestOutput roleRequestOutput; - - /** - * prepare values - */ - @Before - public void setUp() { - Mockito.when(session.getFeatures()).thenReturn(features); - Mockito.when(features.getVersion()).thenReturn(Short.valueOf((short) 42)); - Mockito.when(session.getNextXid()).thenReturn(84L); - Mockito.when(session.getPrimaryConductor()).thenReturn(primaryConductor); - Mockito.when(primaryConductor.getConnectionAdapter()).thenReturn(connectionAdapter); - roleRequestOutput = new RoleRequestOutputBuilder() - .setGenerationId(generationId) - .setRole(ControllerRole.OFPCRROLESLAVE) - .setVersion((short) 42) - .setXid(21L) - .build(); - Mockito.when(connectionAdapter.roleRequest(Matchers.any(RoleRequestInput.class))) - .thenReturn(Futures.immediateFuture(RpcResultBuilder.success(roleRequestOutput).build())); - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#toOFJavaRole(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole)}. - */ - @Test - public void testToOFJavaRole() { - Assert.assertEquals(ControllerRole.OFPCRROLEMASTER, RoleUtil.toOFJavaRole(OfpRole.BECOMEMASTER)); - Assert.assertEquals(ControllerRole.OFPCRROLESLAVE, RoleUtil.toOFJavaRole(OfpRole.BECOMESLAVE)); - Assert.assertEquals(ControllerRole.OFPCRROLENOCHANGE, RoleUtil.toOFJavaRole(OfpRole.NOCHANGE)); - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#toOFJavaRole(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole)}. - */ - @Test(expected = NullPointerException.class) - public void testToOFJavaRoleNull() { - RoleUtil.toOFJavaRole(null); - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#createRoleRequestInput(org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole, java.math.BigInteger)}. - */ - @Test - public void testCreateRuleRequestInput() { - RoleRequestInput roleRequestInput = RoleUtil.createRoleRequestInput(session, OfpRole.BECOMEMASTER, generationId).build(); - Assert.assertEquals(generationId, roleRequestInput.getGenerationId()); - Assert.assertEquals(RoleRequestInput.class, roleRequestInput.getImplementedInterface()); - Assert.assertEquals(ControllerRole.OFPCRROLEMASTER, roleRequestInput.getRole()); - Assert.assertEquals(42, roleRequestInput.getVersion().intValue()); - Assert.assertEquals(84L, roleRequestInput.getXid().longValue()); - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#sendRoleChangeRequest(org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext, org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow.common.config.impl.rev140326.OfpRole, java.math.BigInteger)}. - * @throws Exception - */ - @Test - public void testSendRoleChangeRequest() throws Exception { - Future> roleRequestOutputFx = RoleUtil.sendRoleChangeRequest(session, OfpRole.BECOMEMASTER, generationId); - Assert.assertNotNull(roleRequestOutputFx); - - ArgumentCaptor roleRequestCaptor = ArgumentCaptor.forClass(RoleRequestInput.class); - Mockito.verify(connectionAdapter).roleRequest(roleRequestCaptor.capture()); - - RoleRequest roleRequestInput = roleRequestCaptor.getValue(); - Assert.assertEquals(generationId, roleRequestInput.getGenerationId()); - Assert.assertEquals(RoleRequestInput.class, roleRequestInput.getImplementedInterface()); - Assert.assertEquals(ControllerRole.OFPCRROLEMASTER, roleRequestInput.getRole()); - Assert.assertEquals(42, roleRequestInput.getVersion().intValue()); - Assert.assertEquals(84L, roleRequestInput.getXid().longValue()); - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#readGenerationIdFromDevice(org.opendaylight.openflowplugin.api.openflow.md.core.session.SessionContext)}. - * @throws Exception - */ - @Test - public void testReadGenerationIdFromDevice() throws Exception { - BigInteger generationIdFromDevice = RoleUtil.readGenerationIdFromDevice(session).get(); - Assert.assertEquals(generationId, generationIdFromDevice); - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#getNextGenerationId(java.math.BigInteger)}. - */ - @Test - public void testGetNextGenerationId() { - BigInteger[] src = new BigInteger[] { - BigInteger.ZERO, - BigInteger.ONE, - OFRoleManager.MAX_GENERATION_ID.subtract(BigInteger.ONE), - OFRoleManager.MAX_GENERATION_ID - }; - - BigInteger[] out = new BigInteger[] { - BigInteger.ONE, - BigInteger.valueOf(2L), - OFRoleManager.MAX_GENERATION_ID, - BigInteger.ZERO - }; - - for (int i = 0; i < src.length; i++) { - BigInteger nextGenerationId = RoleUtil.getNextGenerationId(src[i]); - Assert.assertEquals(out[i], nextGenerationId); - } - } - - /** - * Test method for {@link org.opendaylight.openflowplugin.openflow.md.util.RoleUtil#makeCheckedRuleRequestFxResult(com.google.common.util.concurrent.ListenableFuture)}. - * @throws Exception - */ - @Test - public void testMakeCheckedRuleRequestFxResult() throws Exception { - String message = "me sooo naughty!"; - try { - RoleUtil.makeCheckedRuleRequestFxResult(Futures.immediateFailedFuture(new Exception(message))).checkedGet(); - } catch (Exception e) { - Assert.assertEquals(RolePushException.class, e.getClass()); - Assert.assertEquals(ExecutionException.class, e.getCause().getClass()); - Assert.assertEquals(Exception.class, e.getCause().getCause().getClass()); - Assert.assertNull(e.getCause().getCause().getCause()); - Assert.assertEquals(message, e.getCause().getCause().getMessage()); - } - - try { - RoleUtil.makeCheckedRuleRequestFxResult(Futures.immediateFailedFuture(new RolePushException(message))).checkedGet(); - } catch (Exception e) { - Assert.assertEquals(RolePushException.class, e.getClass()); - Assert.assertNull(e.getCause()); - Assert.assertEquals(message, e.getMessage()); - } - - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/WrapperQueueImplTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/WrapperQueueImplTest.java deleted file mode 100644 index 474c6f1b86..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/openflow/md/util/WrapperQueueImplTest.java +++ /dev/null @@ -1,170 +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.openflow.md.util; - -import java.util.Queue; -import java.util.concurrent.ArrayBlockingQueue; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.opendaylight.openflowplugin.api.openflow.md.core.ConnectionConductor; -import org.opendaylight.openflowplugin.api.openflow.md.queue.WaterMarkListener; -import org.opendaylight.openflowplugin.openflow.md.queue.WrapperQueueImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@RunWith(MockitoJUnitRunner.class) -public class WrapperQueueImplTest { - - protected static final Logger LOG = LoggerFactory - .getLogger(WrapperQueueImplTest.class); - - @Mock - private ConnectionConductor connectionConductor; - - @Mock - private WaterMarkListener waterMarkListener; - - private WrapperQueueImpl wrapperQueueImpl; - private final int capacity = 100; - private Queue queueDefault; - private int highWaterMark = 80; - private int lowWaterMark = 65; - - /** - * Setup before tests - */ - @Before - public void setUp() { - queueDefault = new ArrayBlockingQueue<>(capacity); - - wrapperQueueImpl = new WrapperQueueImpl<>(capacity, queueDefault, - waterMarkListener); - } - - /** - * Test for check if wrapper is not null - */ - @Test - public void testWrapperQueueImpl() { - Assert.assertNotNull("Wrapper can not be null.", wrapperQueueImpl); - } - - /** - * Test for set setAutoRead on false on high water mark - */ - @Test - public void testReadOnHighWaterMark() { - - Assert.assertFalse("Wrapper must be not flooded at the start.", - wrapperQueueImpl.isFlooded()); - - push(79); - Assert.assertFalse("Wrapper should not be flooded.", - wrapperQueueImpl.isFlooded()); - Mockito.verify(waterMarkListener, Mockito.times(0)).onHighWaterMark(); - - push(1); - Assert.assertTrue("Wrapper should be flooded.", - wrapperQueueImpl.isFlooded()); - Mockito.verify(waterMarkListener, Mockito.times(1)).onHighWaterMark(); - - Assert.assertEquals( - "Size of queue has to be equals to 80% of capacity of queue", - highWaterMark, queueDefault.size()); - } - - /** - * - */ - private void push(int size) { - for (int i = 0; i < size; i++) { - try { - wrapperQueueImpl.offer(i); - } catch (Exception e) { - LOG.error("Failed to offer item to queue.", e); - } - } - } - - /** - * Test for setAutoRead on true on low water mark - */ - @Test - public void testReadOnLowWaterMark() { - Mockito.verify(waterMarkListener, Mockito.times(0)).onHighWaterMark(); - push(80); - Assert.assertTrue("Wrapper should be flooded.", - wrapperQueueImpl.isFlooded()); - Mockito.verify(waterMarkListener, Mockito.times(1)).onHighWaterMark(); - - Assert.assertEquals( - "Size of queue has to be equals to 80% of capacity of queue", - highWaterMark, queueDefault.size()); - - poll(14); - Mockito.verify(waterMarkListener, Mockito.times(0)).onLowWaterMark(); - Assert.assertTrue("Wrapper should be still flooded.", - wrapperQueueImpl.isFlooded()); - - poll(1); - Mockito.verify(waterMarkListener, Mockito.times(1)).onLowWaterMark(); - - Assert.assertEquals( - "Size of queue has to be equals to 65% on lowWaterMark.", - lowWaterMark, queueDefault.size()); - Assert.assertFalse("Wrapped should be not flooded.", - wrapperQueueImpl.isFlooded()); - } - - /** - * Polling messages - */ - private void poll(int size) { - - for (int i = 0; i < size; i++) { - wrapperQueueImpl.poll(); - } - } - - /** - * Test for one cycle. - */ - @Test - public void testEndReadOnHWMStartOnLWM() { - - Assert.assertFalse("Wrapper should not be flooded", - wrapperQueueImpl.isFlooded()); - Mockito.verify(waterMarkListener, Mockito.times(0)).onLowWaterMark(); - Mockito.verify(waterMarkListener, Mockito.times(0)).onHighWaterMark(); - - push(81); - Assert.assertTrue("Wrapper should be flooded", - wrapperQueueImpl.isFlooded()); - Mockito.verify(waterMarkListener, Mockito.times(0)).onLowWaterMark(); - Mockito.verify(waterMarkListener, Mockito.times(1)).onHighWaterMark(); - - poll(17); - Assert.assertFalse("Wrapper should not be flooded", - wrapperQueueImpl.isFlooded()); - Mockito.verify(waterMarkListener, Mockito.times(1)).onLowWaterMark(); - Mockito.verify(waterMarkListener, Mockito.times(1)).onHighWaterMark(); - - push(18); - Assert.assertTrue("Wrapper should be flooded", - wrapperQueueImpl.isFlooded()); - - Mockito.verify(waterMarkListener, Mockito.times(1)).onLowWaterMark(); - Mockito.verify(waterMarkListener, Mockito.times(2)).onHighWaterMark(); - } -} diff --git a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/statistics/MessageSpyCounterImplTest.java b/openflowplugin/src/test/java/org/opendaylight/openflowplugin/statistics/MessageSpyCounterImplTest.java deleted file mode 100644 index 49f1a8a2e1..0000000000 --- a/openflowplugin/src/test/java/org/opendaylight/openflowplugin/statistics/MessageSpyCounterImplTest.java +++ /dev/null @@ -1,48 +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.statistics; - -import static org.junit.Assert.assertEquals; - -import java.util.List; -import org.junit.Test; -import org.opendaylight.openflowplugin.api.openflow.statistics.MessageSpy; -import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.Action; -import org.opendaylight.yangtools.yang.binding.DataContainer; - -/** - * Created by Martin Bobak mbobak@cisco.com on 9/10/14. - */ -public class MessageSpyCounterImplTest { - - private static final MessageSpyCounterImpl messageSpyCounter = new MessageSpyCounterImpl(); - private static final int EXPECTED_MSG_COUNT = 10; - - @Test - public void testDumpMessageCounts() { - DataContainer msg = new MockDataContainer(); - List messageCounts = messageSpyCounter.dumpMessageCounts(); - assertEquals(EXPECTED_MSG_COUNT,messageCounts.size()); - - assertEquals("FROM_SWITCH_ENQUEUED: no activity detected", messageCounts.get(0)); - messageSpyCounter.spyMessage(msg, MessageSpy.StatisticsGroup.FROM_SWITCH_ENQUEUED); - messageCounts = messageSpyCounter.dumpMessageCounts(); - assertEquals("FROM_SWITCH_ENQUEUED: MSG[Action] -> +1 | 1", messageCounts.get(0)); - - } - - - private static class MockDataContainer implements DataContainer { - - @Override - public Class getImplementedInterface() { - return Action.class; - } - } -} -- 2.36.6