From c267214dc3b211c85271e342cd0b2d8024990048 Mon Sep 17 00:00:00 2001 From: "Claudio D. Gasparini" Date: Wed, 16 Nov 2016 15:11:44 +0100 Subject: [PATCH] BUG-5032: BGP Operational State Implement BGP Operational State per Global and Neighbor. Operational State per PeerGroup is also implemented and will need to be plug in once Peer Group is supported. Change-Id: Ic1a75348e370bdd06777267c153b924acc3b4c15 Signed-off-by: Claudio D. Gasparini --- .../protocol/bgp/state/NeighborUtil.java | 29 +- .../bgp/rib/impl/AdjRibOutListener.java | 10 +- .../bgp/rib/impl/ApplicationPeer.java | 49 +++- .../protocol/bgp/rib/impl/BGPPeer.java | 95 +++++-- .../protocol/bgp/rib/impl/BGPSessionImpl.java | 50 +++- .../bgp/rib/impl/EffectiveRibInWriter.java | 164 +++++++---- .../protocol/bgp/rib/impl/LocRibWriter.java | 59 ++-- .../protocol/bgp/rib/impl/RIBImpl.java | 22 +- .../protocol/bgp/rib/impl/config/AppPeer.java | 27 +- .../bgp/rib/impl/config/BgpDeployerImpl.java | 10 + .../protocol/bgp/rib/impl/config/BgpPeer.java | 45 ++- .../impl/config/OpenConfigMappingUtil.java | 73 ++--- .../protocol/bgp/rib/impl/config/RibImpl.java | 28 +- .../bgp/rib/impl/spi/BGPMessagesListener.java | 31 +++ .../rib/impl/spi/BGPSessionStateListener.java | 43 +++ .../bgp/rib/impl/spi/InstanceType.java | 18 +- .../bgp/rib/impl/state/BGPPeerStateImpl.java | 258 ++++++++++++++++++ .../bgp/rib/impl/state/BGPRIBStateImpl.java | 101 +++++++ .../rib/impl/state/BGPSessionStateImpl.java | 185 +++++++++++++ .../impl/state/BGPSessionStateProvider.java | 43 +++ .../rib/impl/state/BGPStateCollectorImpl.java | 19 +- .../state/peer/PrefixesInstalledCounters.java | 30 ++ .../state/peer/PrefixesReceivedCounters.java | 38 +++ .../impl/state/peer/PrefixesSentCounters.java | 20 ++ .../rib/impl/state/rib/TotalPathsCounter.java | 20 ++ .../impl/state/rib/TotalPrefixesCounter.java | 20 ++ .../bgp/rib/impl/stats/peer/BGPPeerStats.java | 2 - .../rib/impl/stats/peer/BGPPeerStatsImpl.java | 21 +- .../impl/stats/peer/BGPSessionStatsImpl.java | 17 +- .../peer/route/PerTableTypeRouteCounter.java | 8 + .../impl/stats/rib/impl/BGPRenderStats.java | 4 - .../stats/rib/impl/BGPRenderStatsImpl.java | 40 +-- .../rib/impl/RIBImplRuntimeMXBeanImpl.java | 16 +- .../bgp/rib/impl/AbstractAddPathTest.java | 16 +- .../bgp/rib/impl/AddPathAllPathsTest.java | 3 +- .../bgp/rib/impl/ParserToSalTest.java | 10 +- .../protocol/bgp/rib/impl/PeerTest.java | 41 ++- .../impl/SynchronizationAndExceptionTest.java | 26 +- .../bgp/rib/impl/config/AbstractConfig.java | 19 +- .../bgp/rib/impl/config/AppPeerTest.java | 5 +- .../rib/impl/config/BgpDeployerImplTest.java | 8 +- .../bgp/rib/impl/config/BgpPeerTest.java | 14 +- .../config/OpenConfigMappingUtilTest.java | 10 +- .../rib/impl/BGPRenderStatsImplTest.java | 47 +++- .../rib/spi/state/BGPPeerMessagesState.java | 42 +++ .../bgp/rib/spi/state/BGPPeerState.java | 6 + .../bgp/rib/spi/state/BGPSessionState.java | 28 -- .../bgp/testtool/TestingListener.java | 7 +- 48 files changed, 1516 insertions(+), 361 deletions(-) create mode 100644 bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/BGPMessagesListener.java create mode 100644 bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/BGPSessionStateListener.java create mode 100644 bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPPeerStateImpl.java create mode 100644 bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPRIBStateImpl.java create mode 100644 bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPSessionStateImpl.java create mode 100644 bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPSessionStateProvider.java create mode 100644 bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/peer/PrefixesInstalledCounters.java create mode 100644 bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/peer/PrefixesReceivedCounters.java create mode 100644 bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/peer/PrefixesSentCounters.java create mode 100644 bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/rib/TotalPathsCounter.java create mode 100644 bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/rib/TotalPrefixesCounter.java create mode 100644 bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/state/BGPPeerMessagesState.java diff --git a/bgp/openconfig-state/src/main/java/org/opendaylight/protocol/bgp/state/NeighborUtil.java b/bgp/openconfig-state/src/main/java/org/opendaylight/protocol/bgp/state/NeighborUtil.java index 220f2685b5..ecc08969e5 100644 --- a/bgp/openconfig-state/src/main/java/org/opendaylight/protocol/bgp/state/NeighborUtil.java +++ b/bgp/openconfig-state/src/main/java/org/opendaylight/protocol/bgp/state/NeighborUtil.java @@ -24,6 +24,7 @@ import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState; import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState; import org.opendaylight.protocol.bgp.rib.spi.state.BGPGracelfulRestartState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerMessagesState; import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerState; import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState; import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState; @@ -118,7 +119,7 @@ public final class NeighborUtil { @Nonnull final BGPTableTypeRegistryConsumer bgpTableTypeRegistry) { return new NeighborBuilder() .setNeighborAddress(neighbor.getNeighborAddress()) - .setState(buildNeighborState(neighbor.getBGPSessionState())) + .setState(buildNeighborState(neighbor.getBGPSessionState(), neighbor.getBGPPeerMessagesState())) .setTimers(buildTimer(neighbor.getBGPTimersState())) .setTransport(buildTransport(neighbor.getBGPTransportState())) .setErrorHandling(buildErrorHandling(neighbor.getBGPErrorHandlingState())) @@ -130,18 +131,24 @@ public final class NeighborUtil { /** * Builds Neighbor State from BGPPeerState counters * - * @param neighbor BGPPeerState containing Operational state counters + * @param sessionState BGPPeerState containing Operational state counters + * @param bgpPeerMessagesState * @return Neighbor State */ @Nullable - public static State buildNeighborState(@Nullable final BGPSessionState neighbor) { - if (neighbor == null) { + public static State buildNeighborState(@Nullable final BGPSessionState sessionState, + final BGPPeerMessagesState bgpPeerMessagesState) { + if (sessionState == null && bgpPeerMessagesState == null) { return null; } - return new StateBuilder() - .addAugmentation(NeighborStateAugmentation.class, buildCapabilityState(neighbor)) - .addAugmentation(BgpNeighborStateAugmentation.class, - buildMessageState(neighbor)).build(); + final StateBuilder builder = new StateBuilder(); + if (sessionState != null) { + builder.addAugmentation(NeighborStateAugmentation.class, buildCapabilityState(sessionState)); + } + if (bgpPeerMessagesState != null) { + builder.addAugmentation(BgpNeighborStateAugmentation.class, buildMessageState(bgpPeerMessagesState)); + } + return builder.build(); } /** @@ -262,14 +269,14 @@ public final class NeighborUtil { * @return BgpNeighborState containing Message State */ @Nonnull - public static BgpNeighborStateAugmentation buildMessageState(@Nonnull final BGPSessionState neighbor) { + public static BgpNeighborStateAugmentation buildMessageState(@Nonnull final BGPPeerMessagesState neighbor) { return new BgpNeighborStateAugmentationBuilder() .setMessages(new MessagesBuilder() .setReceived(buildMessagesReceived(neighbor)) .setSent(buildMessagesSent(neighbor)).build()).build(); } - private static Received buildMessagesReceived(@Nonnull final BGPSessionState neighbor) { + private static Received buildMessagesReceived(@Nonnull final BGPPeerMessagesState neighbor) { return new ReceivedBuilder() .setUPDATE(toBigInteger(neighbor.getUpdateMessagesReceivedCount())) .setNOTIFICATION(toBigInteger(neighbor.getNotificationMessagesReceivedCount())) @@ -280,7 +287,7 @@ public final class NeighborUtil { return UnsignedLong.valueOf(updateReceivedCounter).bigIntegerValue(); } - private static Sent buildMessagesSent(@Nonnull final BGPSessionState neighbor) { + private static Sent buildMessagesSent(@Nonnull final BGPPeerMessagesState neighbor) { return new SentBuilder() .setUPDATE(toBigInteger(neighbor.getUpdateMessagesSentCount())) .setNOTIFICATION(toBigInteger(neighbor.getNotificationMessagesSentCount())) diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/AdjRibOutListener.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/AdjRibOutListener.java index 4dddf38128..fff71369cb 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/AdjRibOutListener.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/AdjRibOutListener.java @@ -21,6 +21,7 @@ import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService; import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier; import org.opendaylight.protocol.bgp.rib.impl.spi.Codecs; import org.opendaylight.protocol.bgp.rib.impl.spi.CodecsRegistry; +import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesSentCounters; import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils; import org.opendaylight.protocol.bgp.rib.spi.RIBSupport; import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils; @@ -52,7 +53,7 @@ import org.slf4j.LoggerFactory; * performs transcoding to BA form (message) and sends it down the channel. */ @NotThreadSafe -final class AdjRibOutListener implements ClusteredDOMDataTreeChangeListener { +final class AdjRibOutListener implements ClusteredDOMDataTreeChangeListener, PrefixesSentCounters { private static final Logger LOG = LoggerFactory.getLogger(AdjRibOutListener.class); @@ -65,6 +66,7 @@ final class AdjRibOutListener implements ClusteredDOMDataTreeChangeListener { private final boolean mpSupport; private final ListenerRegistration registerDataTreeChangeListener; private final LongAdder routeCounter; + private final LongAdder prefixesSentCounter = new LongAdder(); private AdjRibOutListener(final PeerId peerId, final TablesKey tablesKey, final YangInstanceIdentifier ribId, final CodecsRegistry registry, final RIBSupport support, final DOMDataTreeChangeService service, @@ -146,6 +148,7 @@ final class AdjRibOutListener implements ClusteredDOMDataTreeChangeListener { private Update advertise(final MapEntryNode route) { this.routeCounter.increment(); + this.prefixesSentCounter.increment(); if (!this.mpSupport) { return buildUpdate(Collections.singleton(route), Collections.emptyList(), routeAttributes(route)); } @@ -176,4 +179,9 @@ final class AdjRibOutListener implements ClusteredDOMDataTreeChangeListener { boolean isMpSupported() { return this.mpSupport; } + + @Override + public long getPrefixesSentCount() { + return this.prefixesSentCounter.longValue(); + } } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/ApplicationPeer.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/ApplicationPeer.java index cfdedff7e0..3a02b9b789 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/ApplicationPeer.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/ApplicationPeer.java @@ -27,12 +27,20 @@ import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction; import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain; import org.opendaylight.protocol.bgp.rib.impl.spi.RIB; import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry; +import org.opendaylight.protocol.bgp.rib.impl.state.BGPPeerStateImpl; +import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl; import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStats; import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStatsImpl; import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker; import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils; import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils; import org.opendaylight.protocol.bgp.rib.spi.RouterIds; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState; +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.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.ApplicationRibId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId; @@ -65,7 +73,8 @@ import org.slf4j.LoggerFactory; * For purposed of import policies such as Best Path Selection, application * peer needs to have a BGP-ID that is configurable. */ -public class ApplicationPeer implements AutoCloseable, org.opendaylight.protocol.bgp.rib.spi.Peer, ClusteredDOMDataTreeChangeListener, TransactionChainListener { +public class ApplicationPeer extends BGPPeerStateImpl implements AutoCloseable, + org.opendaylight.protocol.bgp.rib.spi.Peer, ClusteredDOMDataTreeChangeListener, TransactionChainListener { private static final Logger LOG = LoggerFactory.getLogger(ApplicationPeer.class); @@ -79,10 +88,9 @@ public class ApplicationPeer implements AutoCloseable, org.opendaylight.protocol private DOMTransactionChain writerChain; private EffectiveRibInWriter effectiveRibInWriter; private AdjRibInWriter adjRibInWriter; - private BGPPeerStats peerStats; private ListenerRegistration registration; private final Set supportedTables = new HashSet<>(); - + private final BGPSessionStateImpl bgpSessionState = new BGPSessionStateImpl(); @FunctionalInterface interface RegisterAppPeerListener { @@ -93,6 +101,8 @@ public class ApplicationPeer implements AutoCloseable, org.opendaylight.protocol } public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address ipAddress, final RIB rib) { + super(rib.getInstanceIdentifier(), "application-peers", new IpAddress(ipAddress), rib.getLocalTablesKeys(), + Collections.emptySet()); this.name = applicationRibId.getValue(); final RIB targetRib = Preconditions.checkNotNull(rib); this.rawIdentifier = InetAddresses.forString(ipAddress.getValue()).getAddress(); @@ -118,6 +128,7 @@ public class ApplicationPeer implements AutoCloseable, org.opendaylight.protocol } this.supportedTables.add(RibSupportUtils.toYangTablesKey(tablesKey)); }); + setAdvertizedGracefulRestartTableTypes(Collections.emptyList()); this.adjRibInWriter = AdjRibInWriter.create(this.rib.getYangRibId(), PeerRole.Internal, simpleRoutingPolicy, this.writerChain); final RIBSupportContextRegistry context = this.rib.getRibSupportContext(); @@ -130,10 +141,11 @@ public class ApplicationPeer implements AutoCloseable, org.opendaylight.protocol }; this.adjRibInWriter = this.adjRibInWriter.transform(peerId, context, localTables, Collections.emptyMap(), registerAppPeerListener); - this.peerStats = new BGPPeerStatsImpl(localTables); + final BGPPeerStats peerStats = new BGPPeerStatsImpl(this.name, localTables, this); this.effectiveRibInWriter = EffectiveRibInWriter.create(this.rib.getService(), this.rib.createPeerChain(this), this.peerIId, - this.rib.getImportPolicyPeerTracker(), context, PeerRole.Internal, this.peerStats.getEffectiveRibInRouteCounters(), - this.peerStats.getAdjRibInRouteCounters()); + this.rib.getImportPolicyPeerTracker(), context, PeerRole.Internal, + peerStats.getAdjRibInRouteCounters(), localTables); + this.bgpSessionState.registerMessagesCounter(this); } /** @@ -274,4 +286,29 @@ public class ApplicationPeer implements AutoCloseable, org.opendaylight.protocol public void onTransactionChainSuccessful(final TransactionChain chain) { LOG.debug("Transaction chain {} successful.", chain); } + + @Override + public BGPErrorHandlingState getBGPErrorHandlingState() { + return this; + } + + @Override + public BGPAfiSafiState getBGPAfiSafiState() { + return this; + } + + @Override + public BGPSessionState getBGPSessionState() { + return this.bgpSessionState; + } + + @Override + public BGPTimersState getBGPTimersState() { + return this.bgpSessionState; + } + + @Override + public BGPTransportState getBGPTransportState() { + return this.bgpSessionState; + } } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPPeer.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPPeer.java index da76554016..fd8205233f 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPPeer.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPPeer.java @@ -24,6 +24,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import javax.annotation.Nonnull; import javax.annotation.concurrent.GuardedBy; import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeMXBean; import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeRegistration; @@ -42,6 +43,8 @@ import org.opendaylight.protocol.bgp.parser.impl.message.update.LocalPreferenceA import org.opendaylight.protocol.bgp.parser.spi.MessageUtil; import org.opendaylight.protocol.bgp.rib.impl.spi.RIB; import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext; +import org.opendaylight.protocol.bgp.rib.impl.state.BGPPeerStateImpl; +import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateProvider; import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStats; import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStatsImpl; import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPSessionStats; @@ -52,7 +55,14 @@ import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker; import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils; import org.opendaylight.protocol.bgp.rib.spi.Peer; import org.opendaylight.protocol.bgp.rib.spi.RouterIds; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState; import org.opendaylight.protocol.concepts.AbstractRegistration; +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.Ipv4Prefix; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.DestinationIpv4Builder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.prefixes.destination.ipv4.Ipv4Prefixes; @@ -93,8 +103,8 @@ import org.slf4j.LoggerFactory; * Class representing a peer. We have a single instance for each peer, which provides translation from BGP events into * RIB actions. */ -public class BGPPeer implements BGPSessionListener, Peer, AutoCloseable, BGPPeerRuntimeMXBean, TransactionChainListener { - +public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Peer, AutoCloseable, + BGPPeerRuntimeMXBean, TransactionChainListener { private static final Logger LOG = LoggerFactory.getLogger(BGPPeer.class); @GuardedBy("this") @@ -123,25 +133,32 @@ public class BGPPeer implements BGPSessionListener, Peer, AutoCloseable, BGPPeer private YangInstanceIdentifier peerIId; private final Set tableRegistration = new HashSet<>(); - public BGPPeer(final String name, final RIB rib, final PeerRole role, final SimpleRoutingPolicy peerStatus, final RpcProviderRegistry rpcRegistry) { + public BGPPeer(final String name, final RIB rib, final PeerRole role, final SimpleRoutingPolicy peerStatus, + final RpcProviderRegistry rpcRegistry, + @Nonnull final Set afiSafisAdvertized, + @Nonnull final Set afiSafisGracefulAdvertized) { + //FIXME BUG-6971 Once Peer Group is implemented, pass it + super(rib.getInstanceIdentifier(), null, new IpAddress(new Ipv4Address(name)), afiSafisAdvertized, + afiSafisGracefulAdvertized); this.peerRole = role; this.simpleRoutingPolicy = Optional.ofNullable(peerStatus); this.rib = Preconditions.checkNotNull(rib); this.name = name; this.rpcRegistry = rpcRegistry; - this.peerStats = new BGPPeerStatsImpl(this.tables); - + this.peerStats = new BGPPeerStatsImpl(this.name, this.tables, this); this.chain = rib.createPeerChain(this); } - public BGPPeer(final String name, final RIB rib, final PeerRole role, final RpcProviderRegistry rpcRegistry) { - this(name, rib, role, null, rpcRegistry); + public BGPPeer(final String name, final RIB rib, final PeerRole role, + final RpcProviderRegistry rpcRegistry, @Nonnull final Set afiSafisAdvertized, + @Nonnull final Set afiSafisGracefulAdvertized) { + this(name, rib, role, null, rpcRegistry, afiSafisAdvertized, afiSafisGracefulAdvertized); } public void instantiateServiceInstance() { // add current peer to "configured BGP peer" stats this.rib.getRenderStats().getConfiguredPeerCounter().increment(); - this.ribWriter = AdjRibInWriter.create(rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy, this.chain); + this.ribWriter = AdjRibInWriter.create(this.rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy, this.chain); } @Override @@ -286,15 +303,22 @@ public class BGPPeer implements BGPSessionListener, Peer, AutoCloseable, BGPPeer @Override public synchronized void onSessionUp(final BGPSession session) { + this.session = session; + if (this.session instanceof BGPSessionStateProvider) { + ((BGPSessionStateProvider) this.session).registerMessagesCounter(this); + } + final List addPathTablesType = session.getAdvertisedAddPathTableTypes(); final Set advertizedTableTypes = session.getAdvertisedTableTypes(); + final List advertizedGracefulRestartTableTypes = session.getAdvertisedGracefulRestartTableTypes(); LOG.info("Session with peer {} went up with tables {} and Add Path tables {}", this.name, advertizedTableTypes, addPathTablesType); - this.session = session; - this.rawIdentifier = InetAddresses.forString(session.getBgpId().getValue()).getAddress(); final PeerId peerId = RouterIds.createPeerId(session.getBgpId()); this.tables.addAll(advertizedTableTypes.stream().map(t -> new TablesKey(t.getAfi(), t.getSafi())).collect(Collectors.toList())); + + setAdvertizedGracefulRestartTableTypes(advertizedGracefulRestartTableTypes.stream() + .map(t -> new TablesKey(t.getAfi(), t.getSafi())).collect(Collectors.toList())); final boolean announceNone = isAnnounceNone(this.simpleRoutingPolicy); final Map addPathTableMaps = mapTableTypesFamilies(addPathTablesType); this.peerIId = this.rib.getYangRibId().node(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer.QNAME) @@ -313,9 +337,10 @@ public class BGPPeer implements BGPSessionListener, Peer, AutoCloseable, BGPPeer addBgp4Support(peerId, announceNone); if(!isLearnNone(this.simpleRoutingPolicy)) { - this.effRibInWriter = EffectiveRibInWriter.create(this.rib.getService(), this.rib.createPeerChain(this), this.peerIId, - this.rib.getImportPolicyPeerTracker(), this.rib.getRibSupportContext(), this.peerRole, - this.peerStats.getEffectiveRibInRouteCounters(), this.peerStats.getAdjRibInRouteCounters()); + this.effRibInWriter = EffectiveRibInWriter.create(this.rib.getService(), this.rib.createPeerChain(this), + this.peerIId, this.rib.getImportPolicyPeerTracker(), this.rib.getRibSupportContext(), this.peerRole, + this.peerStats.getAdjRibInRouteCounters(), this.tables); + registerPrefixesCounters(this.effRibInWriter, this.effRibInWriter); } this.ribWriter = this.ribWriter.transform(peerId, this.rib.getRibSupportContext(), this.tables, addPathTableMaps); @@ -352,9 +377,12 @@ public class BGPPeer implements BGPSessionListener, Peer, AutoCloseable, BGPPeer // not particularly nice if (context != null && this.session instanceof BGPSessionImpl) { - this.adjRibOutListenerSet.put(key, AdjRibOutListener.create(peerId, key, this.rib.getYangRibId(), this.rib.getCodecsRegistry(), - context.getRibSupport(), this.rib.getService(), ((BGPSessionImpl) this.session).getLimiter(), mpSupport, - this.peerStats.getAdjRibOutRouteCounters().init(key))); + final ChannelOutputLimiter limiter = ((BGPSessionImpl) this.session).getLimiter(); + final AdjRibOutListener adjRibOut = AdjRibOutListener.create(peerId, key, + this.rib.getYangRibId(), this.rib.getCodecsRegistry(), context.getRibSupport(), + this.rib.getService(), limiter, mpSupport, this.peerStats.getAdjRibOutRouteCounters().init(key)); + this.adjRibOutListenerSet.put(key, adjRibOut); + registerPrefixesSentCounter(key, adjRibOut); } } @@ -412,6 +440,7 @@ public class BGPPeer implements BGPSessionListener, Peer, AutoCloseable, BGPPeer closeRegistration(); cleanup(); dropConnection(); + resetState(); } private void closeRegistration() { @@ -491,4 +520,38 @@ public class BGPPeer implements BGPSessionListener, Peer, AutoCloseable, BGPPeer return ImmutableMap.copyOf(addPathTablesType.stream().collect(Collectors.toMap(af -> new TablesKey(af.getAfi(), af.getSafi()), BgpAddPathTableType::getSendReceive))); } + + @Override + public BGPErrorHandlingState getBGPErrorHandlingState() { + return this; + } + + @Override + public BGPAfiSafiState getBGPAfiSafiState() { + return this; + } + + @Override + public BGPSessionState getBGPSessionState() { + if (this.session instanceof BGPSessionStateProvider) { + return ((BGPSessionStateProvider) this.session).getBGPSessionState(); + } + return null; + } + + @Override + public BGPTimersState getBGPTimersState() { + if (this.session instanceof BGPSessionStateProvider) { + return ((BGPSessionStateProvider) this.session).getBGPTimersState(); + } + return null; + } + + @Override + public BGPTransportState getBGPTransportState() { + if (this.session instanceof BGPSessionStateProvider) { + return ((BGPSessionStateProvider) this.session).getBGPTransportState(); + } + return null; + } } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPSessionImpl.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPSessionImpl.java index 32f1eee570..6d81483576 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPSessionImpl.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/BGPSessionImpl.java @@ -37,14 +37,20 @@ import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil; import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl; import org.opendaylight.protocol.bgp.parser.spi.MultiPathSupport; import org.opendaylight.protocol.bgp.parser.spi.pojo.MultiPathSupportImpl; +import org.opendaylight.protocol.bgp.rib.impl.spi.BGPMessagesListener; import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry; import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences; +import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl; +import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateProvider; import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPSessionStats; import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPSessionStatsImpl; import org.opendaylight.protocol.bgp.rib.spi.BGPSession; import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener; import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason; import org.opendaylight.protocol.bgp.rib.spi.State; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Keepalive; @@ -68,7 +74,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @VisibleForTesting -public class BGPSessionImpl extends SimpleChannelInboundHandler implements BGPSession, BGPSessionStats, AutoCloseable { +public class BGPSessionImpl extends SimpleChannelInboundHandler implements BGPSession, BGPSessionStats, + BGPSessionStateProvider, AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class); @@ -110,17 +117,19 @@ public class BGPSessionImpl extends SimpleChannelInboundHandler im private final Ipv4Address bgpId; private final BGPPeerRegistry peerRegistry; private final ChannelOutputLimiter limiter; + private final BGPSessionStateImpl sessionState; private BGPSessionStatsImpl sessionStats; - public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final BGPSessionPreferences localPreferences, - final BGPPeerRegistry peerRegistry) { + public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, + final BGPSessionPreferences localPreferences, final BGPPeerRegistry peerRegistry) { this(listener, channel, remoteOpen, localPreferences.getHoldTime(), peerRegistry); - this.sessionStats = new BGPSessionStatsImpl(this, remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.of(localPreferences), this.tableTypes, this.addPathTypes); + this.sessionStats = new BGPSessionStatsImpl(this, remoteOpen, this.holdTimerValue, this.keepAlive, channel, + Optional.of(localPreferences), this.tableTypes, this.addPathTypes); } - public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, final int localHoldTimer, - final BGPPeerRegistry peerRegistry) { + public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen, + final int localHoldTimer, final BGPPeerRegistry peerRegistry) { this.listener = Preconditions.checkNotNull(listener); this.channel = Preconditions.checkNotNull(channel); this.limiter = new ChannelOutputLimiter(this); @@ -130,6 +139,7 @@ public class BGPSessionImpl extends SimpleChannelInboundHandler im this.keepAlive = this.holdTimerValue / KA_TO_DEADTIMER_RATIO; this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen); this.peerRegistry = peerRegistry; + this.sessionState = new BGPSessionStateImpl(); final Set tts = Sets.newHashSet(); final Set tats = Sets.newHashSet(); @@ -184,6 +194,9 @@ public class BGPSessionImpl extends SimpleChannelInboundHandler im this.bgpId = remoteOpen.getBgpIdentifier(); this.sessionStats = new BGPSessionStatsImpl(this, remoteOpen, this.holdTimerValue, this.keepAlive, channel, Optional.absent(), this.tableTypes, this.addPathTypes); + + this.sessionState.advertizeCapabilities(this.holdTimerValue, channel.remoteAddress(), channel.localAddress(), + this.tableTypes, remoteOpen.getBgpParameters()); } /** @@ -253,7 +266,7 @@ public class BGPSessionImpl extends SimpleChannelInboundHandler im } this.sessionStats.updateReceivedMsg(msg); - + this.sessionState.messageReceived(msg); } catch (final BGPDocumentedException e) { this.terminate(e); } @@ -281,6 +294,7 @@ public class BGPSessionImpl extends SimpleChannelInboundHandler im }); this.lastMessageSentAt = System.nanoTime(); this.sessionStats.updateSentMsg(msg); + this.sessionState.messageSent(msg); return future; } @@ -316,6 +330,7 @@ public class BGPSessionImpl extends SimpleChannelInboundHandler im }); this.state = State.IDLE; removePeerSession(); + this.sessionState.setSessionState(this.state); } /** @@ -425,6 +440,7 @@ public class BGPSessionImpl extends SimpleChannelInboundHandler im protected synchronized void sessionUp() { this.sessionStats.startSessionStopwatch(); this.state = State.UP; + this.sessionState.setSessionState(this.state); this.listener.onSessionUp(this); } @@ -492,4 +508,24 @@ public class BGPSessionImpl extends SimpleChannelInboundHandler im this.close(); } } + + @Override + public BGPSessionState getBGPSessionState() { + return this.sessionState; + } + + @Override + public BGPTimersState getBGPTimersState() { + return this.sessionState; + } + + @Override + public BGPTransportState getBGPTransportState() { + return this.sessionState; + } + + @Override + public void registerMessagesCounter(final BGPMessagesListener bgpMessagesListener) { + this.sessionState.registerMessagesCounter(bgpMessagesListener); + } } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/EffectiveRibInWriter.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/EffectiveRibInWriter.java index bb3dad7e50..148fc74479 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/EffectiveRibInWriter.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/EffectiveRibInWriter.java @@ -10,7 +10,10 @@ package org.opendaylight.protocol.bgp.rib.impl; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Verify; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import java.util.Collection; +import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -28,6 +31,8 @@ import org.opendaylight.protocol.bgp.rib.impl.spi.AbstractImportPolicy; import org.opendaylight.protocol.bgp.rib.impl.spi.ImportPolicyPeerTracker; import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext; import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry; +import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesInstalledCounters; +import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesReceivedCounters; import org.opendaylight.protocol.bgp.rib.impl.stats.peer.route.PerTableTypeRouteCounter; import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils; import org.opendaylight.protocol.bgp.rib.spi.RIBSupport; @@ -64,52 +69,52 @@ import org.slf4j.LoggerFactory; * */ @NotThreadSafe -final class EffectiveRibInWriter implements AutoCloseable { +final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesInstalledCounters, AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(EffectiveRibInWriter.class); - protected static final NodeIdentifier TABLE_ROUTES = new NodeIdentifier(Routes.QNAME); - private final class AdjInTracker implements AutoCloseable, ClusteredDOMDataTreeChangeListener { + private static final Set EMPTY_SET = Collections.emptySet(); + static final NodeIdentifier TABLE_ROUTES = new NodeIdentifier(Routes.QNAME); + + private final class AdjInTracker implements PrefixesReceivedCounters, PrefixesInstalledCounters, AutoCloseable, + ClusteredDOMDataTreeChangeListener { private final RIBSupportContextRegistry registry; private final YangInstanceIdentifier peerIId; private final YangInstanceIdentifier effRibTables; private final ListenerRegistration reg; private final DOMTransactionChain chain; - private final PerTableTypeRouteCounter effectiveRibInRouteCounters; private final PerTableTypeRouteCounter adjRibInRouteCounters; - private final Map> effectiveRibInRouteMap = new ConcurrentHashMap<>(); private final Map> adjRibInRouteMap = new ConcurrentHashMap<>(); + private final Map prefixesReceived; + private final Map prefixesInstalled; - AdjInTracker(final DOMDataTreeChangeService service, final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier peerIId, - @Nonnull final PerTableTypeRouteCounter effectiveRibInRouteCounters, @Nonnull final PerTableTypeRouteCounter adjRibInRouteCounters) { + AdjInTracker(final DOMDataTreeChangeService service, final RIBSupportContextRegistry registry, + final DOMTransactionChain chain, final YangInstanceIdentifier peerIId, + @Nonnull final PerTableTypeRouteCounter adjRibInRouteCounters, @Nonnull Set tables) { this.registry = Preconditions.checkNotNull(registry); this.chain = Preconditions.checkNotNull(chain); this.peerIId = Preconditions.checkNotNull(peerIId); this.effRibTables = this.peerIId.node(EffectiveRibIn.QNAME).node(Tables.QNAME); - this.effectiveRibInRouteCounters = Preconditions.checkNotNull(effectiveRibInRouteCounters); this.adjRibInRouteCounters = Preconditions.checkNotNull(adjRibInRouteCounters); + this.prefixesInstalled = buildPrefixesTables(tables); + this.prefixesReceived = buildPrefixesTables(tables); - final DOMDataTreeIdentifier treeId = new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, this.peerIId.node(AdjRibIn.QNAME).node(Tables.QNAME)); + final DOMDataTreeIdentifier treeId = new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, + this.peerIId.node(AdjRibIn.QNAME).node(Tables.QNAME)); LOG.debug("Registered Effective RIB on {}", this.peerIId); this.reg = service.registerDataTreeChangeListener(treeId, this); } - /** - * @deprecated Should always pass in route counter - * @param service - * @param registry - * @param chain - * @param peerIId - */ - @Deprecated - AdjInTracker(final DOMDataTreeChangeService service, final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier peerIId) { - this(service, registry, chain, peerIId, new PerTableTypeRouteCounter(), new PerTableTypeRouteCounter()); + private Map buildPrefixesTables(final Set tables) { + final ImmutableMap.Builder b = ImmutableMap.builder(); + tables.forEach(table -> b.put(table, new LongAdder())); + return b.build(); } + private void updateRoute(@Nonnull final PerTableTypeRouteCounter counter, @Nonnull final Map> routeMap, @Nonnull final TablesKey tablesKey, @Nonnull final YangInstanceIdentifier routeId) { routeMap.putIfAbsent(tablesKey, new HashSet<>()); routeMap.get(tablesKey).add(routeId); - updateRouteCounter(counter, routeMap,tablesKey); } @@ -129,14 +134,14 @@ final class EffectiveRibInWriter implements AutoCloseable { updateRouteCounter(counter, routeMap,tablesKey); } - private void updateRouteCounter(@Nonnull final PerTableTypeRouteCounter counter, @Nonnull final Map> routeMap, - @Nonnull final TablesKey tablesKey) { - final LongAdder tableCounter = counter.getCounterOrSetDefault(tablesKey); - tableCounter.reset(); - tableCounter.add(routeMap.getOrDefault(tablesKey, new HashSet<>()).size()); + private void updateRouteCounter(@Nonnull final PerTableTypeRouteCounter counter, @Nonnull final Map> routeMap, @Nonnull final TablesKey tablesKey) { + final int size = routeMap.getOrDefault(tablesKey, EMPTY_SET).size(); + counter.setValueToCounterOrSetDefault(tablesKey, size); } - private void processRoute(final DOMDataWriteTransaction tx, final RIBSupport ribSupport, final AbstractImportPolicy policy, final YangInstanceIdentifier routesPath, final DataTreeCandidateNode route) { + private void processRoute(final DOMDataWriteTransaction tx, final RIBSupport ribSupport, final AbstractImportPolicy policy, + final YangInstanceIdentifier routesPath, final DataTreeCandidateNode route) { LOG.debug("Process route {}", route.getIdentifier()); final YangInstanceIdentifier routeId = ribSupport.routePath(routesPath, route.getIdentifier()); final TablesKey tablesKey = new TablesKey(ribSupport.getAfi(), ribSupport.getSafi()); @@ -147,7 +152,7 @@ final class EffectiveRibInWriter implements AutoCloseable { LOG.debug("Route deleted. routeId={}", routeId); deleteRoute(this.adjRibInRouteCounters, this.adjRibInRouteMap, tablesKey, routeId); - deleteRoute(this.effectiveRibInRouteCounters, this.effectiveRibInRouteMap, tablesKey, routeId); + CountersUtil.decrement(this.prefixesInstalled.get(tablesKey), tablesKey); break; case UNMODIFIED: // No-op @@ -156,9 +161,9 @@ final class EffectiveRibInWriter implements AutoCloseable { case SUBTREE_MODIFIED: case WRITE: tx.put(LogicalDatastoreType.OPERATIONAL, routeId, route.getDataAfter().get()); + CountersUtil.increment(this.prefixesReceived.get(tablesKey), tablesKey); // count adj-rib-in route first updateRoute(this.adjRibInRouteCounters, this.adjRibInRouteMap, tablesKey, routeId); - updateRoute(this.effectiveRibInRouteCounters, this.effectiveRibInRouteMap, tablesKey, routeId); // Lookup per-table attributes from RIBSupport final ContainerNode advertisedAttrs = (ContainerNode) NormalizedNodes.findNode(route.getDataAfter(), ribSupport.routeAttributesIdentifier()).orNull(); final ContainerNode effectiveAttrs; @@ -173,13 +178,12 @@ final class EffectiveRibInWriter implements AutoCloseable { if (effectiveAttrs != null) { tx.put(LogicalDatastoreType.OPERATIONAL, routeId.node(ribSupport.routeAttributesIdentifier()), effectiveAttrs); - - updateRoute(this.effectiveRibInRouteCounters, this.effectiveRibInRouteMap, tablesKey, routeId); + if(route.getModificationType() == ModificationType.WRITE) { + CountersUtil.increment(this.prefixesInstalled.get(tablesKey), tablesKey); + } } else { LOG.warn("Route {} advertised empty attributes", routeId); tx.delete(LogicalDatastoreType.OPERATIONAL, routeId); - - deleteRoute(this.effectiveRibInRouteCounters, this.effectiveRibInRouteMap, tablesKey, routeId); } break; default: @@ -203,7 +207,7 @@ final class EffectiveRibInWriter implements AutoCloseable { LOG.debug("Route deleted. routeId={}", childPath); deleteRoute(this.adjRibInRouteCounters, this.adjRibInRouteMap, tablesKey, childPath); - deleteRoute(this.effectiveRibInRouteCounters, this.effectiveRibInRouteMap, tablesKey, childPath); + CountersUtil.decrement(this.prefixesInstalled.get(tablesKey), tablesKey); break; case UNMODIFIED: // No-op @@ -312,9 +316,9 @@ final class EffectiveRibInWriter implements AutoCloseable { // delete the corresponding effective table tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath); - - deleteRoute(this.adjRibInRouteCounters, this.adjRibInRouteMap, new TablesKey(ribSupport.getAfi(), ribSupport.getSafi())); - deleteRoute(this.effectiveRibInRouteCounters, this.effectiveRibInRouteMap, new TablesKey(ribSupport.getAfi(), ribSupport.getSafi())); + final TablesKey tk = new TablesKey(ribSupport.getAfi(), ribSupport.getSafi()); + deleteRoute(this.adjRibInRouteCounters, this.adjRibInRouteMap, tk); + CountersUtil.decrement(this.prefixesInstalled.get(tk), tk); break; case SUBTREE_MODIFIED: modifyTable(tx, tableKey, table); @@ -335,42 +339,90 @@ final class EffectiveRibInWriter implements AutoCloseable { @Override public void close() { this.reg.close(); + this.prefixesReceived.values().forEach(LongAdder::reset); + this.prefixesInstalled.values().forEach(LongAdder::reset); + } + + @Override + public long getPrefixedReceivedCount(final TablesKey tablesKey) { + final LongAdder counter = this.prefixesReceived.get(tablesKey); + if (counter == null) { + return 0; + } + return counter.longValue(); + } + + @Override + public Set getTableKeys() { + return ImmutableSet.copyOf(this.prefixesReceived.keySet()); + } + + @Override + public boolean isSupported(final TablesKey tablesKey) { + return this.prefixesReceived.containsKey(tablesKey); + } + + @Override + public long getPrefixedInstalledCount(final TablesKey tablesKey) { + final LongAdder counter = this.prefixesInstalled.get(tablesKey); + if (counter == null) { + return 0; + } + return counter.longValue(); + } + + @Override + public long getTotalPrefixesInstalled() { + return this.prefixesInstalled.values().stream().mapToLong(LongAdder::longValue).sum(); } } private final AdjInTracker adjInTracker; private final AbstractImportPolicy importPolicy; - @Deprecated - static EffectiveRibInWriter create(@Nonnull final DOMDataTreeChangeService service, @Nonnull final DOMTransactionChain chain, - @Nonnull final YangInstanceIdentifier peerIId, @Nonnull final ImportPolicyPeerTracker importPolicyPeerTracker, @Nonnull final RIBSupportContextRegistry registry, final PeerRole peerRole) { - return new EffectiveRibInWriter(service, chain, peerIId, importPolicyPeerTracker, registry, peerRole); - } - static EffectiveRibInWriter create(@Nonnull final DOMDataTreeChangeService service, @Nonnull final DOMTransactionChain chain, - @Nonnull final YangInstanceIdentifier peerIId, @Nonnull final ImportPolicyPeerTracker importPolicyPeerTracker, @Nonnull final RIBSupportContextRegistry registry, final PeerRole peerRole, - @Nonnull final PerTableTypeRouteCounter effectiveRouteCounters, @Nonnull final PerTableTypeRouteCounter adjRibInRouteCounters) { - return new EffectiveRibInWriter(service, chain, peerIId, importPolicyPeerTracker, registry, peerRole, effectiveRouteCounters, adjRibInRouteCounters); - } - - @Deprecated - private EffectiveRibInWriter(final DOMDataTreeChangeService service, final DOMTransactionChain chain, final YangInstanceIdentifier peerIId, - final ImportPolicyPeerTracker importPolicyPeerTracker, final RIBSupportContextRegistry registry, final PeerRole peerRole) { - importPolicyPeerTracker.peerRoleChanged(peerIId, peerRole); - this.importPolicy = importPolicyPeerTracker.policyFor(IdentifierUtils.peerId((NodeIdentifierWithPredicates) peerIId.getLastPathArgument())); - this.adjInTracker = new AdjInTracker(service, registry, chain, peerIId); + @Nonnull final YangInstanceIdentifier peerIId, @Nonnull final ImportPolicyPeerTracker importPolicyPeerTracker, + @Nonnull final RIBSupportContextRegistry registry, final PeerRole peerRole, + @Nonnull final PerTableTypeRouteCounter adjRibInRouteCounters, @Nonnull Set tables) { + return new EffectiveRibInWriter(service, chain, peerIId, importPolicyPeerTracker, registry, peerRole, + adjRibInRouteCounters, tables); } private EffectiveRibInWriter(final DOMDataTreeChangeService service, final DOMTransactionChain chain, final YangInstanceIdentifier peerIId, - final ImportPolicyPeerTracker importPolicyPeerTracker, final RIBSupportContextRegistry registry, final PeerRole peerRole, - @Nonnull final PerTableTypeRouteCounter effectiveRouteCounters, @Nonnull final PerTableTypeRouteCounter adjRibInRouteCounters) { + final ImportPolicyPeerTracker importPolicyPeerTracker, final RIBSupportContextRegistry registry, final PeerRole peerRole, + @Nonnull final PerTableTypeRouteCounter adjRibInRouteCounters, @Nonnull Set tables) { importPolicyPeerTracker.peerRoleChanged(peerIId, peerRole); this.importPolicy = importPolicyPeerTracker.policyFor(IdentifierUtils.peerId((NodeIdentifierWithPredicates) peerIId.getLastPathArgument())); - this.adjInTracker = new AdjInTracker(service, registry, chain, peerIId, effectiveRouteCounters, adjRibInRouteCounters); + this.adjInTracker = new AdjInTracker(service, registry, chain, peerIId, adjRibInRouteCounters, tables); } @Override public void close() { this.adjInTracker.close(); } + + @Override + public long getPrefixedReceivedCount(final TablesKey tablesKey) { + return this.adjInTracker.getPrefixedReceivedCount(tablesKey); + } + + @Override + public Set getTableKeys() { + return this.adjInTracker.getTableKeys(); + } + + @Override + public boolean isSupported(final TablesKey tablesKey) { + return this.adjInTracker.isSupported(tablesKey); + } + + @Override + public long getPrefixedInstalledCount(@Nonnull final TablesKey tablesKey) { + return this.adjInTracker.getPrefixedInstalledCount(tablesKey); + } + + @Override + public long getTotalPrefixesInstalled() { + return this.adjInTracker.getTotalPrefixesInstalled(); + } } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/LocRibWriter.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/LocRibWriter.java index d6ad73ec11..90d8e7551d 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/LocRibWriter.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/LocRibWriter.java @@ -26,6 +26,8 @@ import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain; import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode; import org.opendaylight.protocol.bgp.mode.api.RouteEntry; import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry; +import org.opendaylight.protocol.bgp.rib.impl.state.rib.TotalPathsCounter; +import org.opendaylight.protocol.bgp.rib.impl.state.rib.TotalPrefixesCounter; import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker; import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils; import org.opendaylight.protocol.bgp.rib.spi.PeerExportGroup; @@ -57,7 +59,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @NotThreadSafe -final class LocRibWriter implements AutoCloseable, ClusteredDOMDataTreeChangeListener { +final class LocRibWriter implements AutoCloseable, TotalPrefixesCounter, TotalPathsCounter, + ClusteredDOMDataTreeChangeListener { private static final Logger LOG = LoggerFactory.getLogger(LocRibWriter.class); @@ -73,11 +76,13 @@ final class LocRibWriter implements AutoCloseable, ClusteredDOMDataTreeChangeLis private final TablesKey localTablesKey; private final ListenerRegistration reg; private final PathSelectionMode pathSelectionMode; - private final LongAdder routeCounter; + private final LongAdder totalPathsCounter = new LongAdder(); + private final LongAdder totalPrefixesCounter = new LongAdder(); - private LocRibWriter(final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier target, - final Long ourAs, final DOMDataTreeChangeService service, final ExportPolicyPeerTracker exportPolicyPeerTracker, final TablesKey tablesKey, - @Nonnull final PathSelectionMode pathSelectionMode, final LongAdder routeCounter) { + private LocRibWriter(final RIBSupportContextRegistry registry, final DOMTransactionChain chain, + final YangInstanceIdentifier target, final Long ourAs, final DOMDataTreeChangeService service, + final ExportPolicyPeerTracker exportPolicyPeerTracker, final TablesKey tablesKey, + final PathSelectionMode pathSelectionMode) { this.chain = Preconditions.checkNotNull(chain); final NodeIdentifierWithPredicates tableKey = RibSupportUtils.toYangTablesKey(tablesKey); this.localTablesKey = tablesKey; @@ -87,7 +92,6 @@ final class LocRibWriter implements AutoCloseable, ClusteredDOMDataTreeChangeLis this.attributesIdentifier = this.ribSupport.routeAttributesIdentifier(); this.exportPolicyPeerTracker = exportPolicyPeerTracker; this.pathSelectionMode = pathSelectionMode; - this.routeCounter = routeCounter; final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction(); tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Routes.QNAME), this.ribSupport.emptyRoutes()); @@ -99,10 +103,12 @@ final class LocRibWriter implements AutoCloseable, ClusteredDOMDataTreeChangeLis this.reg = service.registerDataTreeChangeListener(wildcard, this); } - public static LocRibWriter create(@Nonnull final RIBSupportContextRegistry registry, @Nonnull final TablesKey tablesKey, @Nonnull final DOMTransactionChain chain, - @Nonnull final YangInstanceIdentifier target, @Nonnull final AsNumber ourAs, @Nonnull final DOMDataTreeChangeService service, @Nonnull final ExportPolicyPeerTracker ep, - @Nonnull final PathSelectionMode pathSelectionStrategy, @Nonnull final LongAdder routeCounter) { - return new LocRibWriter(registry, chain, target, ourAs.getValue(), service, ep, tablesKey, pathSelectionStrategy, routeCounter); + public static LocRibWriter create(@Nonnull final RIBSupportContextRegistry registry, @Nonnull final TablesKey tablesKey, + @Nonnull final DOMTransactionChain chain, + @Nonnull final YangInstanceIdentifier target, @Nonnull final AsNumber ourAs, @Nonnull final DOMDataTreeChangeService service, + @Nonnull final ExportPolicyPeerTracker ep, @Nonnull final PathSelectionMode pathSelectionStrategy) { + return new LocRibWriter(registry, chain, target, ourAs.getValue(), service, ep, tablesKey, + pathSelectionStrategy); } @Override @@ -114,8 +120,9 @@ final class LocRibWriter implements AutoCloseable, ClusteredDOMDataTreeChangeLis @Nonnull private RouteEntry createEntry(final PathArgument routeId) { - final RouteEntry ret = this.pathSelectionMode.createRouteEntry(ribSupport.isComplexRoute()); + final RouteEntry ret = this.pathSelectionMode.createRouteEntry(this.ribSupport.isComplexRoute()); this.routeEntries.put(routeId, ret); + this.totalPrefixesCounter.increment(); LOG.trace("Created new entry for {}", routeId); return ret; } @@ -196,23 +203,19 @@ final class LocRibWriter implements AutoCloseable, ClusteredDOMDataTreeChangeLis entry = createEntry(routeId); } entry.addRoute(routerId, this.ribSupport.extractPathId(maybeData.get()), this.attributesIdentifier, maybeData.get()); - } else if (entry != null && entry.removeRoute(routerId, this.ribSupport.extractPathId(maybeDataBefore.get()))) { - this.routeEntries.remove(routeId); - LOG.trace("Removed route from {}", routerId); + this.totalPathsCounter.increment(); + } else if (entry != null) { + this.totalPathsCounter.decrement(); + if(entry.removeRoute(routerId, this.ribSupport.extractPathId(maybeDataBefore.get()))) { + this.routeEntries.remove(routeId); + this.totalPrefixesCounter.decrement(); + LOG.trace("Removed route from {}", routerId); + } } final RouteUpdateKey routeUpdateKey = new RouteUpdateKey(peerId, routeId); LOG.debug("Updated route {} entry {}", routeId, entry); routes.put(routeUpdateKey, entry); } - updateRouteCounter(); - } - - /** - * Update the statistic of loc-rib route - */ - private void updateRouteCounter() { - this.routeCounter.reset(); - this.routeCounter.add(this.routeEntries.size()); } private void walkThrough(final DOMDataWriteTransaction tx, final Set> toUpdate) { @@ -227,4 +230,14 @@ final class LocRibWriter implements AutoCloseable, ClusteredDOMDataTreeChangeLis entry.updateRoute(this.localTablesKey, this.exportPolicyPeerTracker, this.locRibTarget, this.ribSupport, tx, e.getKey().getRouteId()); } } + + @Override + public long getPrefixesCount() { + return this.totalPrefixesCounter.longValue(); + } + + @Override + public long getPathsCount() { + return this.totalPathsCounter.longValue(); + } } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/RIBImpl.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/RIBImpl.java index c1fb15967e..3551c95ffc 100755 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/RIBImpl.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/RIBImpl.java @@ -39,13 +39,13 @@ import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegist import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier; import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode; import org.opendaylight.protocol.bgp.mode.impl.base.BasePathSelectionModeFactory; -import org.opendaylight.protocol.bgp.rib.DefaultRibReference; import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher; import org.opendaylight.protocol.bgp.rib.impl.spi.BgpDeployer; import org.opendaylight.protocol.bgp.rib.impl.spi.CodecsRegistry; import org.opendaylight.protocol.bgp.rib.impl.spi.ImportPolicyPeerTracker; import org.opendaylight.protocol.bgp.rib.impl.spi.RIB; import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry; +import org.opendaylight.protocol.bgp.rib.impl.state.BGPRIBStateImpl; import org.opendaylight.protocol.bgp.rib.impl.stats.rib.impl.BGPRenderStats; import org.opendaylight.protocol.bgp.rib.impl.stats.rib.impl.RIBImplRuntimeMXBeanImpl; import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker; @@ -83,7 +83,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ThreadSafe -public final class RIBImpl extends DefaultRibReference implements ClusterSingletonService, AutoCloseable, RIB, TransactionChainListener, SchemaContextListener { +public final class RIBImpl extends BGPRIBStateImpl implements ClusterSingletonService, RIB, TransactionChainListener, + SchemaContextListener, AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(RIBImpl.class); private static final QName RIB_ID_QNAME = QName.create(Rib.QNAME, "id").intern(); private static final ContainerNode EMPTY_TABLE_ATTRIBUTES = ImmutableNodes.containerNode(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Attributes.QNAME); @@ -119,8 +120,8 @@ public final class RIBImpl extends DefaultRibReference implements ClusterSinglet final BindingCodecTreeFactory codecFactory, final DOMDataBroker domDataBroker, final List localTables, @Nonnull final Map bestPathSelectionStrategies, final GeneratedClassLoadingStrategy classStrategy, final BgpDeployer.WriteConfiguration configurationWriter) { - - super(InstanceIdentifier.create(BgpRib.class).child(Rib.class, new RibKey(Preconditions.checkNotNull(ribId)))); + super(InstanceIdentifier.create(BgpRib.class).child(Rib.class, new RibKey(Preconditions.checkNotNull(ribId))), + localBgpId, localAs); this.localAs = Preconditions.checkNotNull(localAs); this.bgpIdentifier = Preconditions.checkNotNull(localBgpId); this.dispatcher = Preconditions.checkNotNull(dispatcher); @@ -135,7 +136,6 @@ public final class RIBImpl extends DefaultRibReference implements ClusterSinglet this.yangRibId = yangRibIdBuilder.nodeWithKey(Rib.QNAME, RIB_ID_QNAME, ribId.getValue()).build(); this.bestPathSelectionStrategies = Preconditions.checkNotNull(bestPathSelectionStrategies); final ClusterIdentifier cId = (clusterId == null) ? new ClusterIdentifier(localBgpId) : clusterId; - this.renderStats = new RIBImplRuntimeMXBeanImpl(localBgpId, ribId, localAs, cId); this.ribId = ribId; final PolicyDatabase policyDatabase = new PolicyDatabase(this.localAs.getValue(), localBgpId, cId); this.importPolicyPeerTracker = new ImportPolicyPeerTrackerImpl(policyDatabase); @@ -152,6 +152,7 @@ public final class RIBImpl extends DefaultRibReference implements ClusterSinglet } this.exportPolicyPeerTrackerMap = exportPolicies.build(); + this.renderStats = new RIBImplRuntimeMXBeanImpl(localBgpId, ribId, localAs, cId, this, this.localTablesKeys); LOG.info("RIB Singleton Service {} registered", getIdentifier()); //this need to be always the last step this.registration = registerClusterSingletonService(this); @@ -188,8 +189,11 @@ public final class RIBImpl extends DefaultRibReference implements ClusterSinglet pathSelectionStrategy = BasePathSelectionModeFactory.createBestPathSelectionStrategy(); } - this.locRibs.add(LocRibWriter.create(this.ribContextRegistry, key, createPeerChain(this), getYangRibId(), this.localAs, getService(), - this.exportPolicyPeerTrackerMap.get(key), pathSelectionStrategy, this.renderStats.getLocRibRouteCounter().init(key))); + final LocRibWriter locRibWriter = LocRibWriter.create(this.ribContextRegistry, key, createPeerChain(this), + getYangRibId(), this.localAs, getService(), this.exportPolicyPeerTrackerMap.get(key), pathSelectionStrategy); + registerTotalPathCounter(key, locRibWriter); + registerTotalPrefixesCounter(key, locRibWriter); + this.locRibs.add(locRibWriter); } @Override @@ -339,15 +343,11 @@ public final class RIBImpl extends DefaultRibReference implements ClusterSinglet this.locRibs.forEach(LocRibWriter::close); this.locRibs.clear(); - this.renderStats.getLocRibRouteCounter().resetAll(); - - final DOMDataWriteTransaction t = this.domChain.newWriteOnlyTransaction(); t.delete(LogicalDatastoreType.OPERATIONAL, getYangRibId()); final CheckedFuture cleanFuture = t.submit(); this.domChain.close(); - return cleanFuture; } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/AppPeer.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/AppPeer.java index 584882037f..2a8ac86a86 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/AppPeer.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/AppPeer.java @@ -23,6 +23,8 @@ import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer import org.opendaylight.protocol.bgp.rib.impl.ApplicationPeer; import org.opendaylight.protocol.bgp.rib.impl.spi.BgpDeployer.WriteConfiguration; import org.opendaylight.protocol.bgp.rib.impl.spi.RIB; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerStateConsumer; import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.Config; import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.Neighbor; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address; @@ -31,14 +33,16 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib. import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; +import org.osgi.framework.ServiceRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public final class AppPeer implements PeerBean { +public final class AppPeer implements PeerBean, BGPPeerStateConsumer { private static final Logger LOG = LoggerFactory.getLogger(AppPeer.class); private static final QName APP_ID_QNAME = QName.create(ApplicationRib.QNAME, "id").intern(); private Neighbor currentConfiguration; private BgpAppPeerSingletonService bgpAppPeerSingletonService; + private ServiceRegistration serviceRegistration; @Override public void start(final RIB rib, final Neighbor neighbor, final BGPTableTypeRegistryConsumer tableTypeRegistry, @@ -63,6 +67,10 @@ public final class AppPeer implements PeerBean { } catch (final Exception e) { LOG.warn("Failed to close application peer instance", e); } + if (this.serviceRegistration != null) { + this.serviceRegistration.unregister(); + this.serviceRegistration = null; + } } @Override @@ -79,7 +87,17 @@ public final class AppPeer implements PeerBean { return new ApplicationRibId(neighbor.getNeighborAddress().getIpv4Address().getValue()); } - private final class BgpAppPeerSingletonService implements ClusterSingletonService, AutoCloseable { + @Override + public BGPPeerState getPeerState() { + return this.bgpAppPeerSingletonService.getPeerState(); + } + + void setServiceRegistration(final ServiceRegistration serviceRegistration) { + this.serviceRegistration = serviceRegistration; + } + + private final class BgpAppPeerSingletonService implements ClusterSingletonService, BGPPeerStateConsumer, + AutoCloseable { private final ApplicationPeer applicationPeer; private final DOMDataTreeChangeService dataTreeChangeService; private final ApplicationRibId appRibId; @@ -130,5 +148,10 @@ public final class AppPeer implements PeerBean { public ServiceGroupIdentifier getIdentifier() { return this.serviceGroupIdentifier; } + + @Override + public BGPPeerState getPeerState() { + return this.applicationPeer.getPeerState(); + } } } \ No newline at end of file diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpDeployerImpl.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpDeployerImpl.java index 5f68f316c0..fc7e6a400d 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpDeployerImpl.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpDeployerImpl.java @@ -289,6 +289,14 @@ public final class BgpDeployerImpl implements BgpDeployer, ClusteredDataTreeChan bgpPeer.setServiceRegistration(serviceRegistration); } + private void registerAppPeerInstance(final AppPeer appPeer, final String peerInstanceName) { + final Dictionary properties = new Hashtable<>(); + properties.put(InstanceType.PEER.getBeanName(), peerInstanceName); + final ServiceRegistration serviceRegistration = this.bundleContext + .registerService(InstanceType.APP_PEER.getServices(), appPeer, properties); + appPeer.setServiceRegistration(serviceRegistration); + } + private void initiatePeerInstance(final InstanceIdentifier rootIdentifier, final InstanceIdentifier neighborIdentifier, final Neighbor neighbor, final PeerBean bgpPeer, final WriteConfiguration configurationWriter) { final String peerInstanceName = getNeighborInstanceName(neighborIdentifier); @@ -297,6 +305,8 @@ public final class BgpDeployerImpl implements BgpDeployer, ClusteredDataTreeChan bgpPeer.start(rib, neighbor, this.tableTypeRegistry, configurationWriter); if (bgpPeer instanceof BgpPeer) { registerPeerInstance((BgpPeer) bgpPeer, peerInstanceName); + } else if(bgpPeer instanceof AppPeer) { + registerAppPeerInstance((AppPeer) bgpPeer, peerInstanceName); } } } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpPeer.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpPeer.java index 93bfd0d022..31b0cd37c9 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpPeer.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpPeer.java @@ -23,6 +23,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.Set; import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeMXBean; import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpPeerState; import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState; @@ -39,6 +40,8 @@ import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry; import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences; import org.opendaylight.protocol.bgp.rib.impl.spi.BgpDeployer.WriteConfiguration; import org.opendaylight.protocol.bgp.rib.impl.spi.RIB; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerStateConsumer; import org.opendaylight.protocol.concepts.KeyMapping; import org.opendaylight.protocol.util.Ipv4Util; import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafi; @@ -57,12 +60,13 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.mult import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.AddPathCapabilityBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.MultiprotocolCapabilityBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.add.path.capability.AddressFamilies; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey; import org.osgi.framework.ServiceRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public final class BgpPeer implements PeerBean, BGPPeerRuntimeMXBean { +public final class BgpPeer implements PeerBean, BGPPeerStateConsumer, BGPPeerRuntimeMXBean { private static final Logger LOG = LoggerFactory.getLogger(BgpPeer.class); @@ -191,11 +195,20 @@ public final class BgpPeer implements PeerBean, BGPPeerRuntimeMXBean { this.bgpPeerSingletonService.getPeer().resetStats(); } + @Override + public BGPPeerState getPeerState() { + if (this.bgpPeerSingletonService == null) { + return null; + } + return this.bgpPeerSingletonService.getPeerState(); + } + void setServiceRegistration(final ServiceRegistration serviceRegistration) { this.serviceRegistration = serviceRegistration; } - private final class BgpPeerSingletonService implements ClusterSingletonService, AutoCloseable { + private final class BgpPeerSingletonService implements BGPPeerStateConsumer, ClusterSingletonService, + AutoCloseable { private final ServiceGroupIdentifier serviceGroupIdentifier; private final boolean activeConnection; private final BGPDispatcher dispatcher; @@ -209,15 +222,19 @@ public final class BgpPeer implements PeerBean, BGPPeerRuntimeMXBean { private final BGPSessionPreferences prefs; private Future connection; - private BgpPeerSingletonService(final RIB rib, final Neighbor neighbor, final BGPTableTypeRegistryConsumer tableTypeRegistry, - final WriteConfiguration configurationWriter) { + private BgpPeerSingletonService(final RIB rib, final Neighbor neighbor, + final BGPTableTypeRegistryConsumer tableTypeRegistry, final WriteConfiguration configurationWriter) { this.neighborAddress = neighbor.getNeighborAddress(); + final AfiSafis afisSAfis = Preconditions.checkNotNull(neighbor.getAfiSafis()); + final Set afiSafisAdvertized = OpenConfigMappingUtil + .toTableKey(afisSAfis.getAfiSafi(), tableTypeRegistry); this.bgpPeer = new BGPPeer(Ipv4Util.toStringIP(this.neighborAddress), rib, - OpenConfigMappingUtil.toPeerRole(neighbor), getSimpleRoutingPolicy(neighbor), BgpPeer.this.rpcRegistry); + OpenConfigMappingUtil.toPeerRole(neighbor), getSimpleRoutingPolicy(neighbor), BgpPeer.this.rpcRegistry, + afiSafisAdvertized, Collections.emptySet()); final List bgpParameters = getBgpParameters(neighbor, rib, tableTypeRegistry); final KeyMapping keyMapping = OpenConfigMappingUtil.getNeighborKey(neighbor); - this.prefs = new BGPSessionPreferences(rib.getLocalAs(), getHoldTimer(neighbor), rib.getBgpIdentifier(), getPeerAs(neighbor, rib), - bgpParameters, getPassword(keyMapping)); + this.prefs = new BGPSessionPreferences(rib.getLocalAs(), getHoldTimer(neighbor), rib.getBgpIdentifier(), + getPeerAs(neighbor, rib), bgpParameters, getPassword(keyMapping)); this.activeConnection = OpenConfigMappingUtil.isActive(neighbor); this.dispatcher = rib.getDispatcher(); this.inetAddress = Ipv4Util.toInetSocketAddress(this.neighborAddress, OpenConfigMappingUtil.getPort(neighbor)); @@ -225,7 +242,7 @@ public final class BgpPeer implements PeerBean, BGPPeerRuntimeMXBean { this.key = Optional.fromNullable(keyMapping); this.configurationWriter = configurationWriter; this.serviceGroupIdentifier = rib.getRibIServiceGroupIdentifier(); - LOG.info("Peer Singleton Service {} registered", this.serviceGroupIdentifier); + LOG.info("Peer Singleton Service {} registered", this.serviceGroupIdentifier.getValue()); //this need to be always the last step this.registration = rib.registerClusterSingletonService(this); } @@ -243,17 +260,18 @@ public final class BgpPeer implements PeerBean, BGPPeerRuntimeMXBean { if(this.configurationWriter != null) { this.configurationWriter.apply(); } - LOG.info("Peer Singleton Service {} instantiated", getIdentifier()); + LOG.info("Peer Singleton Service {} instantiated", getIdentifier().getValue()); this.bgpPeer.instantiateServiceInstance(); BgpPeer.this.peerRegistry.addPeer(this.neighborAddress, this.bgpPeer, this.prefs); if (this.activeConnection) { - this.connection = this.dispatcher.createReconnectingClient(this.inetAddress, BgpPeer.this.peerRegistry, this.retryTimer, this.key); + this.connection = this.dispatcher.createReconnectingClient(this.inetAddress, BgpPeer.this.peerRegistry, + this.retryTimer, this.key); } } @Override public ListenableFuture closeServiceInstance() { - LOG.info("Close Peer Singleton Service {}", getIdentifier()); + LOG.info("Close Peer Singleton Service {}", getIdentifier().getValue()); if (this.connection != null) { this.connection.cancel(true); this.connection = null; @@ -273,5 +291,10 @@ public final class BgpPeer implements PeerBean, BGPPeerRuntimeMXBean { BGPPeerRuntimeMXBean getPeer() { return this.bgpPeer; } + + @Override + public BGPPeerState getPeerState() { + return this.bgpPeer.getPeerState(); + } } } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/OpenConfigMappingUtil.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/OpenConfigMappingUtil.java index 819cc3a5d7..ab8fd299f0 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/OpenConfigMappingUtil.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/OpenConfigMappingUtil.java @@ -19,6 +19,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.function.BiFunction; import java.util.stream.Collectors; import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode; @@ -83,12 +84,12 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; public final class OpenConfigMappingUtil { + static final String APPLICATION_PEER_GROUP_NAME = "application-peers"; private static final AfiSafi IPV4_AFISAFI = new AfiSafiBuilder().setAfiSafiName(IPV4UNICAST.class).build(); private static final List DEFAULT_AFISAFI = ImmutableList.of(IPV4_AFISAFI); private static final int HOLDTIMER = 90; private static final int CONNECT_RETRY = 30; private static final PortNumber PORT = new PortNumber(179); - static final String APPLICATION_PEER_GROUP_NAME = "application-peers"; private static final BigDecimal DEFAULT_KEEP_ALIVE = BigDecimal.valueOf(30); private static final BigDecimal DEFAULT_MINIMUM_ADV_INTERVAL = BigDecimal.valueOf(30); @@ -102,7 +103,7 @@ public final class OpenConfigMappingUtil { public static int getHoldTimer(final Neighbor neighbor) { final org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.timers.Config config = - getTimersConfig(neighbor); + getTimersConfig(neighbor); if (config != null && config.getHoldTime() != null) { return config.getHoldTime().intValue(); } @@ -131,7 +132,7 @@ public final class OpenConfigMappingUtil { public static int getRetryTimer(final Neighbor neighbor) { final org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.timers.Config config = - getTimersConfig(neighbor); + getTimersConfig(neighbor); if (config != null && config.getConnectRetry() != null) { return config.getConnectRetry().intValue(); } @@ -149,7 +150,7 @@ public final class OpenConfigMappingUtil { } public static InstanceIdentifier getNeighborInstanceIdentifier(final InstanceIdentifier rootIdentifier, - final NeighborKey neighborKey) { + final NeighborKey neighborKey) { return rootIdentifier.child(Neighbors.class).child(Neighbor.class, neighborKey); } @@ -266,45 +267,45 @@ public final class OpenConfigMappingUtil { } public static Global fromRib(final BgpId bgpId, final ClusterIdentifier clusterIdentifier, final RibId ribId, - final AsNumber localAs, final List localTables, - final Map pathSelectionStrategies, final BGPTableTypeRegistryConsumer bgpTableTypeRegistryConsumer) { + final AsNumber localAs, final List localTables, + final Map pathSelectionStrategies, final BGPTableTypeRegistryConsumer bgpTableTypeRegistryConsumer) { return toGlobalConfiguration(bgpId, clusterIdentifier, localAs, localTables, pathSelectionStrategies, bgpTableTypeRegistryConsumer); } private static Global toGlobalConfiguration(final BgpId bgpId, final ClusterIdentifier clusterIdentifier, - final AsNumber localAs, final List localTables, - final Map pathSelectionStrategies, final BGPTableTypeRegistryConsumer bgpTableTypeRegistryConsumer) { + final AsNumber localAs, final List localTables, + final Map pathSelectionStrategies, final BGPTableTypeRegistryConsumer bgpTableTypeRegistryConsumer) { final ConfigBuilder configBuilder = new ConfigBuilder(); configBuilder.setAs(localAs); configBuilder.setRouterId(bgpId); if (clusterIdentifier != null) { configBuilder.addAugmentation(GlobalConfigAugmentation.class, - new GlobalConfigAugmentationBuilder().setRouteReflectorClusterId(new RrClusterIdType(clusterIdentifier)).build()); + new GlobalConfigAugmentationBuilder().setRouteReflectorClusterId(new RrClusterIdType(clusterIdentifier)).build()); } return new GlobalBuilder().setAfiSafis(new AfiSafisBuilder().setAfiSafi(toAfiSafis(localTables, - (afiSafi, tableType) -> toGlobalAfiSafiAddPath(afiSafi, tableType, pathSelectionStrategies), bgpTableTypeRegistryConsumer)).build()) - .setConfig(configBuilder.build()).build(); + (afiSafi, tableType) -> toGlobalAfiSafiAddPath(afiSafi, tableType, pathSelectionStrategies), bgpTableTypeRegistryConsumer)).build()) + .setConfig(configBuilder.build()).build(); } public static Neighbor fromBgpPeer(final List addPathCapabilities, - final List advertisedTables, final Integer holdTimer, final IpAddress ipAddress, - final Boolean isActive, final Rfc2385Key password, final PortNumber portNumber, final Integer retryTimer, - final AsNumber remoteAs, final PeerRole peerRole, final SimpleRoutingPolicy simpleRoutingPolicy, final BGPTableTypeRegistryConsumer bgpTableTypeRegistryConsumer) { + final List advertisedTables, final Integer holdTimer, final IpAddress ipAddress, + final Boolean isActive, final Rfc2385Key password, final PortNumber portNumber, final Integer retryTimer, + final AsNumber remoteAs, final PeerRole peerRole, final SimpleRoutingPolicy simpleRoutingPolicy, final BGPTableTypeRegistryConsumer bgpTableTypeRegistryConsumer) { final NeighborBuilder neighborBuilder = new NeighborBuilder(); neighborBuilder.setNeighborAddress(ipAddress); neighborBuilder.setKey(new NeighborKey(ipAddress)); neighborBuilder.setAfiSafis(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.AfiSafisBuilder().setAfiSafi(toAfiSafis(advertisedTables, - (afiSafi, tableType) -> toNeighborAfiSafiAddPath(afiSafi, tableType, addPathCapabilities), bgpTableTypeRegistryConsumer)).build()); + (afiSafi, tableType) -> toNeighborAfiSafiAddPath(afiSafi, tableType, addPathCapabilities), bgpTableTypeRegistryConsumer)).build()); neighborBuilder.setTransport(new TransportBuilder().setConfig( - new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.transport.ConfigBuilder() + new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.transport.ConfigBuilder() .setPassiveMode(!isActive) .setMtuDiscovery(Boolean.FALSE) .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev160614.Config1.class, - new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev160614.Config1Builder() - .setRemotePort(portNumber).build()) + new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev160614.Config1Builder() + .setRemotePort(portNumber).build()) .build()).build()); neighborBuilder.setConfig( - new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.ConfigBuilder() + new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.ConfigBuilder() .setAuthPassword(password != null ? password.getValue() : null) .setPeerAs(remoteAs) .setPeerType(toPeerType(peerRole)) @@ -313,14 +314,14 @@ public final class OpenConfigMappingUtil { .addAugmentation(NeighborConfigAugmentation.class, setNeighborAugmentation(simpleRoutingPolicy)) .build()); neighborBuilder.setTimers(new TimersBuilder().setConfig( - new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.timers.ConfigBuilder() + new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.timers.ConfigBuilder() .setHoldTime(BigDecimal.valueOf(holdTimer)) .setConnectRetry(BigDecimal.valueOf(retryTimer)) .setKeepaliveInterval(DEFAULT_KEEP_ALIVE) .setMinimumAdvertisementInterval(DEFAULT_MINIMUM_ADV_INTERVAL) .build()).build()); neighborBuilder.setRouteReflector(new RouteReflectorBuilder().setConfig( - new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.route.reflector.ConfigBuilder() + new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.route.reflector.ConfigBuilder() .setRouteReflectorClient(peerRole == PeerRole.RrClient).build()).build()); return neighborBuilder.build(); } @@ -331,14 +332,14 @@ public final class OpenConfigMappingUtil { neighborBuilder.setNeighborAddress(new IpAddress(new Ipv4Address(bgpId.getValue()))); neighborBuilder.setKey(new NeighborKey(neighborBuilder.getNeighborAddress())); neighborBuilder.setConfig(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.ConfigBuilder() - .setDescription(applicationRibId.getValue()) - .addAugmentation(Config2.class, new Config2Builder().setPeerGroup(APPLICATION_PEER_GROUP_NAME).build()) - .build()); + .setDescription(applicationRibId.getValue()) + .addAugmentation(Config2.class, new Config2Builder().setPeerGroup(APPLICATION_PEER_GROUP_NAME).build()) + .build()); return neighborBuilder.build(); } - private static final NeighborConfigAugmentation setNeighborAugmentation(final SimpleRoutingPolicy simpleRoutingPolicy) { + private static NeighborConfigAugmentation setNeighborAugmentation(final SimpleRoutingPolicy simpleRoutingPolicy) { if (simpleRoutingPolicy != null) { return new NeighborConfigAugmentationBuilder().setSimpleRoutingPolicy(simpleRoutingPolicy).build(); } @@ -383,7 +384,7 @@ public final class OpenConfigMappingUtil { } static List toAfiSafis(final List advertizedTables, final BiFunction function, - final BGPTableTypeRegistryConsumer bgpTableTypeRegistryConsumer) { + final BGPTableTypeRegistryConsumer bgpTableTypeRegistryConsumer) { final List afiSafis = new ArrayList<>(advertizedTables.size()); for (final BgpTableType tableType : advertizedTables) { final Optional afiSafiMaybe = toAfiSafi(new BgpTableTypeImpl(tableType.getAfi(), tableType.getSafi()), bgpTableTypeRegistryConsumer); @@ -418,8 +419,8 @@ public final class OpenConfigMappingUtil { static AfiSafi toNeighborAfiSafiAddPath(final AfiSafi afiSafi, final BgpTableType tableType, final List capabilities) { final Optional capability = capabilities.stream() - .filter(af -> af.getAfi().equals(tableType.getAfi()) && af.getSafi().equals(tableType.getSafi())) - .findFirst(); + .filter(af -> af.getAfi().equals(tableType.getAfi()) && af.getSafi().equals(tableType.getSafi())) + .findFirst(); if (!capability.isPresent()) { return afiSafi; } @@ -457,10 +458,18 @@ public final class OpenConfigMappingUtil { public static List toTableTypes(final List afiSafis, final BGPTableTypeRegistryConsumer tableTypeRegistry) { return afiSafis.stream() - .map(afiSafi -> tableTypeRegistry.getTableType(afiSafi.getAfiSafiName())) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toList()); + .map(afiSafi -> tableTypeRegistry.getTableType(afiSafi.getAfiSafiName())) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toList()); } + public static Set toTableKey(final List afiSafis, final BGPTableTypeRegistryConsumer + tableTypeRegistry) { + return afiSafis.stream() + .map(afiSafi -> tableTypeRegistry.getTableKey(afiSafi.getAfiSafiName())) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toSet()); + } } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/RibImpl.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/RibImpl.java index 63cb077d20..38cee4c162 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/RibImpl.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/RibImpl.java @@ -9,6 +9,8 @@ package org.opendaylight.protocol.bgp.rib.impl.config; import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getAfiSafiWithDefault; +import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getClusterIdentifier; +import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.toTableTypes; import com.google.common.base.Preconditions; import java.util.List; @@ -37,6 +39,8 @@ import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry; import org.opendaylight.protocol.bgp.rib.impl.stats.rib.impl.BGPRenderStats; import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker; import org.opendaylight.protocol.bgp.rib.spi.RIBExtensionConsumerContext; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPRIBState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPRIBStateConsumer; import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafi; import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.global.base.Config; import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.bgp.Global; @@ -57,7 +61,7 @@ import org.osgi.framework.ServiceRegistration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public final class RibImpl implements RIB, AutoCloseable { +public final class RibImpl implements RIB, BGPRIBStateConsumer, AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(RibImpl.class); @@ -76,8 +80,9 @@ public final class RibImpl implements RIB, AutoCloseable { private ClusterIdentifier clusterId; - public RibImpl(final ClusterSingletonServiceProvider provider, final RIBExtensionConsumerContext contextProvider, final BGPDispatcher dispatcher, - final BindingCodecTreeFactory codecTreeFactory, final DOMDataBroker domBroker, final SchemaService schemaService) { + public RibImpl(final ClusterSingletonServiceProvider provider, final RIBExtensionConsumerContext contextProvider, + final BGPDispatcher dispatcher, final BindingCodecTreeFactory codecTreeFactory, final DOMDataBroker domBroker, + final SchemaService schemaService) { this.provider = Preconditions.checkNotNull(provider); this.extensions = contextProvider; this.dispatcher = dispatcher; @@ -89,7 +94,7 @@ public final class RibImpl implements RIB, AutoCloseable { void start(final Global global, final String instanceName, final BGPTableTypeRegistryConsumer tableTypeRegistry, final BgpDeployer.WriteConfiguration configurationWriter) { Preconditions.checkState(this.ribImpl == null, "Previous instance %s was not closed.", this); - this.ribImpl = createRib(this.provider, global, instanceName, tableTypeRegistry, configurationWriter); + this.ribImpl = createRib(global, instanceName, tableTypeRegistry, configurationWriter); this.schemaContextRegistration = this.schemaService.registerSchemaContextListener(this.ribImpl); } @@ -98,7 +103,7 @@ public final class RibImpl implements RIB, AutoCloseable { final Config globalConfig = global.getConfig(); final AsNumber globalAs = globalConfig.getAs(); final Ipv4Address globalRouterId = global.getConfig().getRouterId(); - final ClusterIdentifier globalClusterId = OpenConfigMappingUtil.getClusterIdentifier(globalConfig); + final ClusterIdentifier globalClusterId = getClusterIdentifier(globalConfig); return this.afiSafi.containsAll(globalAfiSafi) && globalAfiSafi.containsAll(this.afiSafi) && globalAs.equals(this.asNumber) && globalRouterId.getValue().equals(this.routerId.getValue()) @@ -218,17 +223,17 @@ public final class RibImpl implements RIB, AutoCloseable { return this.ribImpl != null ? this.ribImpl.toString() : null; } - private RIBImpl createRib(final ClusterSingletonServiceProvider provider, final Global global, final String bgpInstanceName, + private RIBImpl createRib(final Global global, final String bgpInstanceName, final BGPTableTypeRegistryConsumer tableTypeRegistry, final BgpDeployer.WriteConfiguration configurationWriter) { this.afiSafi = getAfiSafiWithDefault(global.getAfiSafis(), true); final Config globalConfig = global.getConfig(); this.asNumber = globalConfig.getAs(); this.routerId = globalConfig.getRouterId(); - this.clusterId = OpenConfigMappingUtil.getClusterIdentifier(globalConfig); + this.clusterId = getClusterIdentifier(globalConfig); final Map pathSelectionModes = OpenConfigMappingUtil.toPathSelectionMode(this.afiSafi, tableTypeRegistry).entrySet() .stream().collect(Collectors.toMap(entry -> new TablesKey(entry.getKey().getAfi(), entry.getKey().getSafi()), Map.Entry::getValue)); - return new RIBImpl(provider, new RibId(bgpInstanceName), this.asNumber, new BgpId(this.routerId), this.clusterId, - this.extensions, this.dispatcher, this.codecTreeFactory, this.domBroker, OpenConfigMappingUtil.toTableTypes(this.afiSafi, tableTypeRegistry), pathSelectionModes, + return new RIBImpl(this.provider, new RibId(bgpInstanceName), this.asNumber, new BgpId(this.routerId), this.clusterId, + this.extensions, this.dispatcher, this.codecTreeFactory, this.domBroker, toTableTypes(this.afiSafi, tableTypeRegistry), pathSelectionModes, this.extensions.getClassLoadingStrategy(), configurationWriter); } @@ -236,4 +241,9 @@ public final class RibImpl implements RIB, AutoCloseable { public ClusterSingletonServiceRegistration registerClusterSingletonService(final ClusterSingletonService clusterSingletonService) { return this.ribImpl.registerClusterSingletonService(clusterSingletonService); } + + @Override + public BGPRIBState getRIBState() { + return this.ribImpl.getRIBState(); + } } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/BGPMessagesListener.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/BGPMessagesListener.java new file mode 100644 index 0000000000..66e056ead4 --- /dev/null +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/BGPMessagesListener.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.protocol.bgp.rib.impl.spi; + +import javax.annotation.Nonnull; +import org.opendaylight.yangtools.yang.binding.Notification; + +/** + * BGP Operational Messages Listener State + */ +public interface BGPMessagesListener { + /** + * Fired when message is sent. + * + * @param msg message + */ + void messageSent(@Nonnull Notification msg); + + /** + * Fired when message is received. + * + * @param msg message + */ + void messageReceived(@Nonnull Notification msg); +} diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/BGPSessionStateListener.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/BGPSessionStateListener.java new file mode 100644 index 0000000000..22e1e24f06 --- /dev/null +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/BGPSessionStateListener.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.protocol.bgp.rib.impl.spi; + +import java.net.SocketAddress; +import java.util.List; +import java.util.Set; +import javax.annotation.Nonnull; +import org.opendaylight.protocol.bgp.rib.spi.State; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType; + + +/** + * BGP Operational Session State Listener + */ +public interface BGPSessionStateListener extends BGPMessagesListener{ + /** + * Advertize Session capabilities + * + * @param holdTimerValue hold Timer + * @param remoteAddress remote Address + * @param localAddress local Address + * @param tableTypes supported families + * @param bgpParameters bgp capabilities + */ + void advertizeCapabilities(final int holdTimerValue, @Nonnull final SocketAddress remoteAddress, + @Nonnull final SocketAddress localAddress, @Nonnull final Set tableTypes, + @Nonnull List bgpParameters); + + /** + * Fired when session state changes + * + * @param state session state + */ + void setSessionState(@Nonnull State state); +} diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/InstanceType.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/InstanceType.java index 1b67d2afa3..898a6e79ca 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/InstanceType.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/InstanceType.java @@ -8,28 +8,29 @@ package org.opendaylight.protocol.bgp.rib.impl.spi; -import com.google.common.collect.Lists; +import com.google.common.collect.ImmutableList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeMXBean; import org.opendaylight.protocol.bgp.rib.RibReference; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerStateConsumer; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPRIBStateConsumer; public enum InstanceType { - RIB("ribImpl", Lists.newArrayList(RIB.class, RibReference.class)), + RIB("ribImpl", ImmutableList.of(RIB.class, RibReference.class, BGPRIBStateConsumer.class)), - PEER("bgpPeer", Collections.singletonList(BGPPeerRuntimeMXBean.class)), + PEER("bgpPeer", ImmutableList.of(BGPPeerRuntimeMXBean.class, BGPPeerStateConsumer.class)), - APP_PEER("appPeer", Collections.emptyList()); + APP_PEER("appPeer", Collections.singletonList(BGPPeerStateConsumer.class)); private final String beanName; - private final String[] services; + private final List services; InstanceType(final String beanName, final List> services) { this.beanName = beanName; - this.services = new String[services.size()]; - services.stream().map(clazz -> clazz.getName()).collect(Collectors.toList()).toArray(this.services); + this.services = ImmutableList.copyOf(services.stream().map(Class::getName).collect(Collectors.toList())); } public String getBeanName() { @@ -37,7 +38,6 @@ public enum InstanceType { } public String[] getServices() { - return this.services; + return this.services.toArray(new String[0]); } - } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPPeerStateImpl.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPPeerStateImpl.java new file mode 100644 index 0000000000..e53bd62947 --- /dev/null +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPPeerStateImpl.java @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.protocol.bgp.rib.impl.state; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableSet; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.LongAdder; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.annotation.concurrent.GuardedBy; +import org.opendaylight.protocol.bgp.rib.DefaultRibReference; +import org.opendaylight.protocol.bgp.rib.impl.spi.BGPMessagesListener; +import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesInstalledCounters; +import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesReceivedCounters; +import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesSentCounters; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPGracelfulRestartState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerMessagesState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerStateConsumer; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.Rib; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.RibKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey; +import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.Notification; + +public abstract class BGPPeerStateImpl extends DefaultRibReference implements BGPPeerState, BGPAfiSafiState, + BGPGracelfulRestartState, BGPErrorHandlingState, BGPPeerMessagesState, BGPPeerStateConsumer, BGPMessagesListener { + private static final long NONE = 0L; + private final IpAddress neighborAddress; + private final Set afiSafisAdvertized; + private final Set afiSafisGracefulAdvertized; + private final Set afiSafisGracefulReceived = new HashSet<>(); + private final LongAdder updateSentCounter = new LongAdder(); + private final LongAdder notificationSentCounter = new LongAdder(); + private final LongAdder updateReceivedCounter = new LongAdder(); + private final LongAdder notificationReceivedCounter = new LongAdder(); + private final LongAdder erroneousUpdate = new LongAdder(); + private final String groupId; + + @GuardedBy("this") + private final Map prefixesSent = new HashMap<>(); + @GuardedBy("this") + private PrefixesReceivedCounters prefixesReceived; + @GuardedBy("this") + private PrefixesInstalledCounters prefixesInstalled; + @GuardedBy("this") + private boolean localRestarting; + @GuardedBy("this") + private int peerRestartTime; + @GuardedBy("this") + private boolean peerRestarting; + + public BGPPeerStateImpl(@Nonnull final KeyedInstanceIdentifier instanceIdentifier, + @Nullable final String groupId, @Nonnull final IpAddress neighborAddress, + @Nonnull final Set afiSafisAdvertized, + @Nonnull final Set afiSafisGracefulAdvertized) { + super(instanceIdentifier); + this.neighborAddress = Preconditions.checkNotNull(neighborAddress); + this.groupId = groupId; + this.afiSafisAdvertized = Preconditions.checkNotNull(afiSafisAdvertized); + this.afiSafisGracefulAdvertized = Preconditions.checkNotNull(afiSafisGracefulAdvertized); + } + + @Override + public final String getGroupId() { + return this.groupId; + } + + @Override + public final IpAddress getNeighborAddress() { + return this.neighborAddress; + } + + @Override + public final synchronized long getTotalPrefixes() { + if (this.prefixesInstalled == null) { + return NONE; + } + return this.prefixesInstalled.getTotalPrefixesInstalled(); + } + + @Override + public final BGPPeerMessagesState getBGPPeerMessagesState() { + return this; + } + + @Override + public final BGPGracelfulRestartState getBGPGracelfulRestart() { + return this; + } + + @Override + public final synchronized boolean isAfiSafiSupported(final TablesKey tablesKey) { + return this.prefixesReceived != null && this.prefixesReceived.isSupported(tablesKey) && + this.afiSafisAdvertized.contains(tablesKey); + } + + @Override + public final synchronized long getPrefixesInstalledCount(final TablesKey tablesKey) { + if (this.prefixesInstalled == null) { + return NONE; + } + return this.prefixesInstalled.getPrefixedInstalledCount(tablesKey); + } + + @Override + public final synchronized long getPrefixesSentCount(@Nonnull final TablesKey tablesKey) { + if (this.prefixesSent == null) { + return 0; + } + final PrefixesSentCounters counter = this.prefixesSent.get(tablesKey); + if (counter == null) { + return NONE; + } + return counter.getPrefixesSentCount(); + } + + @Override + public final synchronized long getPrefixesReceivedCount(final TablesKey tablesKey) { + if (this.prefixesReceived == null) { + return NONE; + } + return this.prefixesReceived.getPrefixedReceivedCount(tablesKey); + } + + @Override + public final Set getAfiSafisAdvertized() { + return ImmutableSet.copyOf(this.afiSafisAdvertized); + } + + @Override + public final synchronized Set getAfiSafisReceived() { + if (this.prefixesReceived == null) { + return Collections.emptySet(); + } + return this.prefixesReceived.getTableKeys(); + } + + @Override + public final boolean isGracefulRestartAdvertized(final TablesKey tablesKey) { + return this.afiSafisGracefulAdvertized.contains(tablesKey); + } + + @Override + public final boolean isGracefulRestartReceived(final TablesKey tablesKey) { + return this.afiSafisGracefulReceived.contains(tablesKey); + } + + @Override + public final synchronized boolean isLocalRestarting() { + return this.localRestarting; + } + + @Override + public final synchronized int getPeerRestartTime() { + return this.peerRestartTime; + } + + @Override + public final synchronized boolean isPeerRestarting() { + return this.peerRestarting; + } + + //FIXME BUG-196 + public final void setAfiSafiGracefulRestartState(final int peerRestartTime, final boolean peerRestarting, + final boolean localRestarting) { + this.peerRestartTime = peerRestartTime; + this.peerRestarting = peerRestarting; + this.localRestarting = localRestarting; + } + + protected final synchronized void setAdvertizedGracefulRestartTableTypes(final List receivedGraceful) { + this.afiSafisGracefulReceived.addAll(receivedGraceful); + } + + protected final synchronized void registerPrefixesSentCounter(final TablesKey tablesKey, + final PrefixesSentCounters prefixesSentCounter) { + this.prefixesSent.put(tablesKey, prefixesSentCounter); + } + + protected final synchronized void registerPrefixesCounters(@Nonnull final PrefixesReceivedCounters prefixesReceived, + @Nonnull final PrefixesInstalledCounters prefixesInstalled) { + this.prefixesReceived = prefixesReceived; + this.prefixesInstalled = prefixesInstalled; + } + + protected final synchronized void resetState() { + this.localRestarting = false; + this.peerRestartTime = 0; + this.peerRestarting = false; + } + + @Override + public final BGPPeerState getPeerState() { + return this; + } + + @Override + public final long getErroneousUpdateReceivedCount() { + //FIXME BUG-4979 + return this.erroneousUpdate.longValue(); + } + + @Override + public final long getUpdateMessagesSentCount() { + return this.updateSentCounter.longValue(); + } + + @Override + public final long getNotificationMessagesSentCount() { + return this.notificationSentCounter.longValue(); + } + + @Override + public final long getUpdateMessagesReceivedCount() { + return this.updateReceivedCounter.longValue(); + } + + @Override + public final long getNotificationMessagesReceivedCount() { + return this.notificationReceivedCounter.longValue(); + } + + @Override + public final void messageSent(final Notification msg) { + if (msg instanceof Notify) { + this.notificationSentCounter.increment(); + } else if (msg instanceof Update) { + this.updateSentCounter.increment(); + } + } + + @Override + public final void messageReceived(final Notification msg) { + if (msg instanceof Notify) { + this.notificationReceivedCounter.increment(); + } else if (msg instanceof Update) { + this.updateReceivedCounter.increment(); + } + } +} diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPRIBStateImpl.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPRIBStateImpl.java new file mode 100644 index 0000000000..e09e5f5899 --- /dev/null +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPRIBStateImpl.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.protocol.bgp.rib.impl.state; + + +import com.google.common.base.Preconditions; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import javax.annotation.Nonnull; +import javax.annotation.concurrent.GuardedBy; +import org.opendaylight.protocol.bgp.rib.DefaultRibReference; +import org.opendaylight.protocol.bgp.rib.impl.state.rib.TotalPathsCounter; +import org.opendaylight.protocol.bgp.rib.impl.state.rib.TotalPrefixesCounter; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPRIBState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPRIBStateConsumer; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.Rib; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.RibKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpId; +import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; + +public class BGPRIBStateImpl extends DefaultRibReference implements BGPRIBState, BGPRIBStateConsumer { + private final BgpId routeId; + private final AsNumber localAs; + @GuardedBy("this") + private final Map totalPaths = new HashMap<>(); + @GuardedBy("this") + private final Map totalPrefixes = new HashMap<>(); + + protected BGPRIBStateImpl(final KeyedInstanceIdentifier instanceIdentifier, + @Nonnull final BgpId routeId, @Nonnull final AsNumber localAs) { + super(instanceIdentifier); + this.routeId = Preconditions.checkNotNull(routeId); + this.localAs = Preconditions.checkNotNull(localAs); + } + + @Override + public final synchronized Map getPrefixesCount() { + return this.totalPrefixes.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, + (entry) -> entry.getValue().getPrefixesCount())); + } + + @Override + public final synchronized Map getPathsCount() { + return this.totalPaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, + (entry) -> entry.getValue().getPathsCount())); + } + + @Override + public final synchronized long getTotalPathsCount() { + return this.totalPaths.values().stream().mapToLong(TotalPathsCounter::getPathsCount).sum(); + } + + @Override + public final synchronized long getTotalPrefixesCount() { + return this.totalPrefixes.values().stream().mapToLong(TotalPrefixesCounter::getPrefixesCount).sum(); + } + + @Override + public final synchronized long getPathCount(TablesKey tablesKey) { + return this.totalPaths.get(tablesKey).getPathsCount(); + } + + @Override + public final synchronized long getPrefixesCount(TablesKey tablesKey) { + return this.totalPrefixes.get(tablesKey).getPrefixesCount(); + } + + @Override + public final AsNumber getAs() { + return this.localAs; + } + + @Override + public final BgpId getRouteId() { + return this.routeId; + } + + protected final synchronized void registerTotalPathCounter(@Nonnull final TablesKey key, + @Nonnull final TotalPathsCounter totalPathsCounter) { + this.totalPaths.put(key, totalPathsCounter); + } + + protected final synchronized void registerTotalPrefixesCounter(@Nonnull final TablesKey key, + @Nonnull final TotalPrefixesCounter totalPrefixesCounter) { + this.totalPrefixes.put(key, totalPrefixesCounter); + } + + @Override + public final BGPRIBState getRIBState() { + return this; + } +} diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPSessionStateImpl.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPSessionStateImpl.java new file mode 100644 index 0000000000..15fcc2737f --- /dev/null +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPSessionStateImpl.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.protocol.bgp.rib.impl.state; + +import com.google.common.base.Stopwatch; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nonnull; +import javax.annotation.concurrent.GuardedBy; +import javax.annotation.concurrent.ThreadSafe; +import org.opendaylight.protocol.bgp.rib.impl.StrictBGPPeerRegistry; +import org.opendaylight.protocol.bgp.rib.impl.spi.BGPMessagesListener; +import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionStateListener; +import org.opendaylight.protocol.bgp.rib.spi.State; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParameters; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.MultiprotocolCapability; +import org.opendaylight.yangtools.yang.binding.Notification; + +@ThreadSafe +public final class BGPSessionStateImpl implements BGPSessionState, BGPTimersState, BGPTransportState, + BGPSessionStateListener { + private static final PortNumber NON_DEFINED_PORT = new PortNumber(0); + private final Stopwatch sessionStopwatch; + private int holdTimerValue; + private IpAddress remoteAddress; + private PortNumber remotePort = NON_DEFINED_PORT; + private PortNumber localPort = NON_DEFINED_PORT; + @GuardedBy("this") + private boolean addPathCapability; + @GuardedBy("this") + private boolean asn32Capability; + @GuardedBy("this") + private boolean gracefulRestartCapability; + @GuardedBy("this") + private boolean multiProtocolCapability; + @GuardedBy("this") + private boolean routerRefreshCapability; + @GuardedBy("this") + private State sessionState; + @GuardedBy("this") + private BGPMessagesListener messagesListenerCounter; + + public BGPSessionStateImpl() { + this.sessionState = State.OPEN_CONFIRM; + this.sessionStopwatch = Stopwatch.createUnstarted(); + } + + @Override + public synchronized void messageSent(final Notification msg) { + if (this.messagesListenerCounter != null) { + this.messagesListenerCounter.messageSent(msg); + } + } + + @Override + public synchronized void messageReceived(final Notification msg) { + if (this.messagesListenerCounter != null) { + this.messagesListenerCounter.messageReceived(msg); + } + } + + @Override + public synchronized void advertizeCapabilities(final int holdTimerValue, final SocketAddress remoteAddress, + final SocketAddress localAddress, final Set tableTypes, final List bgpParameters) { + if (bgpParameters != null && !bgpParameters.isEmpty()) { + for (final BgpParameters parameters : bgpParameters) { + for (final OptionalCapabilities optionalCapabilities : parameters.getOptionalCapabilities()) { + final CParameters cParam = optionalCapabilities.getCParameters(); + final CParameters1 capabilities = cParam.getAugmentation(CParameters1.class); + if (capabilities != null) { + final MultiprotocolCapability mc = capabilities.getMultiprotocolCapability(); + if (mc != null) { + this.multiProtocolCapability = true; + } + if (capabilities.getGracefulRestartCapability() != null) { + this.gracefulRestartCapability = true; + } + if (capabilities.getAddPathCapability() != null) { + this.addPathCapability = true; + } + if (capabilities.getRouteRefreshCapability() != null) { + this.routerRefreshCapability = true; + } + } + if (cParam.getAs4BytesCapability() != null) { + this.asn32Capability = true; + } + } + } + } + + this.holdTimerValue = holdTimerValue; + this.remoteAddress = StrictBGPPeerRegistry.getIpAddress(remoteAddress); + this.remotePort = new PortNumber(((InetSocketAddress) remoteAddress).getPort()); + this.localPort = new PortNumber(((InetSocketAddress) localAddress).getPort()); + } + + @Override + public synchronized State getSessionState() { + return this.sessionState; + } + + @Override + public synchronized void setSessionState(@Nonnull State state) { + if (state == State.IDLE) { + this.sessionStopwatch.reset(); + } else if (state == State.UP) { + this.sessionStopwatch.start(); + } + this.sessionState = state; + } + + @Override + public synchronized boolean isAddPathCapabilitySupported() { + return this.addPathCapability; + } + + @Override + public synchronized boolean isAsn32CapabilitySupported() { + return this.asn32Capability; + } + + @Override + public synchronized boolean isGracefulRestartCapabilitySupported() { + return this.gracefulRestartCapability; + } + + @Override + public synchronized boolean isMultiProtocolCapabilitySupported() { + return this.multiProtocolCapability; + } + + @Override + public synchronized boolean isRouterRefreshCapabilitySupported() { + return this.routerRefreshCapability; + } + + @Override + public synchronized PortNumber getLocalPort() { + return this.localPort; + } + + @Override + public synchronized IpAddress getRemoteAddress() { + return this.remoteAddress; + } + + @Nonnull + @Override + public synchronized PortNumber getRemotePort() { + return this.remotePort; + } + + @Override + public synchronized long getNegotiatedHoldTime() { + return this.holdTimerValue; + } + + @Override + public synchronized long getUpTime() { + return this.sessionStopwatch.elapsed(TimeUnit.MILLISECONDS); + } + + public synchronized void registerMessagesCounter(final BGPMessagesListener bgpMessagesListener) { + this.messagesListenerCounter= bgpMessagesListener; + } +} diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPSessionStateProvider.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPSessionStateProvider.java new file mode 100644 index 0000000000..1f9beebbe3 --- /dev/null +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPSessionStateProvider.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.protocol.bgp.rib.impl.state; + +import org.opendaylight.protocol.bgp.rib.impl.spi.BGPMessagesListener; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState; + +/** + * Serves to expose BGP Session, Timers, Transport, BGPErrorHandlingState Operational State + */ +public interface BGPSessionStateProvider { + /** + * BGP Operational Session State + * @return BGPSessionState + */ + BGPSessionState getBGPSessionState(); + + /** + * BGP Operational Timers State + * @return BGPTimersState + */ + BGPTimersState getBGPTimersState(); + + /** + * BGP Operational Transport State + * @return BGPTransportState + */ + BGPTransportState getBGPTransportState(); + + /** + * Register BGP Operational Messages State Listener + * @param bgpMessagesListener BGPMessagesListener + */ + void registerMessagesCounter(BGPMessagesListener bgpMessagesListener); +} diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPStateCollectorImpl.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPStateCollectorImpl.java index 18c81bc221..0937aac4f2 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPStateCollectorImpl.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/BGPStateCollectorImpl.java @@ -10,6 +10,7 @@ package org.opendaylight.protocol.bgp.rib.impl.state; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import org.opendaylight.protocol.bgp.rib.spi.state.BGPPeerState; @@ -22,21 +23,23 @@ import org.opendaylight.protocol.bgp.rib.spi.state.BGPStateProvider; @ThreadSafe public class BGPStateCollectorImpl implements BGPStateProvider, BGPStateConsumer { @GuardedBy("this") - private final List bgpRibStates = new ArrayList<>(); + private final List bgpRibStates = new ArrayList<>(); @GuardedBy("this") - private final List bgpPeerStates = new ArrayList<>(); + private final List bgpPeerStates = new ArrayList<>(); @Override public List getRibStats() { synchronized (this.bgpRibStates) { - return ImmutableList.copyOf(this.bgpRibStates); + return ImmutableList.copyOf(this.bgpRibStates.stream().map(BGPRIBStateConsumer::getRIBState) + .collect(Collectors.toList())); } } @Override public List getPeerStats() { synchronized (this.bgpPeerStates) { - return ImmutableList.copyOf(this.bgpPeerStates); + return ImmutableList.copyOf(this.bgpPeerStates.stream().map(BGPPeerStateConsumer::getPeerState) + .collect(Collectors.toList())); } } @@ -46,7 +49,7 @@ public class BGPStateCollectorImpl implements BGPStateProvider, BGPStateConsumer return; } synchronized (this.bgpRibStates) { - this.bgpRibStates.add(bgpState.getRIBState()); + this.bgpRibStates.add(bgpState); } } @@ -56,7 +59,7 @@ public class BGPStateCollectorImpl implements BGPStateProvider, BGPStateConsumer return; } synchronized (this.bgpRibStates) { - this.bgpRibStates.remove(bgpState.getRIBState()); + this.bgpRibStates.remove(bgpState); } } @@ -66,7 +69,7 @@ public class BGPStateCollectorImpl implements BGPStateProvider, BGPStateConsumer return; } synchronized (this.bgpPeerStates) { - this.bgpPeerStates.add(bgpState.getPeerState()); + this.bgpPeerStates.add(bgpState); } } @@ -76,7 +79,7 @@ public class BGPStateCollectorImpl implements BGPStateProvider, BGPStateConsumer return; } synchronized (this.bgpPeerStates) { - this.bgpPeerStates.remove(bgpState.getPeerState()); + this.bgpPeerStates.remove(bgpState); } } } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/peer/PrefixesInstalledCounters.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/peer/PrefixesInstalledCounters.java new file mode 100644 index 0000000000..5c82618200 --- /dev/null +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/peer/PrefixesInstalledCounters.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.protocol.bgp.rib.impl.state.peer; + +import javax.annotation.Nonnull; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey; + +/** + * Expose Prefixes Installed Count + */ +public interface PrefixesInstalledCounters { + /** + * Prefixes received and installed from Peer count (EffRibIn Count) pet Table + * @param tablesKey table + * @return count + */ + long getPrefixedInstalledCount(@Nonnull final TablesKey tablesKey); + + /** + * total Prefixes received and installed from Peer count (EffRibIn Count) + * @return count + */ + long getTotalPrefixesInstalled(); +} diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/peer/PrefixesReceivedCounters.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/peer/PrefixesReceivedCounters.java new file mode 100644 index 0000000000..842dbf73de --- /dev/null +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/peer/PrefixesReceivedCounters.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.protocol.bgp.rib.impl.state.peer; + +import java.util.Set; +import javax.annotation.Nonnull; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey; + +/** + * Expose Prefixes Received Count + */ +public interface PrefixesReceivedCounters { + /** + * Prefixes received from Peer count (AdjRinIn Count) pet Table + * @param tablesKey table + * @return count + */ + long getPrefixedReceivedCount(@Nonnull final TablesKey tablesKey); + + /** + * list of supported tables per Peer + * @return tables list + */ + Set getTableKeys(); + + /** + * table supported per Peer + * @param tablesKey table type + * @return true if supported + */ + boolean isSupported(TablesKey tablesKey); +} diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/peer/PrefixesSentCounters.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/peer/PrefixesSentCounters.java new file mode 100644 index 0000000000..aece504e78 --- /dev/null +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/peer/PrefixesSentCounters.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.protocol.bgp.rib.impl.state.peer; + +/** + * Expose Prefixes Sent Count + */ +public interface PrefixesSentCounters { + /** + * Prefixes sent to peer + * @return count + */ + long getPrefixesSentCount(); +} diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/rib/TotalPathsCounter.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/rib/TotalPathsCounter.java new file mode 100644 index 0000000000..4e80c8ae41 --- /dev/null +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/rib/TotalPathsCounter.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.protocol.bgp.rib.impl.state.rib; + +/** + * Expose Total Paths Count per RIB + */ +public interface TotalPathsCounter { + /** + * Total Paths installed on RIB + * @return count + */ + long getPathsCount(); +} diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/rib/TotalPrefixesCounter.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/rib/TotalPrefixesCounter.java new file mode 100644 index 0000000000..d38ff3a5d7 --- /dev/null +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/state/rib/TotalPrefixesCounter.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.protocol.bgp.rib.impl.state.rib; + +/** + * Expose Total Prefixes Count per RIB + */ +public interface TotalPrefixesCounter { + /** + * Total Prefixes installed on RIB + * @return count + */ + long getPrefixesCount(); +} diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/BGPPeerStats.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/BGPPeerStats.java index ae251e8b0c..9503a520de 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/BGPPeerStats.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/BGPPeerStats.java @@ -18,7 +18,5 @@ public interface BGPPeerStats { PerTableTypeRouteCounter getAdjRibOutRouteCounters(); - PerTableTypeRouteCounter getEffectiveRibInRouteCounters(); - LongAdder getSessionEstablishedCounter(); } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/BGPPeerStatsImpl.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/BGPPeerStatsImpl.java index df41686296..1716cd04fd 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/BGPPeerStatsImpl.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/BGPPeerStatsImpl.java @@ -18,7 +18,9 @@ import javax.annotation.Nonnull; import org.opendaylight.controller.config.api.IdentityAttributeRef; import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpPeerState; import org.opendaylight.controller.config.yang.bgp.rib.impl.RouteTable; +import org.opendaylight.protocol.bgp.rib.impl.state.BGPPeerStateImpl; import org.opendaylight.protocol.bgp.rib.impl.stats.peer.route.PerTableTypeRouteCounter; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.ZeroBasedCounter32; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey; import org.opendaylight.yangtools.yang.binding.util.BindingReflections; import org.opendaylight.yangtools.yang.common.QName; @@ -27,26 +29,24 @@ public final class BGPPeerStatsImpl implements BGPPeerStats { private final Set tablesKeySet; private final PerTableTypeRouteCounter adjRibInRouteCounters; private final PerTableTypeRouteCounter adjRibOutRouteCounters; - private final PerTableTypeRouteCounter effectiveRibInRouteCounters; private final LongAdder sessionEstablishedCounter = new LongAdder(); + private final BGPPeerStateImpl neighborState; - public BGPPeerStatsImpl(@Nonnull final Set tablesKeySet) { + public BGPPeerStatsImpl(@Nonnull final String peerName, @Nonnull final Set tablesKeySet, + @Nonnull final BGPPeerStateImpl neighborState) { + Preconditions.checkNotNull(peerName); this.tablesKeySet = Preconditions.checkNotNull(tablesKeySet); this.adjRibInRouteCounters = new PerTableTypeRouteCounter(tablesKeySet); this.adjRibOutRouteCounters = new PerTableTypeRouteCounter(tablesKeySet); - this.effectiveRibInRouteCounters = new PerTableTypeRouteCounter(tablesKeySet); + this.neighborState = Preconditions.checkNotNull(neighborState); } public PerTableTypeRouteCounter getAdjRibInRouteCounters() { - return adjRibInRouteCounters; + return this.adjRibInRouteCounters; } public PerTableTypeRouteCounter getAdjRibOutRouteCounters() { - return adjRibOutRouteCounters; - } - - public PerTableTypeRouteCounter getEffectiveRibInRouteCounters() { - return effectiveRibInRouteCounters; + return this.adjRibOutRouteCounters; } private RouteTable createRouteTable(@Nonnull final TablesKey tablesKey) { @@ -62,7 +62,8 @@ public final class BGPPeerStatsImpl implements BGPPeerStats { // we want to get default counter in case particular route table is not initialized (e.g. adj-rib-out is not initialized in some cases) routeTable.setAdjRibInRoutesCount(toZeroBasedCounter32(this.adjRibInRouteCounters.getCounterOrDefault(tablesKey))); routeTable.setAdjRibOutRoutesCount(toZeroBasedCounter32(this.adjRibOutRouteCounters.getCounterOrDefault(tablesKey))); - routeTable.setEffectiveRibInRoutesCount(toZeroBasedCounter32(this.effectiveRibInRouteCounters.getCounterOrDefault(tablesKey))); + routeTable.setEffectiveRibInRoutesCount(new ZeroBasedCounter32(this.neighborState + .getPrefixesInstalledCount(tablesKey))); return routeTable; } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/BGPSessionStatsImpl.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/BGPSessionStatsImpl.java index 7175c9e189..68497e787b 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/BGPSessionStatsImpl.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/BGPSessionStatsImpl.java @@ -77,6 +77,7 @@ public final class BGPSessionStatsImpl implements BGPSessionStats { private final ErrorMsgs errMsgs = new ErrorMsgs(); private final ErrorSentTotal errMsgsSentTotal = new ErrorSentTotal(); private final ErrorReceivedTotal errMsgsRecvTotal = new ErrorReceivedTotal(); + private static final ZeroBasedCounter32 INITIAL_COUNTER = new ZeroBasedCounter32(0L); public BGPSessionStatsImpl(@Nonnull final BGPSessionImpl session, @Nonnull final Open remoteOpen, final int holdTimerValue, final int keepAlive, @Nonnull final Channel channel, @Nonnull final Optional localPreferences, @Nonnull final Collection tableTypes, @Nonnull final List addPathTypes) { @@ -87,8 +88,8 @@ public final class BGPSessionStatsImpl implements BGPSessionStats { this.stats.setKeepaliveCurrent(keepAlive); this.stats.setLocalPeerPreferences(setLocalPeerPref(remoteOpen, channel, tableTypes, addPathTypes)); this.stats.setRemotePeerPreferences(setRemotePeerPref(channel, localPreferences)); - this.errMsgs.setErrorReceivedTotal(errMsgsRecvTotal); - this.errMsgs.setErrorSentTotal(errMsgsSentTotal); + this.errMsgs.setErrorReceivedTotal(this.errMsgsRecvTotal); + this.errMsgs.setErrorSentTotal(this.errMsgsSentTotal); this.errMsgs.setErrorReceived(new ArrayList<>()); this.errMsgs.setErrorSent(new ArrayList<>()); initMsgs(); @@ -96,13 +97,13 @@ public final class BGPSessionStatsImpl implements BGPSessionStats { private static Received newReceivedInstance() { final Received recv = new Received(); - recv.setCount(new ZeroBasedCounter32(0L)); + recv.setCount(INITIAL_COUNTER); return recv; } private static Sent newSentInstance() { final Sent sent = new Sent(); - sent.setCount(new ZeroBasedCounter32(0L)); + sent.setCount(INITIAL_COUNTER); return sent; } @@ -255,8 +256,8 @@ public final class BGPSessionStatsImpl implements BGPSessionStats { this.updMsgs.setSent(newSentInstance()); this.rrMsgs.setReceived(newReceivedInstance()); this.rrMsgs.setSent(newSentInstance()); - this.errMsgsSentTotal.setCount(new ZeroBasedCounter32(0L)); - this.errMsgsRecvTotal.setCount(new ZeroBasedCounter32(0L)); + this.errMsgsSentTotal.setCount(INITIAL_COUNTER); + this.errMsgsRecvTotal.setCount(INITIAL_COUNTER); this.errMsgs.getErrorSent().clear(); this.errMsgs.getErrorReceived().clear(); } @@ -311,7 +312,7 @@ public final class BGPSessionStatsImpl implements BGPSessionStats { received = new ErrorReceived(); received.setErrorCode(error.getErrorCode()); received.setErrorSubcode(error.getErrorSubcode()); - received.setCount(new ZeroBasedCounter32(0L)); + received.setCount(INITIAL_COUNTER); errList.add(received); } received.setCount(new ZeroBasedCounter32(received.getCount().getValue() + 1)); @@ -335,7 +336,7 @@ public final class BGPSessionStatsImpl implements BGPSessionStats { sent = new ErrorSent(); sent.setErrorCode(error.getErrorCode()); sent.setErrorSubcode(error.getErrorSubcode()); - sent.setCount(new ZeroBasedCounter32(0L)); + sent.setCount(INITIAL_COUNTER); errList.add(sent); } sent.setCount(new ZeroBasedCounter32(sent.getCount().getValue() + 1)); diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/route/PerTableTypeRouteCounter.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/route/PerTableTypeRouteCounter.java index e2af7a3378..57bc5f82ad 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/route/PerTableTypeRouteCounter.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/peer/route/PerTableTypeRouteCounter.java @@ -47,6 +47,7 @@ public final class PerTableTypeRouteCounter { /** * Get the counter for given tablesKey. Return an empty counter if it doesn't exist * NOTE: the created empty counter won't be put into the original map + * * @param tablesKey * @return */ @@ -57,6 +58,7 @@ public final class PerTableTypeRouteCounter { /** * Get the counter with given tablesKey. Create an empty counter if it doesn't exist * This method will put the created empty counter back to map + * * @param tablesKey * @return */ @@ -76,4 +78,10 @@ public final class PerTableTypeRouteCounter { LOG.debug("Resetting all route counters.."); this.counters.values().forEach(LongAdder::reset); } + + public void setValueToCounterOrSetDefault(final TablesKey tablesKey, final int size) { + final LongAdder counter = getCounterOrSetDefault(tablesKey); + counter.reset(); + counter.add(size); + } } diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/BGPRenderStats.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/BGPRenderStats.java index 0d2de4fc92..a648f8a47a 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/BGPRenderStats.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/BGPRenderStats.java @@ -9,12 +9,8 @@ package org.opendaylight.protocol.bgp.rib.impl.stats.rib.impl; import java.util.concurrent.atomic.LongAdder; import org.opendaylight.controller.config.yang.bgp.rib.impl.RIBImplRuntimeMXBean; -import org.opendaylight.protocol.bgp.rib.impl.stats.peer.route.PerTableTypeRouteCounter; public interface BGPRenderStats extends RIBImplRuntimeMXBean { - - PerTableTypeRouteCounter getLocRibRouteCounter(); - LongAdder getConfiguredPeerCounter(); LongAdder getConnectedPeerCounter(); diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/BGPRenderStatsImpl.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/BGPRenderStatsImpl.java index a84662a95e..368dbd5dc1 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/BGPRenderStatsImpl.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/BGPRenderStatsImpl.java @@ -12,15 +12,16 @@ import static org.opendaylight.protocol.bgp.rib.impl.CountersUtil.toZeroBasedCou import com.google.common.base.Preconditions; import java.util.ArrayList; import java.util.List; -import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.LongAdder; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.opendaylight.controller.config.api.IdentityAttributeRef; import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpRenderState; import org.opendaylight.controller.config.yang.bgp.rib.impl.LocRibRouteTable; -import org.opendaylight.protocol.bgp.rib.impl.stats.peer.route.PerTableTypeRouteCounter; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPRIBState; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.ZeroBasedCounter32; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.RibId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpId; @@ -28,22 +29,25 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.type import org.opendaylight.yangtools.yang.binding.util.BindingReflections; import org.opendaylight.yangtools.yang.common.QName; -public class BGPRenderStatsImpl implements BGPRenderStats { - private final PerTableTypeRouteCounter locRibRouteCounter = new PerTableTypeRouteCounter(); +public final class BGPRenderStatsImpl implements BGPRenderStats { private final BgpId bgpId; private final RibId ribId; private final ClusterIdentifier clusterId; private final AsNumber localAs; - private final LongAdder configuredPeerCounter; - private final LongAdder connectedPeerCounter; + private final LongAdder configuredPeerCounter = new LongAdder(); + private final LongAdder connectedPeerCounter = new LongAdder(); + private final BGPRIBState globalState; + private final Set tablesKeys; - public BGPRenderStatsImpl(@Nonnull final BgpId bgpId, @Nonnull final RibId ribId, @Nonnull final AsNumber localAs, @Nullable final ClusterIdentifier clusterId) { + public BGPRenderStatsImpl(@Nonnull final BgpId bgpId, @Nonnull final RibId ribId, @Nonnull final AsNumber localAs, + @Nullable final ClusterIdentifier clusterId, @Nonnull final BGPRIBState globalState, + @Nonnull final Set tablesKeys) { this.bgpId = Preconditions.checkNotNull(bgpId); this.ribId = Preconditions.checkNotNull(ribId); + this.globalState = Preconditions.checkNotNull(globalState); + this.tablesKeys = Preconditions.checkNotNull(tablesKeys); this.localAs = localAs; this.clusterId = clusterId; - this.configuredPeerCounter = new LongAdder(); - this.connectedPeerCounter = new LongAdder(); } @Override @@ -58,30 +62,26 @@ public class BGPRenderStatsImpl implements BGPRenderStats { // fill in the the statistic part final LongAdder totalRouteCount = new LongAdder(); final List locRibRouteTableList = new ArrayList<>(); - this.locRibRouteCounter.getCounters().entrySet().forEach(e -> generateCounters(e, locRibRouteTableList, totalRouteCount)); + this.tablesKeys.forEach(e -> generateCounters(e, locRibRouteTableList, totalRouteCount)); renderState.setLocRibRouteTable(locRibRouteTableList); renderState.setLocRibRoutesCount(toZeroBasedCounter32(totalRouteCount)); return renderState; } - private void generateCounters(final Map.Entry e, final List locRibRouteTableList, + private void generateCounters(final TablesKey tablesKey, final List locRibRouteTableList, final LongAdder totalRouteCount) { final LocRibRouteTable table = new LocRibRouteTable(); - final QName afi = BindingReflections.getQName(e.getKey().getAfi()).intern(); - final QName safi = BindingReflections.getQName(e.getKey().getSafi()).intern(); + final QName afi = BindingReflections.getQName(tablesKey.getAfi()).intern(); + final QName safi = BindingReflections.getQName(tablesKey.getSafi()).intern(); table.setAfi(new IdentityAttributeRef(afi.toString())); table.setSafi(new IdentityAttributeRef(safi.toString())); - table.setRoutesCount(toZeroBasedCounter32(e.getValue())); + final long count = this.globalState.getPathCount(tablesKey); + table.setRoutesCount(new ZeroBasedCounter32(count)); locRibRouteTableList.add(table); - totalRouteCount.add(e.getValue().longValue()); + totalRouteCount.add(count); } - @Override - public PerTableTypeRouteCounter getLocRibRouteCounter() { - return this.locRibRouteCounter; - } - @Override public LongAdder getConfiguredPeerCounter() { return this.configuredPeerCounter; diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/RIBImplRuntimeMXBeanImpl.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/RIBImplRuntimeMXBeanImpl.java index 01e8c7ceac..0d7fde3897 100644 --- a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/RIBImplRuntimeMXBeanImpl.java +++ b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/RIBImplRuntimeMXBeanImpl.java @@ -7,13 +7,15 @@ */ package org.opendaylight.protocol.bgp.rib.impl.stats.rib.impl; +import java.util.Set; import java.util.concurrent.atomic.LongAdder; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpRenderState; -import org.opendaylight.protocol.bgp.rib.impl.stats.peer.route.PerTableTypeRouteCounter; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPRIBState; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.RibId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.ClusterIdentifier; @@ -23,8 +25,11 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.type public class RIBImplRuntimeMXBeanImpl implements BGPRenderStats { private final BGPRenderStats renderStats; - public RIBImplRuntimeMXBeanImpl(@Nonnull final BgpId bgpId, @Nonnull final RibId ribId, @Nonnull final AsNumber localAs, @Nullable final ClusterIdentifier clusterId) { - this.renderStats = new BGPRenderStatsImpl(bgpId, ribId, localAs, clusterId); + public RIBImplRuntimeMXBeanImpl(@Nonnull final BgpId bgpId, @Nonnull final RibId ribId, + @Nonnull final AsNumber localAs, @Nullable final ClusterIdentifier clusterId, + @Nonnull final BGPRIBState globalState, + @Nonnull final Set tablesKeys) { + this.renderStats = new BGPRenderStatsImpl(bgpId, ribId, localAs, clusterId, globalState, tablesKeys); } @Override @@ -32,11 +37,6 @@ public class RIBImplRuntimeMXBeanImpl implements BGPRenderStats { return this.renderStats.getBgpRenderState(); } - @Override - public PerTableTypeRouteCounter getLocRibRouteCounter() { - return this.renderStats.getLocRibRouteCounter(); - } - @Override public LongAdder getConfiguredPeerCounter() { return this.renderStats.getConfiguredPeerCounter(); diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AbstractAddPathTest.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AbstractAddPathTest.java index 20edea6e66..54ff39750e 100644 --- a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AbstractAddPathTest.java +++ b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AbstractAddPathTest.java @@ -18,10 +18,10 @@ import com.google.common.net.InetAddresses; import io.netty.channel.epoll.Epoll; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.concurrent.Future; -import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Collections; import java.util.List; +import java.util.Set; import java.util.concurrent.ExecutionException; import javassist.ClassPool; import org.junit.After; @@ -87,6 +87,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.mult import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.BgpRib; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpOrigin; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.ClusterIdentifier; @@ -104,7 +105,7 @@ import org.opendaylight.yangtools.yang.binding.util.BindingReflections; import org.opendaylight.yangtools.yang.model.api.SchemaContext; class AbstractAddPathTest extends AbstractDataBrokerTest { - static final int RETRY_TIMER = 10; + private static final int RETRY_TIMER = 10; static final String RIB_ID = "127.0.0.1"; static final Ipv4Address PEER1 = new Ipv4Address("127.0.0.2"); static final Ipv4Address PEER2 = new Ipv4Address("127.0.0.3"); @@ -126,6 +127,8 @@ class AbstractAddPathTest extends AbstractDataBrokerTest { static final Update UPD_NA_100_EBGP = createSimpleUpdateEbgp(PREFIX1, null); static final Update UPD_NA_200 = createSimpleUpdate(PREFIX1, null, CLUSTER_ID, 200); static final Update UPD_NA_200_EBGP = createSimpleUpdateEbgp(PREFIX1, null); + static final TablesKey TABLES_KEY = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class); + static final Set AFI_SAFIS_ADVERTIZED = Collections.singleton(TABLES_KEY); protected BGPExtensionProviderContext context; private static final InstanceIdentifier BGP_IID = InstanceIdentifier.create(BgpRib.class); protected SchemaContext schemaContext; @@ -228,11 +231,14 @@ class AbstractAddPathTest extends AbstractDataBrokerTest { } private static void configurePeer(final Ipv4Address localAddress, final RIBImpl ribImpl, final BgpParameters bgpParameters, final PeerRole peerRole) { - final InetAddress inetAddress = InetAddresses.forString(localAddress.getValue()); + final IpAddress ipAddress = new IpAddress(new Ipv4Address(InetAddresses.forString(localAddress.getValue()) + .getHostAddress())); - final BGPPeer bgpPeer = new BGPPeer(inetAddress.getHostAddress(), ribImpl, peerRole, null); + + final BGPPeer bgpPeer = new BGPPeer(localAddress.getValue(), ribImpl, peerRole, null, AFI_SAFIS_ADVERTIZED, + Collections.emptySet()); final List tlvs = Lists.newArrayList(bgpParameters); - StrictBGPPeerRegistry.GLOBAL.addPeer(new IpAddress(new Ipv4Address(inetAddress.getHostAddress())), bgpPeer, + StrictBGPPeerRegistry.GLOBAL.addPeer(ipAddress, bgpPeer, new BGPSessionPreferences(AS_NUMBER, HOLDTIMER, new BgpId(RIB_ID), AS_NUMBER, tlvs, Optional.absent())); bgpPeer.instantiateServiceInstance(); } diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AddPathAllPathsTest.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AddPathAllPathsTest.java index 2e02469b2a..26fc97e847 100644 --- a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AddPathAllPathsTest.java +++ b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AddPathAllPathsTest.java @@ -45,8 +45,7 @@ public class AddPathAllPathsTest extends AbstractAddPathTest { public void testUseCase1() throws Exception { final List tables = ImmutableList.of(new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class)); - final TablesKey tk = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class); - final Map pathTables = ImmutableMap.of(tk, new AllPathSelection()); + final Map pathTables = ImmutableMap.of(TABLES_KEY, new AllPathSelection()); final RIBImpl ribImpl = new RIBImpl(this.clusterSingletonServiceProvider, new RibId("test-rib"), AS_NUMBER, new BgpId(RIB_ID), null, this.ribExtension, diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/ParserToSalTest.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/ParserToSalTest.java index cc3de9c9a0..facaa64338 100755 --- a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/ParserToSalTest.java +++ b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/ParserToSalTest.java @@ -52,6 +52,8 @@ import org.opendaylight.protocol.bgp.rib.spi.RIBExtensionProviderContext; import org.opendaylight.protocol.bgp.rib.spi.SimpleRIBExtensionProviderContext; import org.opendaylight.protocol.bgp.util.HexDumpBGPFileParser; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber; +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.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv4.routes.ipv4.routes.Ipv4Route; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.ipv6.routes.ipv6.routes.Ipv6Route; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.linkstate.rev150210.LinkstateAddressFamily; @@ -81,6 +83,8 @@ public class ParserToSalTest extends AbstractDataBrokerTest { private AbstractRIBExtensionProviderActivator baseact, lsact; private RIBExtensionProviderContext ext1, ext2; private static final TablesKey TABLE_KEY = new TablesKey(LinkstateAddressFamily.class, LinkstateSubsequentAddressFamily.class); + private String localAddress = "127.0.0.1"; + private final IpAddress neighborAddress = new IpAddress(new Ipv4Address(localAddress)); @Mock BGPDispatcher dispatcher; @Mock @@ -149,7 +153,8 @@ public class ParserToSalTest extends AbstractDataBrokerTest { rib.instantiateServiceInstance(); assertTablesExists(tables, true); rib.onGlobalContextUpdated(this.schemaService.getGlobalContext()); - final BGPPeer peer = new BGPPeer("peer-" + this.mock.toString(), rib, PeerRole.Ibgp, null); + final BGPPeer peer = new BGPPeer(this.localAddress, rib, PeerRole.Ibgp, null, Collections.emptySet(), + Collections.emptySet()); peer.instantiateServiceInstance(); final ListenerRegistration reg = this.mock.registerUpdateListener(peer); reg.close(); @@ -164,7 +169,8 @@ public class ParserToSalTest extends AbstractDataBrokerTest { rib.instantiateServiceInstance(); rib.onGlobalContextUpdated(this.schemaService.getGlobalContext()); assertTablesExists(tables, true); - final BGPPeer peer = new BGPPeer("peer-" + this.mock.toString(), rib, PeerRole.Ibgp, null); + final BGPPeer peer = new BGPPeer(this.localAddress, rib, PeerRole.Ibgp, null, Collections.emptySet(), + Collections.emptySet()); peer.instantiateServiceInstance(); final ListenerRegistration reg = this.mock.registerUpdateListener(peer); reg.close(); diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/PeerTest.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/PeerTest.java index 4365e26f70..39167ebd39 100644 --- a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/PeerTest.java +++ b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/PeerTest.java @@ -29,8 +29,6 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.opendaylight.controller.config.yang.bgp.rib.impl.RouteTable; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.protocol.bgp.parser.BGPDocumentedException; @@ -89,6 +87,7 @@ public class PeerTest extends AbstractRIBTestSetup { private Map> routes; private BGPPeer classic; + private final Ipv4Address neighborAddress = new Ipv4Address("127.0.0.1"); @Override @Before @@ -99,25 +98,19 @@ public class PeerTest extends AbstractRIBTestSetup { } private void overrideMockedBehaviour() { - Mockito.doAnswer(new Answer() { - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable { - final Object[] args = invocation.getArguments(); - final NormalizedNode node = (NormalizedNode) args[2]; - if (node.getIdentifier().getNodeType().equals(Ipv4Route.QNAME) || node.getNodeType().equals(PREFIX_QNAME)) { - PeerTest.this.routes.put((YangInstanceIdentifier) args[1], node); - } - return args[1]; + Mockito.doAnswer(invocation -> { + final Object[] args = invocation.getArguments(); + final NormalizedNode node = (NormalizedNode) args[2]; + if (node.getIdentifier().getNodeType().equals(Ipv4Route.QNAME) || node.getNodeType().equals(PREFIX_QNAME)) { + this.routes.put((YangInstanceIdentifier) args[1], node); } + return args[1]; }).when(getTransaction()).put(Mockito.eq(LogicalDatastoreType.OPERATIONAL), Mockito.any(YangInstanceIdentifier.class), Mockito.any(NormalizedNode.class)); - Mockito.doAnswer(new Answer() { - @Override - public Object answer(final InvocationOnMock invocation) throws Throwable { - final Object[] args = invocation.getArguments(); - PeerTest.this.routes.remove(args[1]); - return args[1]; - } + Mockito.doAnswer(invocation -> { + final Object[] args = invocation.getArguments(); + this.routes.remove(args[1]); + return args[1]; }).when(getTransaction()).delete(Mockito.eq(LogicalDatastoreType.OPERATIONAL), Mockito.any(YangInstanceIdentifier.class)); } @@ -126,7 +119,7 @@ public class PeerTest extends AbstractRIBTestSetup { final Ipv4Prefix first = new Ipv4Prefix("127.0.0.2/32"); final Ipv4Prefix second = new Ipv4Prefix("127.0.0.1/32"); final Ipv4Prefix third = new Ipv4Prefix("127.0.0.3/32"); - this.peer = new ApplicationPeer(new ApplicationRibId("t"), new Ipv4Address("127.0.0.1"), getRib()); + this.peer = new ApplicationPeer(new ApplicationRibId(this.neighborAddress.getValue()), this.neighborAddress, getRib()); this.peer.instantiateServiceInstance(null, null); final YangInstanceIdentifier base = getRib().getYangRibId().node(LocRib.QNAME).node(Tables.QNAME).node(RibSupportUtils.toYangTablesKey(KEY)); this.peer.onDataTreeChanged(ipv4Input(base, ModificationType.WRITE, first, second, third)); @@ -138,14 +131,15 @@ public class PeerTest extends AbstractRIBTestSetup { @Test public void testClassicPeer() throws Exception { - this.classic = new BGPPeer("testPeer", getRib(), PeerRole.Ibgp, null); + this.classic = new BGPPeer(this.neighborAddress.getValue(), getRib(), PeerRole.Ibgp, null, Collections.emptySet(), + Collections.emptySet()); this.classic.instantiateServiceInstance(); this.mockSession(); - assertEquals("testPeer", this.classic.getName()); + assertEquals(this.neighborAddress.getValue(), this.classic.getName()); this.classic.onSessionUp(this.session); assertEquals(1, this.classic.getBgpPeerState().getSessionEstablishedCount().getValue().intValue()); Assert.assertArrayEquals(new byte[]{1, 1, 1, 1}, this.classic.getRawIdentifier()); - assertEquals("BGPPeer{name=testPeer, tables=[TablesKey [_afi=class org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Ipv4AddressFamily, _safi=class org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily]]}", this.classic.toString()); + assertEquals("BGPPeer{name=127.0.0.1, tables=[TablesKey [_afi=class org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Ipv4AddressFamily, _safi=class org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily]]}", this.classic.toString()); final List prefs = Lists.newArrayList(new Ipv4Prefix("8.0.1.0/28"), new Ipv4Prefix("127.0.0.1/32"), new Ipv4Prefix("2.2.2.2/24")); final UpdateBuilder ub = new UpdateBuilder(); @@ -172,7 +166,8 @@ public class PeerTest extends AbstractRIBTestSetup { assertEquals(3, this.routes.size()); //create new peer so that it gets advertized routes from RIB - try (final BGPPeer testingPeer = new BGPPeer("testingPeer", getRib(), PeerRole.Ibgp, null)) { + try (final BGPPeer testingPeer = new BGPPeer(this.neighborAddress.getValue(), getRib(), PeerRole.Ibgp, null, + Collections.emptySet(), Collections.emptySet())) { testingPeer.instantiateServiceInstance(); testingPeer.onSessionUp(this.session); assertEquals(3, this.routes.size()); diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/SynchronizationAndExceptionTest.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/SynchronizationAndExceptionTest.java index 619a210563..17343e2e7d 100644 --- a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/SynchronizationAndExceptionTest.java +++ b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/SynchronizationAndExceptionTest.java @@ -53,6 +53,7 @@ import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil; import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl; import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber; +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.Ipv4Prefix; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Notify; @@ -105,6 +106,7 @@ public class SynchronizationAndExceptionTest extends AbstractAddPathTest { private static final AsNumber AS_NUMBER = new AsNumber(30L); private static final Ipv4Address BGP_ID = new Ipv4Address("1.1.1.2"); private static final String LOCAL_IP = "1.1.1.4"; + private final IpAddress neighbor = new IpAddress(new Ipv4Address(LOCAL_IP)); private static final int LOCAL_PORT = 12345; private final BgpTableType ipv4tt = new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class); private Open classicOpen; @@ -199,15 +201,17 @@ public class SynchronizationAndExceptionTest extends AbstractAddPathTest { @Test public void testHandleMessageAfterException() throws InterruptedException { - final Map pathTables = ImmutableMap.of(new TablesKey(ipv4tt.getAfi(), ipv4tt.getSafi()), + final Map pathTables = ImmutableMap.of(TABLES_KEY, BasePathSelectionModeFactory.createBestPathSelectionStrategy()); - final RIBImpl ribImpl = new RIBImpl(this.clusterSingletonServiceProvider, new RibId(RIB_ID), AS_NUMBER, new BgpId(RIB_ID), null, this.ribExtension, - this.dispatcher, this.mappingService.getCodecFactory(), this.domBroker, ImmutableList.of(ipv4tt), pathTables, this.ribExtension - .getClassLoadingStrategy(), null); + final RIBImpl ribImpl = new RIBImpl(this.clusterSingletonServiceProvider, new RibId(RIB_ID), AS_NUMBER, + new BgpId(RIB_ID), null, this.ribExtension, this.dispatcher, this.mappingService.getCodecFactory(), + this.domBroker, ImmutableList.of(this.ipv4tt), pathTables, this.ribExtension.getClassLoadingStrategy(), + null); ribImpl.instantiateServiceInstance(); ribImpl.onGlobalContextUpdated(this.schemaContext); - final BGPPeer bgpPeer = new BGPPeer("peer-test", ribImpl, PeerRole.Ibgp, null); + final BGPPeer bgpPeer = new BGPPeer(LOCAL_IP, ribImpl, PeerRole.Ibgp, null, AFI_SAFIS_ADVERTIZED, + Collections.emptySet()); bgpPeer.instantiateServiceInstance(); final BGPSessionImpl bgpSession = new BGPSessionImpl(bgpPeer, this.speakerListener, this.classicOpen, this.classicOpen.getHoldTimer(), null); bgpSession.setChannelExtMsgCoder(this.classicOpen); @@ -238,15 +242,17 @@ public class SynchronizationAndExceptionTest extends AbstractAddPathTest { @Test public void testUseCase1() throws InterruptedException { - final Map pathTables = ImmutableMap.of(new TablesKey(ipv4tt.getAfi(), ipv4tt.getSafi()), + final Map pathTables = ImmutableMap.of(TABLES_KEY, BasePathSelectionModeFactory.createBestPathSelectionStrategy()); - final RIBImpl ribImpl = new RIBImpl(this.clusterSingletonServiceProvider, new RibId(RIB_ID), AS_NUMBER, new BgpId(RIB_ID), null, this.ribExtension, - this.dispatcher, this.mappingService.getCodecFactory(), this.domBroker, ImmutableList.of(ipv4tt), pathTables, this.ribExtension - .getClassLoadingStrategy(), null); + final RIBImpl ribImpl = new RIBImpl(this.clusterSingletonServiceProvider, new RibId(RIB_ID), AS_NUMBER, + new BgpId(RIB_ID), null, this.ribExtension, this.dispatcher, this.mappingService.getCodecFactory(), + this.domBroker, ImmutableList.of(this.ipv4tt), pathTables, this.ribExtension.getClassLoadingStrategy(), + null); ribImpl.instantiateServiceInstance(); ribImpl.onGlobalContextUpdated(this.schemaContext); - final BGPPeer bgpPeer = new BGPPeer("peer-test", ribImpl, PeerRole.Ibgp, null); + final BGPPeer bgpPeer = new BGPPeer(LOCAL_IP, ribImpl, PeerRole.Ibgp, null, AFI_SAFIS_ADVERTIZED, + Collections.emptySet()); bgpPeer.instantiateServiceInstance(); final BGPSessionImpl bgpSession = new BGPSessionImpl(bgpPeer, this.speakerListener, this.classicOpen, this.classicOpen.getHoldTimer(), null); bgpSession.setChannelExtMsgCoder(this.classicOpen); diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/AbstractConfig.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/AbstractConfig.java index ef025eaed3..2c3d32f11c 100644 --- a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/AbstractConfig.java +++ b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/AbstractConfig.java @@ -48,20 +48,27 @@ import org.opendaylight.protocol.bgp.rib.impl.stats.rib.impl.BGPRenderStats; import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.BgpRib; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.Rib; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.RibId; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.RibKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Ipv4AddressFamily; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily; import org.opendaylight.yangtools.concepts.ListenerRegistration; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.osgi.framework.ServiceRegistration; class AbstractConfig { + static final TablesKey TABLES_KEY = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class); protected static final AsNumber AS = new AsNumber(72L); + protected ClusterSingletonService singletonService; @Mock protected RIB rib; @Mock @@ -84,13 +91,13 @@ class AbstractConfig { protected ListenerRegistration listener; @Mock protected Future future; - protected ClusterSingletonService singletonService; @Mock protected DOMDataWriteTransaction domDW; @Mock private ImportPolicyPeerTracker importPolicyPeerTracker; @Mock private DOMDataTreeChangeService dataTreeChangeService; + protected static final RibId RIB_ID = new RibId("test"); @Before public void setUp() throws Exception { @@ -101,6 +108,9 @@ class AbstractConfig { }).when(this.rib).registerClusterSingletonService(any(ClusterSingletonService.class)); Mockito.doReturn(new LongAdder()).when(this.render).getConfiguredPeerCounter(); Mockito.doReturn(this.render).when(this.rib).getRenderStats(); + Mockito.doReturn(InstanceIdentifier.create(BgpRib.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight + .params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.Rib.class, new RibKey(RIB_ID))).when(this.rib) + .getInstanceIdentifier(); Mockito.doReturn(this.domTx).when(this.rib).createPeerChain(any(TransactionChainListener.class)); Mockito.doReturn(AS).when(this.rib).getLocalAs(); Mockito.doReturn(this.importPolicyPeerTracker).when(this.rib).getImportPolicyPeerTracker(); @@ -126,8 +136,10 @@ class AbstractConfig { Mockito.doReturn(null).when(checkedFuture).checkedGet(); Mockito.doReturn(null).when(checkedFuture).get(); Mockito.doReturn("checkedFuture").when(checkedFuture).toString(); - - Mockito.doNothing().when(this.singletonServiceRegistration).close(); + Mockito.doAnswer(invocationOnMock->{ + this.singletonService.closeServiceInstance(); + return null; + }).when(this.singletonServiceRegistration).close(); Mockito.doReturn(YangInstanceIdentifier.of(Rib.QNAME)).when(this.rib).getYangRibId(); Mockito.doReturn(this.dataTreeChangeService).when(this.rib).getService(); Mockito.doReturn(this.listener).when(this.dataTreeChangeService).registerDataTreeChangeListener(any(), any()); @@ -140,6 +152,7 @@ class AbstractConfig { Mockito.doReturn(java.util.Optional.of(new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class))) .when(this.tableTypeRegistry).getTableType(any()); + Mockito.doReturn(java.util.Optional.of(TABLES_KEY)).when(this.tableTypeRegistry).getTableKey(any()); Mockito.doReturn(Collections.singleton(new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class))) .when(this.rib).getLocalTables(); Mockito.doNothing().when(this.configurationWriter).apply(); diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/AppPeerTest.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/AppPeerTest.java index 3a13a25544..5316345efd 100644 --- a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/AppPeerTest.java +++ b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/AppPeerTest.java @@ -44,12 +44,13 @@ public class AppPeerTest extends AbstractConfig { Mockito.verify(this.rib).getService(); Mockito.verify(this.rib).getRibIServiceGroupIdentifier(); Mockito.verify(this.rib).registerClusterSingletonService(any(ClusterSingletonService.class)); + Mockito.verify(this.rib, times(1)).getLocalTablesKeys(); this.singletonService.instantiateServiceInstance(); Mockito.verify(this.rib, times(2)).getYangRibId(); Mockito.verify(this.configurationWriter).apply(); Mockito.verify(this.rib).getRibSupportContext(); - Mockito.verify(this.rib).getLocalTablesKeys(); + Mockito.verify(this.rib, times(2)).getLocalTablesKeys(); Mockito.verify(this.domTx).newWriteOnlyTransaction(); APP_PEER.close(); @@ -61,8 +62,6 @@ public class AppPeerTest extends AbstractConfig { Mockito.verify(this.rib, times(4)).getService(); Mockito.verify(this.rib, times(2)).getRibIServiceGroupIdentifier(); Mockito.verify(this.rib, times(2)).registerClusterSingletonService(any(ClusterSingletonService.class)); - - this.singletonService.closeServiceInstance(); Mockito.verify(this.listener, times(2)).close(); assertTrue(APP_PEER.containsEqualConfiguration(this.neighbor)); diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpDeployerImplTest.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpDeployerImplTest.java index ff557c4db7..46ecc65199 100644 --- a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpDeployerImplTest.java +++ b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpDeployerImplTest.java @@ -17,6 +17,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType.DELETE; import static org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType.WRITE; +import static org.opendaylight.protocol.bgp.rib.impl.config.AbstractConfig.TABLES_KEY; import static org.opendaylight.protocol.bgp.rib.impl.config.BgpPeerTest.createAddPath; import static org.opendaylight.protocol.bgp.rib.impl.config.BgpPeerTest.createConfig; import static org.opendaylight.protocol.bgp.rib.impl.config.BgpPeerTest.createRR; @@ -112,7 +113,9 @@ public class BgpDeployerImplTest { private static final AsNumber AS = new AsNumber(72L); private static final IpAddress IPADDRESS = new IpAddress(new Ipv4Address("127.0.0.1")); private static final BgpId BGP_ID = new BgpId(IPADDRESS.getIpv4Address()); - private static final BgpTableType TABLE_TYPE = new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class); + private static final BgpTableType TABLE_TYPE = new BgpTableTypeImpl(Ipv4AddressFamily.class, + UnicastSubsequentAddressFamily.class); + private static final short SHORT = 0; @Mock @@ -149,6 +152,7 @@ public class BgpDeployerImplTest { .when(domDataBroker).getSupportedExtensions(); Mockito.doReturn(Optional.of(TABLE_TYPE)).when(this.tableTypeRegistry).getTableType(any()); + Mockito.doReturn(Optional.of(TABLES_KEY)).when(this.tableTypeRegistry).getTableKey(any()); Mockito.doNothing().when(this.registration).unregister(); Mockito.doReturn(this.registration).when(this.bundleContext).registerService(eq(InstanceType.RIB.getServices()), any() , any(Dictionary.class)); @@ -342,7 +346,7 @@ public class BgpDeployerImplTest { verify(this.blueprintContainer).getComponentInstance(eq("bgpPeer")); verifyPrivate(spyDeployer).invoke("initiatePeerInstance", any(InstanceIdentifier.class), any(InstanceIdentifier.class), any(Neighbor.class), any(PeerBean.class), any(BgpDeployer.WriteConfiguration.class)); - verifyPrivate(spyDeployer).invoke("registerPeerInstance", any(Neighbor.class), anyString()); + verifyPrivate(spyDeployer).invoke("registerPeerInstance", any(BgpPeer.class), anyString()); verify(this.bundleContext).registerService(eq(InstanceType.PEER.getServices()), any(BgpPeer.class), any(Dictionary.class)); //change with same peer already existing diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpPeerTest.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpPeerTest.java index 65cb090c56..8660771b56 100644 --- a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpPeerTest.java +++ b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpPeerTest.java @@ -101,6 +101,9 @@ public class BgpPeerTest extends AbstractConfig { } this.bgpPeer.setServiceRegistration(this.serviceRegistration); this.bgpPeer.close(); + Mockito.verify(this.singletonServiceRegistration).close(); + Mockito.verify(this.future).cancel(true); + this.bgpPeer.restart(this.rib, this.tableTypeRegistry); Mockito.verify(this.rib, times(2)).createPeerChain(any()); Mockito.verify(this.rib, times(4)).getLocalAs(); @@ -117,18 +120,17 @@ public class BgpPeerTest extends AbstractConfig { final Neighbor neighborExpected = createNeighborExpected(NEIGHBOR_ADDRESS); assertTrue(this.bgpPeer.containsEqualConfiguration(neighborExpected)); assertFalse(this.bgpPeer.containsEqualConfiguration(createNeighborExpected(new IpAddress(new Ipv4Address("127.0.0.2"))))); - - this.singletonService.closeServiceInstance(); Mockito.verify(this.bgpPeerRegistry).removePeer(any(IpAddress.class)); this.bgpPeer.close(); Mockito.verify(this.singletonServiceRegistration, times(2)).close(); Mockito.verify(this.serviceRegistration).unregister(); - Mockito.verify(this.future).cancel(true); + Mockito.verify(this.future, times(2)).cancel(true); - final Neighbor emptyNeighbor = new NeighborBuilder().setNeighborAddress(NEIGHBOR_ADDRESS).build(); - this.bgpPeer.start(this.rib, emptyNeighbor, this.tableTypeRegistry, this.configurationWriter); - assertTrue(this.bgpPeer.containsEqualConfiguration(emptyNeighbor)); + final Neighbor neighborDiffConfig = new NeighborBuilder().setNeighborAddress(NEIGHBOR_ADDRESS) + .setAfiSafis(createAfiSafi()).build(); + this.bgpPeer.start(this.rib, neighborDiffConfig, this.tableTypeRegistry, this.configurationWriter); + assertTrue(this.bgpPeer.containsEqualConfiguration(neighborDiffConfig)); this.bgpPeer.close(); } diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/OpenConfigMappingUtilTest.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/OpenConfigMappingUtilTest.java index b1e1a715b8..2e854e0dfa 100644 --- a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/OpenConfigMappingUtilTest.java +++ b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/OpenConfigMappingUtilTest.java @@ -76,7 +76,6 @@ import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.re import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.network.instance.protocols.ProtocolKey; import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.policy.types.rev151009.BGP; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber; -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.PortNumber; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType; @@ -130,8 +129,7 @@ public class OpenConfigMappingUtilTest { private static final ClusterIdentifier CLUSTER_IDENTIFIER = new ClusterIdentifier("192.168.1.2"); private static final AsNumber AS = new AsNumber(72L); - private static final IpAddress IPADDRESS = new IpAddress(new Ipv4Address("127.0.0.1")); - private static final BgpId BGP_ID = new BgpId(IPADDRESS.getIpv4Address()); + private static final BgpId BGP_ID = new BgpId(NEIGHBOR_ADDRESS.getIpv4Address()); private static final RibId RIB_ID = new RibId("bgp"); private static final List FAMILIES; private static final List TABLE_TYPES; @@ -440,7 +438,7 @@ public class OpenConfigMappingUtilTest { @Test public void fromBgpPeer() { - final Neighbor result = OpenConfigMappingUtil.fromBgpPeer(FAMILIES, TABLE_TYPES, 30, IPADDRESS, true, null, PORT_NUMBER, 30, AS, PeerRole.Ibgp, null, this.tableTypeRegistry); + final Neighbor result = OpenConfigMappingUtil.fromBgpPeer(FAMILIES, TABLE_TYPES, 30, NEIGHBOR_ADDRESS, true, null, PORT_NUMBER, 30, AS, PeerRole.Ibgp, null, this.tableTypeRegistry); final List afisafis = new ArrayList<>(); afisafis.add(new AfiSafiBuilder().setAfiSafiName(IPV4UNICAST.class) .addAugmentation(AfiSafi1.class, new AfiSafi1Builder().setReceive(true).setSendMax(Shorts.checkedCast(ALL_PATHS)).build()).build()); @@ -449,7 +447,7 @@ public class OpenConfigMappingUtilTest { final Neighbor expected = new NeighborBuilder() .setAfiSafis(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.AfiSafisBuilder().setAfiSafi(afisafis).build()) .setConfig(new ConfigBuilder().setPeerAs(AS).setPeerType(PeerType.INTERNAL).setRouteFlapDamping(false).setSendCommunity(CommunityType.NONE).build()) - .setNeighborAddress(IPADDRESS) + .setNeighborAddress(NEIGHBOR_ADDRESS) .setRouteReflector(new RouteReflectorBuilder().setConfig(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp .neighbor.group.route.reflector.ConfigBuilder().setRouteReflectorClient(false).build()).build()) .setTimers(new TimersBuilder().setConfig(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group @@ -468,7 +466,7 @@ public class OpenConfigMappingUtilTest { final Neighbor result = OpenConfigMappingUtil.fromApplicationPeer(app, BGP_ID); final Neighbor expected = new NeighborBuilder().setConfig(new ConfigBuilder().setDescription(app.getValue()) .addAugmentation(Config2.class, new Config2Builder().setPeerGroup(OpenConfigMappingUtil.APPLICATION_PEER_GROUP_NAME).build()).build()) - .setNeighborAddress(IPADDRESS).build(); + .setNeighborAddress(NEIGHBOR_ADDRESS).build(); assertEquals(expected, result); } } \ No newline at end of file diff --git a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/BGPRenderStatsImplTest.java b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/BGPRenderStatsImplTest.java index e95f5948d9..efb32ed6d7 100644 --- a/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/BGPRenderStatsImplTest.java +++ b/bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/stats/rib/impl/BGPRenderStatsImplTest.java @@ -9,13 +9,19 @@ package org.opendaylight.protocol.bgp.rib.impl.stats.rib.impl; import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; -import java.util.ArrayList; +import java.util.Collections; import java.util.List; -import java.util.concurrent.atomic.LongAdder; +import org.junit.Before; import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.opendaylight.controller.config.api.IdentityAttributeRef; import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpRenderState; import org.opendaylight.controller.config.yang.bgp.rib.impl.LocRibRouteTable; +import org.opendaylight.protocol.bgp.rib.spi.state.BGPRIBState; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.ZeroBasedCounter32; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.RibId; @@ -31,10 +37,20 @@ public class BGPRenderStatsImplTest { private static final ClusterIdentifier CLUSTER_ID = new ClusterIdentifier("192.168.1.2"); private static final AsNumber AS = new AsNumber(0x10L); private static final ZeroBasedCounter32 COUTER = new ZeroBasedCounter32(0L); + private static final ZeroBasedCounter32 COUTER_ONE_ROUTE = new ZeroBasedCounter32(1L); + private final TablesKey tk = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class); + @Mock + private BGPRIBState bgpGlobalState; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } @Test public void getBgpRenderState() throws Exception { - final BGPRenderStatsImpl render = new BGPRenderStatsImpl(BGP_ID, RIB_ID, AS, CLUSTER_ID); + final BGPRenderStatsImpl render = new BGPRenderStatsImpl(BGP_ID, RIB_ID, AS, CLUSTER_ID, this.bgpGlobalState, + Collections.singleton(this.tk)); final BgpRenderState renderStateExpected = new BgpRenderState(); renderStateExpected.setRibId(RIB_ID); @@ -43,20 +59,23 @@ public class BGPRenderStatsImplTest { renderStateExpected.setLocalAs(AS); renderStateExpected.setConfiguredPeerCount(COUTER); renderStateExpected.setConnectedPeerCount(COUTER); - final List locRibRouteTableList = new ArrayList<>(); + final LocRibRouteTable locRibTable = new LocRibRouteTable(); + locRibTable.setAfi(new IdentityAttributeRef(Ipv4AddressFamily.QNAME.toString())); + locRibTable.setSafi(new IdentityAttributeRef(UnicastSubsequentAddressFamily.QNAME.toString())); + locRibTable.setRoutesCount(COUTER); + final List locRibRouteTableList = Collections.singletonList(locRibTable); renderStateExpected.setLocRibRouteTable(locRibRouteTableList); renderStateExpected.setLocRibRoutesCount(COUTER); + doReturn(0L).when(this.bgpGlobalState).getPathCount(eq(this.tk)); assertEquals(renderStateExpected, render.getBgpRenderState()); - LongAdder counter = render.getLocRibRouteCounter().init(new TablesKey(Ipv4AddressFamily.class, - UnicastSubsequentAddressFamily.class)); - counter.increment(); - assertEquals(1L, counter.longValue()); - counter = render.getConfiguredPeerCounter(); - counter.increment(); - assertEquals(1L, counter.longValue()); - counter = render.getConnectedPeerCounter(); - counter.increment(); - assertEquals(1L, counter.longValue()); + doReturn(1L).when(this.bgpGlobalState).getPathCount(eq(this.tk)); + locRibTable.setRoutesCount(COUTER_ONE_ROUTE); + renderStateExpected.setLocRibRoutesCount(COUTER_ONE_ROUTE); + assertEquals(renderStateExpected, render.getBgpRenderState()); + render.getConfiguredPeerCounter().increment(); + assertEquals(1L, render.getConfiguredPeerCounter().longValue()); + render.getConnectedPeerCounter().increment(); + assertEquals(1L, render.getConnectedPeerCounter().longValue()); } } \ No newline at end of file diff --git a/bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/state/BGPPeerMessagesState.java b/bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/state/BGPPeerMessagesState.java new file mode 100644 index 0000000000..a351d4faa8 --- /dev/null +++ b/bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/state/BGPPeerMessagesState.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ + +package org.opendaylight.protocol.bgp.rib.spi.state; + +/** + * BGP Peer Messages Operational State + */ +public interface BGPPeerMessagesState { + /** + * Update Messages Sent count + * + * @return count + */ + long getUpdateMessagesSentCount(); + + /** + * Notification Messages Sent count + * + * @return count + */ + long getNotificationMessagesSentCount(); + + /** + * Update Messages Received count + * + * @return count + */ + long getUpdateMessagesReceivedCount(); + + /** + * Notification Update Messages Received count + * + * @return count + */ + long getNotificationMessagesReceivedCount(); +} diff --git a/bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/state/BGPPeerState.java b/bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/state/BGPPeerState.java index 78b6774eb4..05c0327097 100644 --- a/bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/state/BGPPeerState.java +++ b/bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/state/BGPPeerState.java @@ -78,6 +78,12 @@ public interface BGPPeerState extends RibReference { */ @Nullable BGPSessionState getBGPSessionState(); + /** + * BGP Message Operational State + * @return BGPPeerMessagesState + */ + @Nullable BGPPeerMessagesState getBGPPeerMessagesState(); + /** * BGP Operation Timers State * @return BGPTimersState diff --git a/bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/state/BGPSessionState.java b/bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/state/BGPSessionState.java index bdae08b7db..fd0c2d39c4 100644 --- a/bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/state/BGPSessionState.java +++ b/bgp/rib-spi/src/main/java/org/opendaylight/protocol/bgp/rib/spi/state/BGPSessionState.java @@ -55,32 +55,4 @@ public interface BGPSessionState { * @return true if supported */ boolean isRouterRefreshCapabilitySupported(); - - /** - * Update Messages Sent count - * - * @return count - */ - long getUpdateMessagesSentCount(); - - /** - * Notification Messages Sent count - * - * @return count - */ - long getNotificationMessagesSentCount(); - - /** - * Update Messages Received count - * - * @return count - */ - long getUpdateMessagesReceivedCount(); - - /** - * Notification Update Messages Received count - * - * @return count - */ - long getNotificationMessagesReceivedCount(); } diff --git a/bgp/testtool/src/main/java/org/opendaylight/protocol/bgp/testtool/TestingListener.java b/bgp/testtool/src/main/java/org/opendaylight/protocol/bgp/testtool/TestingListener.java index c022aad549..8ad753feb4 100644 --- a/bgp/testtool/src/main/java/org/opendaylight/protocol/bgp/testtool/TestingListener.java +++ b/bgp/testtool/src/main/java/org/opendaylight/protocol/bgp/testtool/TestingListener.java @@ -8,6 +8,7 @@ package org.opendaylight.protocol.bgp.testtool; import java.util.List; +import java.util.concurrent.atomic.LongAdder; import org.opendaylight.protocol.bgp.rib.impl.BGPSessionImpl; import org.opendaylight.protocol.bgp.rib.spi.BGPSession; import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener; @@ -26,7 +27,7 @@ final class TestingListener implements BGPSessionListener { private final int nPrefixes; private final List extCom; private final boolean multiPathSupport; - private int messageCounter = 0; + private LongAdder messageCounter = new LongAdder(); TestingListener(final int nPrefixes, final List extCom, final boolean multiPathSupport) { this.nPrefixes = nPrefixes; @@ -65,7 +66,7 @@ final class TestingListener implements BGPSessionListener { @Override public void onMessage(final BGPSession session, final Notification message) { if (message instanceof Update) { - messageCounter++; + this.messageCounter.increment(); } LOG.debug("Message received: {}", message.toString()); } @@ -76,6 +77,6 @@ final class TestingListener implements BGPSessionListener { } void printCount(final String localAddress) { - LOG.info("Peer {} received {} update messages.", localAddress, messageCounter); + LOG.info("Peer {} received {} update messages.", localAddress, this.messageCounter.longValue()); } } -- 2.36.6