*/
/**
* Generated file
-
+ * <p>
* Generated from: yang module name: bgp-rib-impl yang module local name: rib-impl
* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
* Generated at: Wed Nov 06 13:02:32 CET 2013
- *
+ * <p>
* Do not modify this file unless it is present under src/main directory
*/
package org.opendaylight.controller.config.yang.bgp.rib.impl;
-import com.google.common.reflect.AbstractInvocationHandler;
-import com.google.common.reflect.Reflection;
-import java.lang.reflect.Method;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Collectors;
-import org.opendaylight.controller.config.api.JmxAttributeValidationException;
-import org.opendaylight.controller.config.api.osgi.WaitingServiceTracker;
-import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode;
-import org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil;
-import org.opendaylight.protocol.bgp.rib.impl.spi.BGPBestPathSelection;
-import org.opendaylight.protocol.bgp.rib.impl.spi.BgpDeployer;
-import org.opendaylight.protocol.bgp.rib.impl.spi.InstanceType;
-import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
-import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.Bgp;
-import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.top.bgp.Global;
-import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.network.instance.Protocols;
-import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.network.instance.rev151018.network.instance.top.network.instances.network.instance.protocols.Protocol;
-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.opendaylight.params.xml.ns.yang.bgp.openconfig.extensions.rev160614.Protocol1;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-
/**
*
*/
@Deprecated
public final class RIBImplModule extends org.opendaylight.controller.config.yang.bgp.rib.impl.AbstractRIBImplModule {
- private static final String IS_NOT_SET = "is not set.";
- private BundleContext bundleContext;
-
public RIBImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier name,
final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
super(name, dependencyResolver);
@Override
public void customValidation() {
- JmxAttributeValidationException.checkNotNull(getExtensions(), IS_NOT_SET, extensionsJmxAttribute);
- JmxAttributeValidationException.checkNotNull(getRibId(), IS_NOT_SET, ribIdJmxAttribute);
- JmxAttributeValidationException.checkNotNull(getLocalAs(), IS_NOT_SET, localAsJmxAttribute);
- JmxAttributeValidationException.checkNotNull(getBgpRibId(), IS_NOT_SET, bgpRibIdJmxAttribute);
- JmxAttributeValidationException.checkNotNull(getLocalTable(), IS_NOT_SET, localTableJmxAttribute);
}
@Override
public java.lang.AutoCloseable createInstance() {
- final WaitingServiceTracker<BgpDeployer> bgpDeployerTracker =
- WaitingServiceTracker.create(BgpDeployer.class, this.bundleContext);
- final BgpDeployer bgpDeployer = bgpDeployerTracker.waitForService(WaitingServiceTracker.FIVE_MINUTES);
- //map configuration to OpenConfig BGP
- final Global global = OpenConfigMappingUtil.fromRib(getBgpRibId(), getClusterId(), getRibId(),
- new AsNumber(getLocalAs()), getLocalTableDependency(),
- mapBestPathSelectionStrategyByFamily(getRibPathSelectionModeDependency()), bgpDeployer.getTableTypeRegistry());
- final InstanceIdentifier<Bgp> bgpIID = bgpDeployer.getInstanceIdentifier().child(Protocols.class)
- .child(Protocol.class, new ProtocolKey(BGP.class, getRibId().getValue())).augmentation(Protocol1.class)
- .child(Bgp.class);
- bgpDeployer.onGlobalModified(bgpIID, global, () -> bgpDeployer.writeConfiguration(global, bgpIID.child(Global.class)));
-
- //get rib instance service, use filter
- final WaitingServiceTracker<RIB> ribTracker = WaitingServiceTracker.create(RIB.class,
- this.bundleContext, "(" + InstanceType.RIB.getBeanName() + "=" + getRibId().getValue() + ")");
- final RIB rib = ribTracker.waitForService(WaitingServiceTracker.FIVE_MINUTES);
- final RIBImplRuntimeRegistration register = getRootRuntimeBeanRegistratorWrapper().register(rib.getRenderStats());
-
- return Reflection.newProxy(AutoCloseableRIB.class, new AbstractInvocationHandler() {
- @Override
- protected Object handleInvocation(final Object proxy, final Method method, final Object[] args) throws Throwable {
- if (method.getName().equals("close")) {
- bgpDeployer.onGlobalRemoved(bgpIID);
- register.close();
- bgpDeployerTracker.close();
- ribTracker.close();
- return null;
- } else {
- return method.invoke(rib, args);
- }
- }
- });
- }
-
- public void setBundleContext(final BundleContext bundleContext) {
- this.bundleContext = bundleContext;
- }
-
- private static Map<TablesKey, PathSelectionMode> mapBestPathSelectionStrategyByFamily(final List<BGPBestPathSelection> bestPathSelectionDependency) {
- return Collections.unmodifiableMap(bestPathSelectionDependency.stream().collect(
- Collectors.toMap(st -> new TablesKey(st.getAfi(), st.getSafi()), BGPBestPathSelection::getStrategy)));
+ //NOP
+ return null;
}
-
- private interface AutoCloseableRIB extends RIB, AutoCloseable {
- }
-
-
}
*/
/**
* Generated file
-
+ * <p>
* Generated from: yang module name: bgp-rib-impl yang module local name: rib-impl
* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
* Generated at: Wed Nov 06 13:02:32 CET 2013
- *
+ * <p>
* Do not modify this file unless it is present under src/main directory
*/
package org.opendaylight.controller.config.yang.bgp.rib.impl;
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.spi.Module;
-import org.osgi.framework.BundleContext;
-
/**
*
*/
@Deprecated
public class RIBImplModuleFactory extends org.opendaylight.controller.config.yang.bgp.rib.impl.AbstractRIBImplModuleFactory {
-
- @Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
- final RIBImplModule module = (RIBImplModule) super.createModule(instanceName, dependencyResolver, bundleContext);
- module.setBundleContext(bundleContext);
- return module;
- }
-
- @Override
- public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
- final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
- final RIBImplModule module = (RIBImplModule) super.createModule(instanceName, dependencyResolver, old, bundleContext);
- module.setBundleContext(bundleContext);
- return module;
- }
-
}
private static final Logger LOG = LoggerFactory.getLogger(AdjRibOutListener.class);
- static final QName PREFIX_QNAME = QName.create(Ipv4Route.QNAME, "prefix").intern();
- private final YangInstanceIdentifier.NodeIdentifier routeKeyLeaf = new YangInstanceIdentifier.NodeIdentifier(PREFIX_QNAME);
+ private static final QName PREFIX_QNAME = QName.create(Ipv4Route.QNAME, "prefix").intern();
+ private final YangInstanceIdentifier.NodeIdentifier routeKeyLeaf = new YangInstanceIdentifier
+ .NodeIdentifier(PREFIX_QNAME);
private final ChannelOutputLimiter session;
private final Codecs codecs;
private final RIBSupport support;
private final boolean mpSupport;
private final ListenerRegistration<AdjRibOutListener> 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,
- final ChannelOutputLimiter session, final boolean mpSupport, final LongAdder routeCounter) {
+ final CodecsRegistry registry, final RIBSupport support, final DOMDataTreeChangeService service,
+ final ChannelOutputLimiter session, final boolean mpSupport) {
this.session = requireNonNull(session);
this.support = requireNonNull(support);
this.codecs = registry.getCodecs(this.support);
this.mpSupport = mpSupport;
- final YangInstanceIdentifier adjRibOutId = ribId.node(Peer.QNAME).node(IdentifierUtils.domPeerId(peerId)).node(AdjRibOut.QNAME).node(Tables.QNAME).node(RibSupportUtils.toYangTablesKey(tablesKey));
- this.registerDataTreeChangeListener = service.registerDataTreeChangeListener(new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, adjRibOutId), this);
- this.routeCounter = routeCounter;
+ final YangInstanceIdentifier adjRibOutId = ribId.node(Peer.QNAME).node(IdentifierUtils.domPeerId(peerId))
+ .node(AdjRibOut.QNAME).node(Tables.QNAME).node(RibSupportUtils.toYangTablesKey(tablesKey));
+ this.registerDataTreeChangeListener = service.registerDataTreeChangeListener(
+ new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, adjRibOutId), this);
}
- static AdjRibOutListener create(@Nonnull final PeerId peerId, @Nonnull final TablesKey tablesKey, @Nonnull final YangInstanceIdentifier ribId,
- @Nonnull final CodecsRegistry registry, @Nonnull final RIBSupport support, @Nonnull final DOMDataTreeChangeService service,
- @Nonnull final ChannelOutputLimiter session, final boolean mpSupport, @Nonnull final LongAdder routeCounter
- ) {
- return new AdjRibOutListener(peerId, tablesKey, ribId, registry, support, service, session, mpSupport, routeCounter);
+ static AdjRibOutListener create(
+ @Nonnull final PeerId peerId,
+ @Nonnull final TablesKey tablesKey,
+ @Nonnull final YangInstanceIdentifier ribId,
+ @Nonnull final CodecsRegistry registry,
+ @Nonnull final RIBSupport support,
+ @Nonnull final DOMDataTreeChangeService service,
+ @Nonnull final ChannelOutputLimiter session,
+ final boolean mpSupport) {
+ return new AdjRibOutListener(peerId, tablesKey, ribId, registry, support, service, session, mpSupport);
}
@Override
private void processRouteChange(final DataTreeCandidateNode route) {
final Update update;
switch (route.getModificationType()) {
- case UNMODIFIED:
- LOG.debug("Skipping unmodified route {}", route.getIdentifier());
- return;
- case DELETE:
- case DISAPPEARED:
- // FIXME: we can batch deletions into a single batch
- update = withdraw((MapEntryNode) route.getDataBefore().get());
- LOG.debug("Withdrawing routes {}", update);
- break;
- case APPEARED:
- case SUBTREE_MODIFIED:
- case WRITE:
- update = advertise((MapEntryNode) route.getDataAfter().get());
- LOG.debug("Advertising routes {}", update);
- break;
- default:
- LOG.warn("Ignoring unhandled modification type {}", route.getModificationType());
- return;
+ case UNMODIFIED:
+ LOG.debug("Skipping unmodified route {}", route.getIdentifier());
+ return;
+ case DELETE:
+ case DISAPPEARED:
+ // FIXME: we can batch deletions into a single batch
+ update = withdraw((MapEntryNode) route.getDataBefore().get());
+ LOG.debug("Withdrawing routes {}", update);
+ break;
+ case APPEARED:
+ case SUBTREE_MODIFIED:
+ case WRITE:
+ update = advertise((MapEntryNode) route.getDataAfter().get());
+ LOG.debug("Advertising routes {}", update);
+ break;
+ default:
+ LOG.warn("Ignoring unhandled modification type {}", route.getModificationType());
+ return;
}
this.session.write(update);
}
if (LOG.isDebugEnabled()) {
LOG.debug("AdjRibOut parsing route {}", NormalizedNodes.toStringTree(route));
}
- final ContainerNode advertisedAttrs = (ContainerNode) NormalizedNodes.findNode(route, this.support.routeAttributesIdentifier()).orNull();
+ final ContainerNode advertisedAttrs = (ContainerNode) NormalizedNodes.findNode(route,
+ this.support.routeAttributesIdentifier()).orNull();
return this.codecs.deserializeAttributes(advertisedAttrs);
}
private Update withdraw(final MapEntryNode route) {
- this.routeCounter.decrement();
if (!this.mpSupport) {
return buildUpdate(Collections.emptyList(), Collections.singleton(route), routeAttributes(route));
}
}
private Update advertise(final MapEntryNode route) {
- this.routeCounter.increment();
this.prefixesSentCounter.increment();
if (!this.mpSupport) {
return buildUpdate(Collections.singleton(route), Collections.emptyList(), routeAttributes(route));
return this.support.buildUpdate(Collections.singleton(route), Collections.emptyList(), routeAttributes(route));
}
- private Update buildUpdate(@Nonnull final Collection<MapEntryNode> advertised, @Nonnull final Collection<MapEntryNode> withdrawn, @Nonnull final Attributes attr) {
- final UpdateBuilder ub = new UpdateBuilder()
- .setWithdrawnRoutes(new WithdrawnRoutesBuilder().setWithdrawnRoutes(extractPrefixes(withdrawn)).build())
- .setNlri(new NlriBuilder().setNlri(extractPrefixes(advertised)).build());
+ private Update buildUpdate(
+ @Nonnull final Collection<MapEntryNode> advertised,
+ @Nonnull final Collection<MapEntryNode> withdrawn,
+ @Nonnull final Attributes attr) {
+ final UpdateBuilder ub = new UpdateBuilder().setWithdrawnRoutes(
+ new WithdrawnRoutesBuilder().setWithdrawnRoutes(extractPrefixes(withdrawn)).build())
+ .setNlri(new NlriBuilder().setNlri(extractPrefixes(advertised)).build());
ub.setAttributes(attr);
return ub.build();
}
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;
* peer needs to have a BGP-ID that is configurable.
*/
public class ApplicationPeer extends BGPPeerStateImpl implements org.opendaylight.protocol.bgp.rib.spi.Peer,
- ClusteredDOMDataTreeChangeListener, TransactionChainListener {
+ ClusteredDOMDataTreeChangeListener, TransactionChainListener {
private static final Logger LOG = LoggerFactory.getLogger(ApplicationPeer.class);
}
public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address ipAddress, final RIB rib) {
- super(rib.getInstanceIdentifier(), "application-peers", new IpAddress(ipAddress), rib.getLocalTablesKeys(),
- Collections.emptySet());
+ super(rib.getInstanceIdentifier(), "application-peers", new IpAddress(ipAddress),
+ rib.getLocalTablesKeys(), Collections.emptySet());
this.name = applicationRibId.getValue();
final RIB targetRib = requireNonNull(rib);
this.rawIdentifier = InetAddresses.forString(ipAddress.getValue()).getAddress();
}
public synchronized void instantiateServiceInstance(final DOMDataTreeChangeService dataTreeChangeService,
- final DOMDataTreeIdentifier appPeerDOMId) {
+ final DOMDataTreeIdentifier appPeerDOMId) {
this.chain = this.rib.createPeerChain(this);
this.writerChain = this.rib.createPeerChain(this);
});
setAdvertizedGracefulRestartTableTypes(Collections.emptyList());
- this.adjRibInWriter = AdjRibInWriter.create(this.rib.getYangRibId(), PeerRole.Internal, simpleRoutingPolicy, this.writerChain);
+ this.adjRibInWriter = AdjRibInWriter.create(this.rib.getYangRibId(), PeerRole.Internal, simpleRoutingPolicy,
+ this.writerChain);
final RIBSupportContextRegistry context = this.rib.getRibSupportContext();
final RegisterAppPeerListener registerAppPeerListener = () -> {
synchronized (this) {
- if(this.chain != null) {
+ if (this.chain != null) {
this.registration = dataTreeChangeService.registerDataTreeChangeListener(appPeerDOMId, this);
}
}
};
this.adjRibInWriter = this.adjRibInWriter.transform(peerId, context, localTables, Collections.emptyMap(),
- registerAppPeerListener);
- 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,
- peerStats.getAdjRibInRouteCounters(), localTables);
+ registerAppPeerListener);
+ this.effectiveRibInWriter = EffectiveRibInWriter
+ .create(this.rib.getService(), this.rib.createPeerChain(this), this.peerIId,
+ this.rib.getImportPolicyPeerTracker(), context, PeerRole.Internal,
+ localTables);
this.bgpSessionState.registerMessagesCounter(this);
}
*/
@Override
public synchronized void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
- if(this.chain == null) {
+ if (this.chain == null) {
LOG.trace("Skipping data changed called to Application Peer. Change : {}", changes);
return;
}
LOG.debug("Modification Type {}", tc.getRootNode().getModificationType());
final YangInstanceIdentifier path = tc.getRootPath();
final PathArgument lastArg = path.getLastPathArgument();
- Verify.verify(lastArg instanceof NodeIdentifierWithPredicates, "Unexpected type %s in path %s", lastArg.getClass(), path);
+ Verify.verify(lastArg instanceof NodeIdentifierWithPredicates,
+ "Unexpected type %s in path %s", lastArg.getClass(), path);
final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
if (!this.supportedTables.contains(tableKey)) {
LOG.trace("Skipping received data change for non supported family {}.", tableKey);
final PathArgument childIdentifier = child.getIdentifier();
final YangInstanceIdentifier tableId = this.adjRibsInId.node(tableKey).node(childIdentifier);
switch (child.getModificationType()) {
- case DELETE:
- LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
- tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
- break;
- case UNMODIFIED:
- // No-op
- break;
- case SUBTREE_MODIFIED:
- if (EffectiveRibInWriter.TABLE_ROUTES.equals(childIdentifier)) {
- processRoutesTable(child, tableId, tx, tableId);
+ case DELETE:
+ LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
+ tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
+ break;
+ case UNMODIFIED:
+ // No-op
+ break;
+ case SUBTREE_MODIFIED:
+ if (EffectiveRibInWriter.TABLE_ROUTES.equals(childIdentifier)) {
+ processRoutesTable(child, tableId, tx, tableId);
+ break;
+ }
+ case WRITE:
+ if (child.getDataAfter().isPresent()) {
+ final NormalizedNode<?, ?> dataAfter = child.getDataAfter().get();
+ LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
+ LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
+ tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
+ }
+ break;
+ default:
break;
- }
- case WRITE:
- if (child.getDataAfter().isPresent()) {
- final NormalizedNode<?,?> dataAfter = child.getDataAfter().get();
- LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
- LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
- tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
- }
- break;
- default:
- break;
}
}
}
/**
* Applies modification under table routes based on modification type instead of only put. BUG 4438
+ *
* @param node
* @param identifier
* @param tx
* @param routeTableIdentifier
*/
- private synchronized void processRoutesTable(final DataTreeCandidateNode node, final YangInstanceIdentifier identifier,
- final DOMDataWriteTransaction tx, final YangInstanceIdentifier routeTableIdentifier) {
+ private synchronized void processRoutesTable(final DataTreeCandidateNode node,
+ final YangInstanceIdentifier identifier, final DOMDataWriteTransaction tx,
+ final YangInstanceIdentifier routeTableIdentifier) {
for (final DataTreeCandidateNode child : node.getChildNodes()) {
final YangInstanceIdentifier childIdentifier = identifier.node(child.getIdentifier());
switch (child.getModificationType()) {
- case DELETE:
- LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
- tx.delete(LogicalDatastoreType.OPERATIONAL, childIdentifier);
- break;
- case UNMODIFIED:
- // No-op
- break;
- case SUBTREE_MODIFIED:
- //For be ables to use DELETE when we remove specific routes as we do when we remove the whole routes,
- // we need to go deeper three levels
- if (!routeTableIdentifier.equals(childIdentifier.getParent().getParent().getParent())) {
- processRoutesTable(child, childIdentifier, tx, routeTableIdentifier);
+ case DELETE:
+ LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
+ tx.delete(LogicalDatastoreType.OPERATIONAL, childIdentifier);
+ break;
+ case UNMODIFIED:
+ // No-op
+ break;
+ case SUBTREE_MODIFIED:
+ //For be ables to use DELETE when we remove specific routes as we do when we remove the whole routes,
+ // we need to go deeper three levels
+ if (!routeTableIdentifier.equals(childIdentifier.getParent().getParent().getParent())) {
+ processRoutesTable(child, childIdentifier, tx, routeTableIdentifier);
+ break;
+ }
+ case WRITE:
+ if (child.getDataAfter().isPresent()) {
+ final NormalizedNode<?, ?> dataAfter = child.getDataAfter().get();
+ LOG.trace("App peer -> AdjRibsIn path : {}", childIdentifier);
+ LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
+ tx.put(LogicalDatastoreType.OPERATIONAL, childIdentifier, dataAfter);
+ }
+ break;
+ default:
break;
- }
- case WRITE:
- if (child.getDataAfter().isPresent()) {
- final NormalizedNode<?,?> dataAfter = child.getDataAfter().get();
- LOG.trace("App peer -> AdjRibsIn path : {}", childIdentifier);
- LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
- tx.put(LogicalDatastoreType.OPERATIONAL, childIdentifier, dataAfter);
- }
- break;
- default:
- break;
}
}
}
final ListenableFuture<Void> future;
if (this.adjRibInWriter != null) {
future = this.adjRibInWriter.removePeer();
- }else {
+ } else {
future = Futures.immediateFuture(null);
}
if (this.chain != null) {
@Override
public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
- final AsyncTransaction<?, ?> transaction, final Throwable cause) {
+ final AsyncTransaction<?, ?> transaction, final Throwable cause) {
LOG.error("Transaction chain {} failed.", transaction != null ? transaction.getIdentifier() : null, cause);
}
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;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.BGPPeerRuntimeRegistrator;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpPeerState;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
import org.opendaylight.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;
import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
* Class representing a peer. We have a single instance for each peer, which provides translation from BGP events into
* RIB actions.
*/
-public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Peer, BGPPeerRuntimeMXBean,
- TransactionChainListener {
+public class BGPPeer extends BGPPeerStateImpl implements BGPSessionListener, Peer, TransactionChainListener {
private static final Logger LOG = LoggerFactory.getLogger(BGPPeer.class);
@GuardedBy("this")
private final RIB rib;
private final String name;
- private BGPPeerRuntimeRegistrator registrator;
private BGPPeerRuntimeRegistration runtimeReg;
private final Map<TablesKey, AdjRibOutListener> adjRibOutListenerSet = new HashMap<>();
private final RpcProviderRegistry rpcRegistry;
private RoutedRpcRegistration<BgpPeerRpcService> rpcRegistration;
private final PeerRole peerRole;
private final Optional<SimpleRoutingPolicy> simpleRoutingPolicy;
- private final BGPPeerStats peerStats;
private YangInstanceIdentifier peerIId;
private final Set<AbstractRegistration> tableRegistration = new HashSet<>();
public BGPPeer(final String name, final RIB rib, final PeerRole role, final SimpleRoutingPolicy peerStatus,
- final RpcProviderRegistry rpcRegistry,
- @Nonnull final Set<TablesKey> afiSafisAdvertized,
- @Nonnull final Set<TablesKey> afiSafisGracefulAdvertized) {
+ final RpcProviderRegistry rpcRegistry,
+ @Nonnull final Set<TablesKey> afiSafisAdvertized,
+ @Nonnull final Set<TablesKey> afiSafisGracefulAdvertized) {
//FIXME BUG-6971 Once Peer Group is implemented, pass it
super(rib.getInstanceIdentifier(), null, new IpAddress(new Ipv4Address(name)), afiSafisAdvertized,
- afiSafisGracefulAdvertized);
+ afiSafisGracefulAdvertized);
this.peerRole = role;
this.simpleRoutingPolicy = Optional.ofNullable(peerStatus);
this.rib = requireNonNull(rib);
this.name = name;
this.rpcRegistry = rpcRegistry;
- 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, @Nonnull final Set<TablesKey> afiSafisAdvertized,
- @Nonnull final Set<TablesKey> afiSafisGracefulAdvertized) {
+ final RpcProviderRegistry rpcRegistry, @Nonnull final Set<TablesKey> afiSafisAdvertized,
+ @Nonnull final Set<TablesKey> 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(this.rib.getYangRibId(), this.peerRole, this.simpleRoutingPolicy, this.chain);
}
if (this.peerRole == PeerRole.Ibgp && (attrs == null || attrs.getLocalPref() == null)) {
throw new BGPDocumentedException(BGPError.MANDATORY_ATTR_MISSING_MSG + "LOCAL_PREF",
BGPError.WELL_KNOWN_ATTR_MISSING,
- new byte[] { LocalPreferenceAttributeParser.TYPE });
+ new byte[]{LocalPreferenceAttributeParser.TYPE});
}
}
}
}
final MpReachNlriBuilder b = new MpReachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(
UnicastSubsequentAddressFamily.class).setAdvertizedRoutes(
- new AdvertizedRoutesBuilder().setDestinationType(
- new DestinationIpv4CaseBuilder().setDestinationIpv4(
- new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build());
+ new AdvertizedRoutesBuilder().setDestinationType(
+ new DestinationIpv4CaseBuilder().setDestinationIpv4(
+ new DestinationIpv4Builder().setIpv4Prefixes(prefixes).build()).build()).build());
if (message.getAttributes() != null) {
b.setCNextHop(message.getAttributes().getCNextHop());
}
/**
* Create MPUnreach for the prefixes to be handled in the same way as linkstate routes
*
- * @param message Update message containing withdrawn routes
+ * @param message Update message containing withdrawn routes
* @param isAnyNlriAnnounced
* @return MpUnreachNlri with prefixes from the withdrawn routes field
*/
final List<Ipv4Prefixes> prefixes = new ArrayList<>();
for (final Ipv4Prefix p : message.getWithdrawnRoutes().getWithdrawnRoutes()) {
boolean nlriAnounced = false;
- if(isAnyNlriAnnounced) {
+ if (isAnyNlriAnnounced) {
nlriAnounced = message.getNlri().getNlri().contains(p);
}
- if(!nlriAnounced) {
+ if (!nlriAnounced) {
prefixes.add(new Ipv4PrefixesBuilder().setPrefix(p).build());
}
}
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()));
+ .map(t -> new TablesKey(t.getAfi(), t.getSafi())).collect(Collectors.toList()));
final boolean announceNone = isAnnounceNone(this.simpleRoutingPolicy);
final Map<TablesKey, SendReceive> 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)
- .node(IdentifierUtils.domPeerId(peerId));
+ .node(IdentifierUtils.domPeerId(peerId));
- if(!announceNone) {
+ if (!announceNone) {
createAdjRibOutListener(peerId);
}
this.tables.forEach(tablesKey -> {
final ExportPolicyPeerTracker exportTracker = this.rib.getExportPolicyPeerTracker(tablesKey);
if (exportTracker != null) {
this.tableRegistration.add(exportTracker.registerPeer(peerId, addPathTableMaps.get(tablesKey), this.peerIId, this.peerRole,
- this.simpleRoutingPolicy));
+ this.simpleRoutingPolicy));
}
});
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.getAdjRibInRouteCounters(), this.tables);
+ 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.tables);
registerPrefixesCounters(this.effRibInWriter, this.effRibInWriter);
}
this.ribWriter = this.ribWriter.transform(peerId, this.rib.getRibSupportContext(), this.tables, addPathTableMaps);
- // register BGP Peer stats
- this.peerStats.getSessionEstablishedCounter().increment();
- if (this.registrator != null) {
- this.runtimeReg = this.registrator.register(this);
- }
-
if (this.rpcRegistry != null) {
this.rpcRegistration = this.rpcRegistry.addRoutedRpcImplementation(BgpPeerRpcService.class,
new BgpPeerRpc(this, session, this.tables));
this.rib.getInstanceIdentifier().child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer.class, new PeerKey(peerId));
this.rpcRegistration.registerPath(PeerContext.class, path);
}
-
- this.rib.getRenderStats().getConnectedPeerCounter().increment();
}
private void createAdjRibOutListener(final PeerId peerId) {
- this.tables.forEach(key->createAdjRibOutListener(peerId, key, true));
+ this.tables.forEach(key -> createAdjRibOutListener(peerId, key, true));
}
//try to add a support for old-school BGP-4, if peer did not advertise IPv4-Unicast MP capability
if (context != null && this.session instanceof BGPSessionImpl) {
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.rib.getYangRibId(), this.rib.getCodecsRegistry(), context.getRibSupport(),
+ this.rib.getService(), limiter, mpSupport);
this.adjRibOutListenerSet.put(key, adjRibOut);
registerPrefixesSentCounter(key, adjRibOut);
}
@Override
public void onSessionDown(final BGPSession session, final Exception e) {
- if(e.getMessage().equals(BGPSessionImpl.END_OF_INPUT)) {
+ if (e.getMessage().equals(BGPSessionImpl.END_OF_INPUT)) {
LOG.info("Session with peer {} went down", this.name);
} else {
LOG.info("Session with peer {} went down", this.name, e);
LOG.warn("Error closing session with peer", e);
}
this.session = null;
-
- this.rib.getRenderStats().getConnectedPeerCounter().decrement();
}
}
return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
}
- @Override
- public void resetSession() {
- releaseConnection();
- }
-
- @Override
- public void resetStats() {
- if (this.session instanceof BGPSessionStats) {
- ((BGPSessionStats) this.session).resetBgpSessionStats();
- }
- }
-
- @Override
- public BgpSessionState getBgpSessionState() {
- if (this.session instanceof BGPSessionStats) {
- return ((BGPSessionStats) this.session).getBgpSessionState();
- }
- return new BgpSessionState();
- }
-
- @Override
- public synchronized BgpPeerState getBgpPeerState() {
- return this.peerStats.getBgpPeerState();
- }
-
@Override
public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
LOG.error("Transaction chain failed.", cause);
private static Map<TablesKey, SendReceive> mapTableTypesFamilies(final List<AddressFamilies> addPathTablesType) {
return ImmutableMap.copyOf(addPathTablesType.stream().collect(Collectors.toMap(af -> new TablesKey(af.getAfi(), af.getSafi()),
- BgpAddPathTableType::getSendReceive)));
+ BgpAddPathTableType::getSendReceive)));
}
@Override
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
-import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.annotation.concurrent.GuardedBy;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
import org.opendaylight.protocol.bgp.parser.BGPError;
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.slf4j.LoggerFactory;
@VisibleForTesting
-public class BGPSessionImpl extends SimpleChannelInboundHandler<Notification> implements BGPSession, BGPSessionStats,
- BGPSessionStateProvider, AutoCloseable {
+public class BGPSessionImpl extends SimpleChannelInboundHandler<Notification> implements BGPSession,
+ BGPSessionStateProvider, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
private final BGPPeerRegistry peerRegistry;
private final ChannelOutputLimiter limiter;
private final BGPSessionStateImpl sessionState;
-
- private BGPSessionStatsImpl sessionStats;
private boolean terminationReasonNotified;
public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen,
- final BGPSessionPreferences localPreferences, final BGPPeerRegistry peerRegistry) {
+ 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);
}
public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen,
- final int localHoldTimer, final BGPPeerRegistry peerRegistry) {
+ final int localHoldTimer, final BGPPeerRegistry peerRegistry) {
this.listener = requireNonNull(listener);
this.channel = requireNonNull(channel);
this.limiter = new ChannelOutputLimiter(this);
for (final BgpParameters param : remoteOpen.getBgpParameters()) {
for (final OptionalCapabilities optCapa : param.getOptionalCapabilities()) {
final CParameters cParam = optCapa.getCParameters();
- if ( cParam.getAugmentation(CParameters1.class) == null) {
+ if (cParam.getAugmentation(CParameters1.class) == null) {
continue;
}
- if(cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability() != null) {
+ if (cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability() != null) {
final MultiprotocolCapability multi = cParam.getAugmentation(CParameters1.class).getMultiprotocolCapability();
final TablesKey tt = new TablesKey(multi.getAfi(), multi.getSafi());
LOG.trace("Added table type to sync {}", tt);
this.tableTypes = tats;
this.addPathTypes = addPathCapabilitiesList;
- if (! this.addPathTypes.isEmpty()) {
+ if (!this.addPathTypes.isEmpty()) {
final ChannelPipeline pipeline = this.channel.pipeline();
final BGPByteToMessageDecoder decoder = pipeline.get(BGPByteToMessageDecoder.class);
decoder.addDecoderConstraint(MultiPathSupport.class,
channel.eventLoop().schedule(this::handleKeepaliveTimer, this.keepAlive, TimeUnit.SECONDS);
}
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());
+ this.tableTypes, remoteOpen.getBgpParameters());
}
/**
public synchronized void setChannelExtMsgCoder(final Open remoteOpen) {
final boolean enableExMess = BgpExtendedMessageUtil.advertizedBgpExtendedMessageCapability(remoteOpen);
if (enableExMess) {
- this.channel.pipeline().replace(BGPMessageHeaderDecoder.class, EXTENDED_MSG_DECODER, BGPMessageHeaderDecoder.getExtendedBGPMessageHeaderDecoder());
+ this.channel.pipeline().replace(BGPMessageHeaderDecoder.class, EXTENDED_MSG_DECODER,
+ BGPMessageHeaderDecoder.getExtendedBGPMessageHeaderDecoder());
}
}
@Override
public synchronized void close() {
if (this.state != State.IDLE && !this.terminationReasonNotified) {
- this.writeAndFlush(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode()).setErrorSubcode(BGPError.CEASE.getSubcode()).build());
+ this.writeAndFlush(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode())
+ .setErrorSubcode(BGPError.CEASE.getSubcode()).build());
this.closeWithoutMessage();
}
}
} else if (msg instanceof Notify) {
final Notify notify = (Notify) msg;
// Notifications are handled internally
- LOG.info("Session closed because Notification message received: {} / {}, data={}", notify.getErrorCode(),
- notify.getErrorSubcode(), notify.getData() != null ? ByteBufUtil.hexDump(notify.getData()) : null);
+ LOG.info("Session closed because Notification message received: {} / {}, data={}",
+ notify.getErrorCode(),
+ notify.getErrorSubcode(),
+ notify.getData() != null ? ByteBufUtil.hexDump(notify.getData()) : null);
notifyTerminationReasonAndCloseWithoutMessage(notify.getErrorCode(), notify.getErrorSubcode());
} else if (msg instanceof Keepalive) {
// Keepalives are handled internally
LOG.warn("Ignoring unhandled message: {}.", msg.getClass());
}
- this.sessionStats.updateReceivedMsg(msg);
this.sessionState.messageReceived(msg);
} catch (final BGPDocumentedException e) {
this.terminate(e);
}
}
- private synchronized void notifyTerminationReasonAndCloseWithoutMessage(final Short errorCode, final Short errorSubcode) {
+ private synchronized void notifyTerminationReasonAndCloseWithoutMessage(
+ final Short errorCode,
+ final Short errorSubcode) {
this.terminationReasonNotified = true;
this.listener.onSessionTerminated(this, new BGPTerminationReason(
- BGPError.forValue(errorCode, errorSubcode)));
+ BGPError.forValue(errorCode, errorSubcode)));
this.closeWithoutMessage();
}
@GuardedBy("this")
private ChannelFuture writeEpilogue(final ChannelFuture future, final Notification msg) {
future.addListener(
- (ChannelFutureListener) f -> {
- if (!f.isSuccess()) {
- LOG.warn("Failed to send message {} to socket {}", msg, BGPSessionImpl.this.channel, f.cause());
- } else {
- LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
- }
- });
+ (ChannelFutureListener) f -> {
+ if (!f.isSuccess()) {
+ LOG.warn("Failed to send message {} to socket {}", msg, BGPSessionImpl.this.channel, f.cause());
+ } else {
+ LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
+ }
+ });
this.lastMessageSentAt = System.nanoTime();
- this.sessionStats.updateSentMsg(msg);
this.sessionState.messageSent(msg);
return future;
}
if (ct >= nextKeepalive) {
this.writeAndFlush(KEEP_ALIVE);
nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(this.keepAlive);
- this.sessionStats.updateSentMsgKA();
}
this.channel.eventLoop().schedule(this::handleKeepaliveTimer, nextKeepalive - ct, TimeUnit.NANOSECONDS);
}
return Collections.emptyList();
}
- protected synchronized void sessionUp() {
- this.sessionStats.startSessionStopwatch();
+ @VisibleForTesting
+ synchronized void sessionUp() {
this.state = State.UP;
this.sessionState.setSessionState(this.state);
this.listener.onSessionUp(this);
return this.asNumber;
}
- synchronized boolean isWritable() {
+ private synchronized boolean isWritable() {
return this.channel != null && this.channel.isWritable();
}
- @Override
- public synchronized BgpSessionState getBgpSessionState() {
- return this.sessionStats.getBgpSessionState();
- }
-
- @Override
- public synchronized void resetBgpSessionStats() {
- this.sessionStats.resetBgpSessionStats();
- }
-
public ChannelOutputLimiter getLimiter() {
return this.limiter;
}
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;
-import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;
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;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
/**
* Implementation of the BGP import policy. Listens on peer's Adj-RIB-In, inspects all inbound
* routes in the context of the advertising peer's role and applies the inbound policy.
- *
+ * <p>
* Inbound policy is applied as follows:
- *
+ * <p>
* 1) if the peer is an eBGP peer, perform attribute replacement and filtering
* 2) check if a route is admissible based on attributes attached to it, as well as the
- * advertising peer's role
+ * advertising peer's role
* 3) output admitting routes with edited attributes into /bgp-rib/rib/peer/effective-rib-in/tables/routes
- *
*/
@NotThreadSafe
final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesInstalledCounters, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(EffectiveRibInWriter.class);
-
- private static final Set<YangInstanceIdentifier> EMPTY_SET = Collections.emptySet();
static final NodeIdentifier TABLE_ROUTES = new NodeIdentifier(Routes.QNAME);
private final class AdjInTracker implements PrefixesReceivedCounters, PrefixesInstalledCounters, AutoCloseable,
- ClusteredDOMDataTreeChangeListener {
+ ClusteredDOMDataTreeChangeListener {
private final RIBSupportContextRegistry registry;
private final YangInstanceIdentifier peerIId;
private final YangInstanceIdentifier effRibTables;
private final ListenerRegistration<?> reg;
private final DOMTransactionChain chain;
- private final PerTableTypeRouteCounter adjRibInRouteCounters;
- private final Map<TablesKey, Set<YangInstanceIdentifier>> adjRibInRouteMap = new ConcurrentHashMap<>();
private final Map<TablesKey, LongAdder> prefixesReceived;
private final Map<TablesKey, LongAdder> prefixesInstalled;
AdjInTracker(final DOMDataTreeChangeService service, final RIBSupportContextRegistry registry,
- final DOMTransactionChain chain, final YangInstanceIdentifier peerIId,
- @Nonnull final PerTableTypeRouteCounter adjRibInRouteCounters, @Nonnull Set<TablesKey> tables) {
+ final DOMTransactionChain chain, final YangInstanceIdentifier peerIId,
+ @Nonnull Set<TablesKey> tables) {
this.registry = requireNonNull(registry);
this.chain = requireNonNull(chain);
this.peerIId = requireNonNull(peerIId);
this.effRibTables = this.peerIId.node(EffectiveRibIn.QNAME).node(Tables.QNAME);
- this.adjRibInRouteCounters = requireNonNull(adjRibInRouteCounters);
this.prefixesInstalled = buildPrefixesTables(tables);
this.prefixesReceived = buildPrefixesTables(tables);
final DOMDataTreeIdentifier treeId = new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL,
- this.peerIId.node(AdjRibIn.QNAME).node(Tables.QNAME));
+ this.peerIId.node(AdjRibIn.QNAME).node(Tables.QNAME));
LOG.debug("Registered Effective RIB on {}", this.peerIId);
this.reg = service.registerDataTreeChangeListener(treeId, this);
}
return b.build();
}
-
- private void updateRoute(@Nonnull final PerTableTypeRouteCounter counter, @Nonnull final Map<TablesKey, Set<YangInstanceIdentifier>> routeMap,
- @Nonnull final TablesKey tablesKey, @Nonnull final YangInstanceIdentifier routeId) {
- routeMap.putIfAbsent(tablesKey, new HashSet<>());
- routeMap.get(tablesKey).add(routeId);
- updateRouteCounter(counter, routeMap,tablesKey);
- }
-
- private void deleteRoute(@Nonnull final PerTableTypeRouteCounter counter, @Nonnull final Map<TablesKey, Set<YangInstanceIdentifier>> routeMap,
- @Nonnull final TablesKey tablesKey, @Nonnull final YangInstanceIdentifier routeId) {
- if (routeMap.containsKey(tablesKey)) {
- routeMap.get(tablesKey).remove(routeId);
- }
-
- updateRouteCounter(counter, routeMap,tablesKey);
- }
-
- private void deleteRoute(@Nonnull final PerTableTypeRouteCounter counter, @Nonnull final Map<TablesKey, Set<YangInstanceIdentifier>> routeMap,
- @Nonnull final TablesKey tablesKey) {
- routeMap.remove(tablesKey);
-
- updateRouteCounter(counter, routeMap,tablesKey);
- }
-
- private void updateRouteCounter(@Nonnull final PerTableTypeRouteCounter counter, @Nonnull final Map<TablesKey,
- Set<YangInstanceIdentifier>> 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) {
+ 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());
switch (route.getModificationType()) {
- case DELETE:
- case DISAPPEARED:
- tx.delete(LogicalDatastoreType.OPERATIONAL, routeId);
- LOG.debug("Route deleted. routeId={}", routeId);
-
- deleteRoute(this.adjRibInRouteCounters, this.adjRibInRouteMap, tablesKey, routeId);
- CountersUtil.decrement(this.prefixesInstalled.get(tablesKey), tablesKey);
- break;
- case UNMODIFIED:
- // No-op
- break;
- case APPEARED:
- 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);
- // Lookup per-table attributes from RIBSupport
- final ContainerNode advertisedAttrs = (ContainerNode) NormalizedNodes.findNode(route.getDataAfter(), ribSupport.routeAttributesIdentifier()).orNull();
- final ContainerNode effectiveAttrs;
-
- if (advertisedAttrs != null) {
- effectiveAttrs = policy.effectiveAttributes(advertisedAttrs);
- } else {
- effectiveAttrs = null;
- }
+ case DELETE:
+ case DISAPPEARED:
+ tx.delete(LogicalDatastoreType.OPERATIONAL, routeId);
+ LOG.debug("Route deleted. routeId={}", routeId);
+ CountersUtil.decrement(this.prefixesInstalled.get(tablesKey), tablesKey);
+ break;
+ case UNMODIFIED:
+ // No-op
+ break;
+ case APPEARED:
+ case SUBTREE_MODIFIED:
+ case WRITE:
+ tx.put(LogicalDatastoreType.OPERATIONAL, routeId, route.getDataAfter().get());
+ CountersUtil.increment(this.prefixesReceived.get(tablesKey), tablesKey);
+ // Lookup per-table attributes from RIBSupport
+ final ContainerNode advertisedAttrs = (ContainerNode) NormalizedNodes.findNode(route.getDataAfter(), ribSupport.routeAttributesIdentifier()).orNull();
+ final ContainerNode effectiveAttrs;
+
+ if (advertisedAttrs != null) {
+ effectiveAttrs = policy.effectiveAttributes(advertisedAttrs);
+ } else {
+ effectiveAttrs = null;
+ }
- LOG.debug("Route {} effective attributes {} towards {}", route.getIdentifier(), effectiveAttrs, routeId);
+ LOG.debug("Route {} effective attributes {} towards {}", route.getIdentifier(), effectiveAttrs, routeId);
- if (effectiveAttrs != null) {
- tx.put(LogicalDatastoreType.OPERATIONAL, routeId.node(ribSupport.routeAttributesIdentifier()), effectiveAttrs);
- if(route.getModificationType() == ModificationType.WRITE) {
- CountersUtil.increment(this.prefixesInstalled.get(tablesKey), tablesKey);
+ if (effectiveAttrs != null) {
+ tx.put(LogicalDatastoreType.OPERATIONAL, routeId.node(ribSupport.routeAttributesIdentifier()), effectiveAttrs);
+ 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);
}
- } else {
- LOG.warn("Route {} advertised empty attributes", routeId);
- tx.delete(LogicalDatastoreType.OPERATIONAL, routeId);
- }
- break;
- default:
- LOG.warn("Ignoring unhandled route {}", route);
- break;
+ break;
+ default:
+ LOG.warn("Ignoring unhandled route {}", route);
+ break;
}
}
.getModificationType(), childDataAfter, child.getDataBefore());
final YangInstanceIdentifier childPath = tablePath.node(childIdentifier);
switch (child.getModificationType()) {
- case DELETE:
- case DISAPPEARED:
- tx.delete(LogicalDatastoreType.OPERATIONAL, childPath);
- LOG.debug("Route deleted. routeId={}", childPath);
-
- deleteRoute(this.adjRibInRouteCounters, this.adjRibInRouteMap, tablesKey, childPath);
- CountersUtil.decrement(this.prefixesInstalled.get(tablesKey), tablesKey);
- break;
- case UNMODIFIED:
- // No-op
- break;
- case SUBTREE_MODIFIED:
- processModifiedRouteTables(child, childIdentifier,tx, ribSupport, EffectiveRibInWriter.this.importPolicy, childPath, childDataAfter);
- break;
- case APPEARED:
- case WRITE:
- writeRouteTables(child, childIdentifier,tx, ribSupport, EffectiveRibInWriter.this.importPolicy, childPath, childDataAfter);
-
- break;
- default:
- LOG.warn("Ignoring unhandled child {}", child);
- break;
+ case DELETE:
+ case DISAPPEARED:
+ tx.delete(LogicalDatastoreType.OPERATIONAL, childPath);
+ LOG.debug("Route deleted. routeId={}", childPath);
+ CountersUtil.decrement(this.prefixesInstalled.get(tablesKey), tablesKey);
+ break;
+ case UNMODIFIED:
+ // No-op
+ break;
+ case SUBTREE_MODIFIED:
+ processModifiedRouteTables(child, childIdentifier, tx, ribSupport, EffectiveRibInWriter.this.importPolicy, childPath, childDataAfter);
+ break;
+ case APPEARED:
+ case WRITE:
+ writeRouteTables(child, childIdentifier, tx, ribSupport, EffectiveRibInWriter.this.importPolicy, childPath, childDataAfter);
+
+ break;
+ default:
+ LOG.warn("Ignoring unhandled child {}", child);
+ break;
}
}
}
final RIBSupport ribSupport = getRibSupport(tableKey).getRibSupport();
final ModificationType modificationType = root.getModificationType();
switch (modificationType) {
- case DELETE:
- case DISAPPEARED:
- final YangInstanceIdentifier effectiveTablePath = effectiveTablePath(tableKey);
- LOG.debug("Delete Effective Table {} modification type {}, ", effectiveTablePath, modificationType);
-
- // delete the corresponding effective table
- tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath);
- 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);
- break;
- case UNMODIFIED:
- LOG.info("Ignoring spurious notification on {} data {}", rootPath, table);
- break;
- case APPEARED:
- case WRITE:
- writeTable(tx, tableKey, table);
- break;
- default:
- LOG.warn("Ignoring unhandled root {}", root);
- break;
+ case DELETE:
+ case DISAPPEARED:
+ final YangInstanceIdentifier effectiveTablePath = effectiveTablePath(tableKey);
+ LOG.debug("Delete Effective Table {} modification type {}, ", effectiveTablePath, modificationType);
+
+ // delete the corresponding effective table
+ tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath);
+ final TablesKey tk = new TablesKey(ribSupport.getAfi(), ribSupport.getSafi());
+ CountersUtil.decrement(this.prefixesInstalled.get(tk), tk);
+ break;
+ case SUBTREE_MODIFIED:
+ modifyTable(tx, tableKey, table);
+ break;
+ case UNMODIFIED:
+ LOG.info("Ignoring spurious notification on {} data {}", rootPath, table);
+ break;
+ case APPEARED:
+ case WRITE:
+ writeTable(tx, tableKey, table);
+ break;
+ default:
+ LOG.warn("Ignoring unhandled root {}", root);
+ break;
}
}
private final AdjInTracker adjInTracker;
private final AbstractImportPolicy importPolicy;
- 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 adjRibInRouteCounters, @Nonnull Set<TablesKey> tables) {
- return new EffectiveRibInWriter(service, chain, peerIId, importPolicyPeerTracker, registry, peerRole,
- adjRibInRouteCounters, tables);
+ 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 Set<TablesKey> tables) {
+ return new EffectiveRibInWriter(service, chain, peerIId, importPolicyPeerTracker, registry, peerRole, tables);
}
- private EffectiveRibInWriter(final DOMDataTreeChangeService service, final DOMTransactionChain chain, final YangInstanceIdentifier peerIId,
- final ImportPolicyPeerTracker importPolicyPeerTracker, final RIBSupportContextRegistry registry, final PeerRole peerRole,
- @Nonnull final PerTableTypeRouteCounter adjRibInRouteCounters, @Nonnull Set<TablesKey> tables) {
+ private EffectiveRibInWriter(final DOMDataTreeChangeService service,
+ final DOMTransactionChain chain,
+ final YangInstanceIdentifier peerIId,
+ final ImportPolicyPeerTracker importPolicyPeerTracker,
+ final RIBSupportContextRegistry registry,
+ final PeerRole peerRole,
+ @Nonnull Set<TablesKey> tables) {
importPolicyPeerTracker.peerRoleChanged(peerIId, peerRole);
this.importPolicy = importPolicyPeerTracker.policyFor(IdentifierUtils.peerId((NodeIdentifierWithPredicates) peerIId.getLastPathArgument()));
- this.adjInTracker = new AdjInTracker(service, registry, chain, peerIId, adjRibInRouteCounters, tables);
+ this.adjInTracker = new AdjInTracker(service, registry, chain, peerIId, tables);
}
@Override
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.spi.RIBSupportContext;
+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;
import org.opendaylight.protocol.bgp.rib.spi.RIBExtensionConsumerContext;
import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
@ThreadSafe
public final class RIBImpl extends BGPRIBStateImpl implements ClusterSingletonService, RIB, TransactionChainListener,
- SchemaContextListener, AutoCloseable {
+ 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);
private final Map<TransactionChain<?, ?>, LocRibWriter> txChainToLocRibWriter = new HashMap<>();
private final Map<TablesKey, PathSelectionMode> bestPathSelectionStrategies;
private final ImportPolicyPeerTracker importPolicyPeerTracker;
- private final RIBImplRuntimeMXBeanImpl renderStats;
private final RibId ribId;
private final Map<TablesKey, ExportPolicyPeerTracker> exportPolicyPeerTrackerMap;
private boolean isServiceInstantiated;
public RIBImpl(final ClusterSingletonServiceProvider provider, final RibId ribId, final AsNumber localAs, final BgpId localBgpId,
- final ClusterIdentifier clusterId, final RIBExtensionConsumerContext extensions, final BGPDispatcher dispatcher,
- final BindingCodecTreeFactory codecFactory, final DOMDataBroker domDataBroker, final List<BgpTableType> localTables,
- @Nonnull final Map<TablesKey, PathSelectionMode> bestPathSelectionStrategies, final GeneratedClassLoadingStrategy classStrategy,
- final BgpDeployer.WriteConfiguration configurationWriter) {
+ final ClusterIdentifier clusterId, final RIBExtensionConsumerContext extensions, final BGPDispatcher dispatcher,
+ final BindingCodecTreeFactory codecFactory, final DOMDataBroker domDataBroker, final List<BgpTableType> localTables,
+ @Nonnull final Map<TablesKey, PathSelectionMode> bestPathSelectionStrategies, final GeneratedClassLoadingStrategy classStrategy,
+ final BgpDeployer.WriteConfiguration configurationWriter) {
super(InstanceIdentifier.create(BgpRib.class).child(Rib.class, new RibKey(requireNonNull(ribId))),
- localBgpId, localAs);
+ localBgpId, localAs);
this.localAs = requireNonNull(localAs);
this.bgpIdentifier = requireNonNull(localBgpId);
this.dispatcher = requireNonNull(dispatcher);
exportPolicies.put(key, new ExportPolicyPeerTrackerImpl(policyDatabase, key));
}
this.exportPolicyPeerTrackerMap = exportPolicies.build();
-
- this.renderStats = new RIBImplRuntimeMXBeanImpl(localBgpId, ribId, localAs, cId, this, this.localTablesKeys);
LOG.info("RIB Singleton Service {} registered, RIB {}", getIdentifier().getValue(), this.ribId.getValue());
//this need to be always the last step
this.registration = registerClusterSingletonService(this);
}
final LocRibWriter locRibWriter = LocRibWriter.create(this.ribContextRegistry, key, txChain,
- getYangRibId(), this.localAs, getService(), this.exportPolicyPeerTrackerMap.get(key), pathSelectionStrategy);
+ getYangRibId(), this.localAs, getService(), this.exportPolicyPeerTrackerMap.get(key), pathSelectionStrategy);
registerTotalPathCounter(key, locRibWriter);
registerTotalPrefixesCounter(key, locRibWriter);
this.txChainToLocRibWriter.put(txChain, locRibWriter);
return (DOMDataTreeChangeService) this.service;
}
- @Override
- public BGPRenderStats getRenderStats() {
- return this.renderStats;
- }
-
@Override
public YangInstanceIdentifier getYangRibId() {
return this.yangRibId;
public synchronized void instantiateServiceInstance() {
this.isServiceInstantiated = true;
this.domChain = this.domDataBroker.createTransactionChain(this);
- if(this.configurationWriter != null) {
+ if (this.configurationWriter != null) {
this.configurationWriter.apply();
}
LOG.info("RIB Singleton Service {} instantiated, RIB {}", getIdentifier().getValue(), this.ribId.getValue());
- LOG.debug("Instantiating RIB table {} at {}", this.ribId , this.yangRibId);
+ LOG.debug("Instantiating RIB table {} at {}", this.ribId, this.yangRibId);
final ContainerNode bgpRib = Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(BgpRib.QNAME))
- .addChild(ImmutableNodes.mapNodeBuilder(Rib.QNAME).build()).build();
+ .addChild(ImmutableNodes.mapNodeBuilder(Rib.QNAME).build()).build();
final MapEntryNode ribInstance = Builders.mapEntryBuilder().withNodeIdentifier(
- new NodeIdentifierWithPredicates(Rib.QNAME, RIB_ID_QNAME, this.ribId .getValue()))
- .addChild(ImmutableNodes.leafNode(RIB_ID_QNAME, this.ribId .getValue()))
- .addChild(ImmutableNodes.mapNodeBuilder(Peer.QNAME).build())
- .addChild(Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(LocRib.QNAME))
- .addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build())
- .build()).build();
+ new NodeIdentifierWithPredicates(Rib.QNAME, RIB_ID_QNAME, this.ribId.getValue()))
+ .addChild(ImmutableNodes.leafNode(RIB_ID_QNAME, this.ribId.getValue()))
+ .addChild(ImmutableNodes.mapNodeBuilder(Peer.QNAME).build())
+ .addChild(Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(LocRib.QNAME))
+ .addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build())
+ .build()).build();
final DOMDataWriteTransaction trans = this.domChain.newWriteOnlyTransaction();
@Override
public synchronized ListenableFuture<Void> closeServiceInstance() {
- if(!this.isServiceInstantiated) {
+ if (!this.isServiceInstantiated) {
LOG.trace("RIB Singleton Service {} already closed, RIB {}", getIdentifier().getValue(),
- this.ribId.getValue());
+ this.ribId.getValue());
return Futures.immediateFuture(null);
}
LOG.info("Close RIB Singleton Service {}, RIB {}", getIdentifier().getValue(), this.ribId.getValue());
@Override
public ClusterSingletonServiceRegistration registerClusterSingletonService(
- final ClusterSingletonService clusterSingletonService) {
+ final ClusterSingletonService clusterSingletonService) {
return ClusterSingletonServiceRegistrationHelper
- .registerSingletonService(this.provider, clusterSingletonService);
+ .registerSingletonService(this.provider, clusterSingletonService);
}
@Override
import java.util.Objects;
import java.util.Set;
import javax.annotation.concurrent.GuardedBy;
-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;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
import org.slf4j.LoggerFactory;
-public final class BgpPeer implements PeerBean, BGPPeerStateConsumer, BGPPeerRuntimeMXBean {
+public final class BgpPeer implements PeerBean, BGPPeerStateConsumer {
private static final Logger LOG = LoggerFactory.getLogger(BgpPeer.class);
@Override
public synchronized void start(final RIB rib, final Neighbor neighbor, final BGPTableTypeRegistryConsumer tableTypeRegistry,
- final WriteConfiguration configurationWriter) {
+ final WriteConfiguration configurationWriter) {
Preconditions.checkState(this.bgpPeerSingletonService == null, "Previous peer instance was not closed.");
this.bgpPeerSingletonService = new BgpPeerSingletonService(rib, neighbor, tableTypeRegistry, configurationWriter);
this.currentConfiguration = neighbor;
final List<AfiSafi> actualSafi = actAfiSafi != null ? actAfiSafi.getAfiSafi() : Collections.emptyList();
final List<AfiSafi> extSafi = extAfiSafi != null ? extAfiSafi.getAfiSafi() : Collections.emptyList();
return actualSafi.containsAll(extSafi) && extSafi.containsAll(actualSafi)
- && Objects.equals(this.currentConfiguration.getConfig(), neighbor.getConfig())
- && Objects.equals(this.currentConfiguration.getNeighborAddress(), neighbor.getNeighborAddress())
- && Objects.equals(this.currentConfiguration.getAddPaths(),neighbor.getAddPaths())
- && Objects.equals(this.currentConfiguration.getApplyPolicy(), neighbor.getApplyPolicy())
- && Objects.equals(this.currentConfiguration.getAsPathOptions(), neighbor.getAsPathOptions())
- && Objects.equals(this.currentConfiguration.getEbgpMultihop(), neighbor.getEbgpMultihop())
- && Objects.equals(this.currentConfiguration.getGracefulRestart(), neighbor.getGracefulRestart())
- && Objects.equals(this.currentConfiguration.getErrorHandling(), neighbor.getErrorHandling())
- && Objects.equals(this.currentConfiguration.getLoggingOptions(), neighbor.getLoggingOptions())
- && Objects.equals(this.currentConfiguration.getRouteReflector(), neighbor.getRouteReflector())
- && Objects.equals(this.currentConfiguration.getState(), neighbor.getState())
- && Objects.equals(this.currentConfiguration.getTimers(), neighbor.getTimers())
- && Objects.equals(this.currentConfiguration.getTransport(), neighbor.getTransport());
+ && Objects.equals(this.currentConfiguration.getConfig(), neighbor.getConfig())
+ && Objects.equals(this.currentConfiguration.getNeighborAddress(), neighbor.getNeighborAddress())
+ && Objects.equals(this.currentConfiguration.getAddPaths(), neighbor.getAddPaths())
+ && Objects.equals(this.currentConfiguration.getApplyPolicy(), neighbor.getApplyPolicy())
+ && Objects.equals(this.currentConfiguration.getAsPathOptions(), neighbor.getAsPathOptions())
+ && Objects.equals(this.currentConfiguration.getEbgpMultihop(), neighbor.getEbgpMultihop())
+ && Objects.equals(this.currentConfiguration.getGracefulRestart(), neighbor.getGracefulRestart())
+ && Objects.equals(this.currentConfiguration.getErrorHandling(), neighbor.getErrorHandling())
+ && Objects.equals(this.currentConfiguration.getLoggingOptions(), neighbor.getLoggingOptions())
+ && Objects.equals(this.currentConfiguration.getRouteReflector(), neighbor.getRouteReflector())
+ && Objects.equals(this.currentConfiguration.getState(), neighbor.getState())
+ && Objects.equals(this.currentConfiguration.getTimers(), neighbor.getTimers())
+ && Objects.equals(this.currentConfiguration.getTransport(), neighbor.getTransport());
}
private static List<BgpParameters> getBgpParameters(final Neighbor neighbor, final RIB rib,
return Optional.absent();
}
- @Override
- public BgpPeerState getBgpPeerState() {
- return this.bgpPeerSingletonService.getPeer().getBgpPeerState();
- }
-
- @Override
- public BgpSessionState getBgpSessionState() {
- return this.bgpPeerSingletonService.getPeer().getBgpSessionState();
- }
-
- @Override
- public void resetSession() {
- this.bgpPeerSingletonService.getPeer().resetSession();
- }
-
- @Override
- public void resetStats() {
- this.bgpPeerSingletonService.getPeer().resetStats();
- }
-
@Override
public BGPPeerState getPeerState() {
if (this.bgpPeerSingletonService == null) {
}
private final class BgpPeerSingletonService implements BGPPeerStateConsumer, ClusterSingletonService,
- AutoCloseable {
+ AutoCloseable {
private final ServiceGroupIdentifier serviceGroupIdentifier;
private final boolean activeConnection;
private final BGPDispatcher dispatcher;
private boolean isServiceInstantiated;
private BgpPeerSingletonService(final RIB rib, final Neighbor neighbor,
- final BGPTableTypeRegistryConsumer tableTypeRegistry, final WriteConfiguration configurationWriter) {
+ final BGPTableTypeRegistryConsumer tableTypeRegistry, final WriteConfiguration configurationWriter) {
this.neighborAddress = neighbor.getNeighborAddress();
final AfiSafis afisSAfis = requireNonNull(neighbor.getAfiSafis());
final Set<TablesKey> afiSafisAdvertized = OpenConfigMappingUtil
- .toTableKey(afisSAfis.getAfiSafi(), tableTypeRegistry);
+ .toTableKey(afisSAfis.getAfiSafi(), tableTypeRegistry);
this.bgpPeer = new BGPPeer(Ipv4Util.toStringIP(this.neighborAddress), rib,
- OpenConfigMappingUtil.toPeerRole(neighbor), getSimpleRoutingPolicy(neighbor), BgpPeer.this.rpcRegistry,
- afiSafisAdvertized, Collections.emptySet());
+ OpenConfigMappingUtil.toPeerRole(neighbor), getSimpleRoutingPolicy(neighbor), BgpPeer.this.rpcRegistry,
+ afiSafisAdvertized, Collections.emptySet());
final List<BgpParameters> 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));
+ getPeerAs(neighbor, rib), bgpParameters, getPassword(keyMapping));
this.activeConnection = OpenConfigMappingUtil.isActive(neighbor);
this.dispatcher = rib.getDispatcher();
this.inetAddress = Ipv4Util.toInetSocketAddress(this.neighborAddress, OpenConfigMappingUtil.getPort(neighbor));
@Override
public synchronized void instantiateServiceInstance() {
this.isServiceInstantiated = true;
- if(this.configurationWriter != null) {
+ if (this.configurationWriter != null) {
this.configurationWriter.apply();
}
LOG.info("Peer Singleton Service {} instantiated, Peer {}", getIdentifier().getValue(), this.neighborAddress);
@Override
public synchronized ListenableFuture<Void> closeServiceInstance() {
- if(!this.isServiceInstantiated) {
+ if (!this.isServiceInstantiated) {
LOG.info("Peer Singleton Service {} already closed, Peer {}", getIdentifier().getValue(),
- this.neighborAddress);
+ this.neighborAddress);
return Futures.immediateFuture(null);
}
LOG.info("Close Peer Singleton Service {}, Peer {}", getIdentifier().getValue(), this.neighborAddress);
this.connection = null;
}
final ListenableFuture<Void> future = this.bgpPeer.close();
- if(BgpPeer.this.currentConfiguration != null) {
+ if (BgpPeer.this.currentConfiguration != null) {
this.dispatcher.getBGPPeerRegistry().removePeer(BgpPeer.this.currentConfiguration.getNeighborAddress());
}
return future;
return this.serviceGroupIdentifier;
}
- BGPPeerRuntimeMXBean getPeer() {
- return this.bgpPeer;
- }
-
@Override
public BGPPeerState getPeerState() {
return this.bgpPeer.getPeerState();
import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
-import org.opendaylight.mdsal.dom.api.DOMSchemaService;
import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeFactory;
+import org.opendaylight.mdsal.dom.api.DOMSchemaService;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
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.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;
private ClusterIdentifier clusterId;
public RibImpl(final ClusterSingletonServiceProvider provider, final RIBExtensionConsumerContext contextProvider,
- final BGPDispatcher dispatcher, final BindingCodecTreeFactory codecTreeFactory, final DOMDataBroker domBroker,
- final DOMSchemaService domSchemaService) {
+ final BGPDispatcher dispatcher, final BindingCodecTreeFactory codecTreeFactory, final DOMDataBroker domBroker,
+ final DOMSchemaService domSchemaService) {
this.provider = requireNonNull(provider);
this.extensions = contextProvider;
this.dispatcher = dispatcher;
}
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);
+ final BgpDeployer.WriteConfiguration configurationWriter) {
+ Preconditions.checkState(this.ribImpl == null,
+ "Previous instance %s was not closed.", this);
this.ribImpl = createRib(global, instanceName, tableTypeRegistry, configurationWriter);
this.schemaContextRegistration = this.domSchemaService.registerSchemaContextListener(this.ribImpl);
}
final Ipv4Address globalRouterId = global.getConfig().getRouterId();
final ClusterIdentifier globalClusterId = getClusterIdentifier(globalConfig);
return this.afiSafi.containsAll(globalAfiSafi) && globalAfiSafi.containsAll(this.afiSafi)
- && globalAs.equals(this.asNumber)
- && globalRouterId.getValue().equals(this.routerId.getValue())
- && globalClusterId.getValue().equals(this.clusterId.getValue());
+ && globalAs.equals(this.asNumber)
+ && globalRouterId.getValue().equals(this.routerId.getValue())
+ && globalClusterId.getValue().equals(this.clusterId.getValue());
}
@Override
if (this.serviceRegistration != null) {
try {
this.serviceRegistration.unregister();
- } catch(final IllegalStateException e) {
+ } catch (final IllegalStateException e) {
LOG.warn("Failed to unregister {} service instance", this, e);
}
this.serviceRegistration = null;
this.serviceRegistration = serviceRegistration;
}
- @Override
- public BGPRenderStats getRenderStats() {
- return this.ribImpl.getRenderStats();
- }
-
@Override
public ImportPolicyPeerTracker getImportPolicyPeerTracker() {
return this.ribImpl.getImportPolicyPeerTracker();
return this.ribImpl != null ? this.ribImpl.toString() : null;
}
- private RIBImpl createRib(final Global global, final String bgpInstanceName,
- final BGPTableTypeRegistryConsumer tableTypeRegistry, final BgpDeployer.WriteConfiguration configurationWriter) {
+ 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 = getClusterIdentifier(globalConfig);
- final Map<TablesKey, PathSelectionMode> 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(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);
+ final Map<TablesKey, PathSelectionMode> 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(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);
}
@Override
- public ClusterSingletonServiceRegistration registerClusterSingletonService(final ClusterSingletonService clusterSingletonService) {
+ public ClusterSingletonServiceRegistration registerClusterSingletonService(
+ final ClusterSingletonService clusterSingletonService) {
return this.ribImpl.registerClusterSingletonService(clusterSingletonService);
}
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;
RIB("ribImpl", ImmutableList.of(RIB.class, RibReference.class, BGPRIBStateConsumer.class)),
- PEER("bgpPeer", ImmutableList.of(BGPPeerRuntimeMXBean.class, BGPPeerStateConsumer.class)),
+ PEER("bgpPeer", ImmutableList.of(BGPPeerStateConsumer.class)),
APP_PEER("appPeer", Collections.singletonList(BGPPeerStateConsumer.class));
import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
import org.opendaylight.protocol.bgp.rib.RibReference;
-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.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
/**
* Internal reference to a RIB instance.
*/
-public interface RIB extends RibReference, ClusterSingletonServiceProvider {
+public interface RIB extends RibReference, ClusterSingletonServiceProvider {
AsNumber getLocalAs();
BgpId getBgpIdentifier();
*
* @return A set of identifiers.
*/
- @Nonnull Set<? extends BgpTableType> getLocalTables();
+ @Nonnull
+ Set<? extends BgpTableType> getLocalTables();
BGPDispatcher getDispatcher();
/**
* Return instance of DOMDataTreeChangeService, where consumer can register to
* listen on DOM data changes.
+ *
* @return DOMDataTreeChangeService
*/
DOMDataTreeChangeService getService();
- BGPRenderStats getRenderStats();
-
ImportPolicyPeerTracker getImportPolicyPeerTracker();
/**
* Returns ExportPolicyPeerTracker for specific tableKey, where peer can register himself
* as supporting the table. Same export policy can be used to check which peers support respective
* table and announce then routes if required.
+ *
* @param tablesKey supported table
* @return ExportPolicyPeerTracker
*/
/**
* Return common ServiceGroupIdentifier to be used between same group cluster service
+ *
* @return ServiceGroupIdentifier
*/
ServiceGroupIdentifier getRibIServiceGroupIdentifier();
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.bgp.rib.impl.stats.peer;
-
-import java.util.concurrent.atomic.LongAdder;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpPeerState;
-import org.opendaylight.protocol.bgp.rib.impl.stats.peer.route.PerTableTypeRouteCounter;
-
-public interface BGPPeerStats {
- BgpPeerState getBgpPeerState();
-
- PerTableTypeRouteCounter getAdjRibInRouteCounters();
-
- PerTableTypeRouteCounter getAdjRibOutRouteCounters();
-
- LongAdder getSessionEstablishedCounter();
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.bgp.rib.impl.stats.peer;
-
-import static java.util.Objects.requireNonNull;
-import static org.opendaylight.protocol.bgp.rib.impl.CountersUtil.toZeroBasedCounter32;
-
-import com.google.common.collect.Lists;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.atomic.LongAdder;
-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;
-
-public final class BGPPeerStatsImpl implements BGPPeerStats {
- private final Set<TablesKey> tablesKeySet;
- private final PerTableTypeRouteCounter adjRibInRouteCounters;
- private final PerTableTypeRouteCounter adjRibOutRouteCounters;
- private final LongAdder sessionEstablishedCounter = new LongAdder();
- private final BGPPeerStateImpl neighborState;
-
- public BGPPeerStatsImpl(@Nonnull final String peerName, @Nonnull final Set<TablesKey> tablesKeySet,
- @Nonnull final BGPPeerStateImpl neighborState) {
- requireNonNull(peerName);
- this.tablesKeySet = requireNonNull(tablesKeySet);
- this.adjRibInRouteCounters = new PerTableTypeRouteCounter(tablesKeySet);
- this.adjRibOutRouteCounters = new PerTableTypeRouteCounter(tablesKeySet);
- this.neighborState = requireNonNull(neighborState);
- }
-
- public PerTableTypeRouteCounter getAdjRibInRouteCounters() {
- return this.adjRibInRouteCounters;
- }
-
- public PerTableTypeRouteCounter getAdjRibOutRouteCounters() {
- return this.adjRibOutRouteCounters;
- }
-
- private RouteTable createRouteTable(@Nonnull final TablesKey tablesKey) {
- requireNonNull(tablesKey);
- final RouteTable routeTable = new RouteTable();
- final QName afiQName = BindingReflections.findQName(tablesKey.getAfi()).intern();
- final QName safiQName = BindingReflections.findQName(tablesKey.getSafi()).intern();
- routeTable.setAfi(new IdentityAttributeRef(afiQName.toString()));
- routeTable.setSafi(new IdentityAttributeRef(safiQName.toString()));
- // 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(new ZeroBasedCounter32(this.neighborState
- .getPrefixesInstalledCount(tablesKey)));
-
- return routeTable;
- }
-
- @Override
- public BgpPeerState getBgpPeerState() {
- final BgpPeerState peerState = new BgpPeerState();
- final List<RouteTable> routes = Lists.newArrayList();
- this.tablesKeySet.forEach(tablesKey -> routes.add(createRouteTable(tablesKey)));
- peerState.setRouteTable(routes);
- peerState.setSessionEstablishedCount(toZeroBasedCounter32(this.sessionEstablishedCounter));
- return peerState;
- }
-
- @Override
- public LongAdder getSessionEstablishedCounter() {
- return this.sessionEstablishedCounter;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.protocol.bgp.rib.impl.stats.peer;
-
-import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
-
-/**
- * Serves to expose BGP session statistics to the BGP Peer, to which the session is related.
- */
-public interface BGPSessionStats {
-
- /**
- * Retrieves actual BGP session state. Containing all information collected from the session.
- *
- * @return State of the BGP session.
- */
- BgpSessionState getBgpSessionState();
-
- /**
- * Resets BGP session statistics. Sets counters values to zero.
- */
- void resetBgpSessionStats();
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.protocol.bgp.rib.impl.stats.peer;
-
-import static java.util.Objects.requireNonNull;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Stopwatch;
-import io.netty.channel.Channel;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-import javax.annotation.Nonnull;
-import org.opendaylight.controller.config.api.IdentityAttributeRef;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.AdvertisedAddPathTableTypes;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.AdvertizedTableTypes;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.ErrorMsgs;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.ErrorReceived;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.ErrorReceivedTotal;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.ErrorSent;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.ErrorSentTotal;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.KeepAliveMsgs;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.LocalPeerPreferences;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.MessagesStats;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.Received;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.RemotePeerPreferences;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.RouteRefreshMsgs;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.Sent;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.TotalMsgs;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.UpdateMsgs;
-import org.opendaylight.protocol.bgp.rib.impl.BGPSessionImpl;
-import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
-import org.opendaylight.protocol.util.StatisticsUtil;
-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.IpAddressBuilder;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Timestamp;
-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.message.rev130919.Keepalive;
-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.Open;
-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.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.RouteRefresh;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.mp.capabilities.MultiprotocolCapability;
-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.types.rev130919.BgpId;
-import org.opendaylight.yangtools.yang.binding.Notification;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class BGPSessionStatsImpl implements BGPSessionStats {
- private static final Logger LOG = LoggerFactory.getLogger(BGPSessionStatsImpl.class);
-
- private final Stopwatch sessionStopwatch;
- private final BgpSessionState stats;
- private final BGPSessionImpl session;
- private final TotalMsgs totalMsgs = new TotalMsgs();
- private final KeepAliveMsgs kaMsgs = new KeepAliveMsgs();
- private final UpdateMsgs updMsgs = new UpdateMsgs();
- private final RouteRefreshMsgs rrMsgs = new RouteRefreshMsgs();
- 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<BGPSessionPreferences> localPreferences, @Nonnull final Collection<BgpTableType> tableTypes, @Nonnull final List<AddressFamilies> addPathTypes) {
- this.session = session;
- this.sessionStopwatch = Stopwatch.createUnstarted();
- this.stats = new BgpSessionState();
- this.stats.setHoldtimeCurrent(holdTimerValue);
- this.stats.setKeepaliveCurrent(keepAlive);
- this.stats.setLocalPeerPreferences(setLocalPeerPref(remoteOpen, channel, tableTypes, addPathTypes));
- this.stats.setRemotePeerPreferences(setRemotePeerPref(channel, localPreferences));
- this.errMsgs.setErrorReceivedTotal(this.errMsgsRecvTotal);
- this.errMsgs.setErrorSentTotal(this.errMsgsSentTotal);
- this.errMsgs.setErrorReceived(new ArrayList<>());
- this.errMsgs.setErrorSent(new ArrayList<>());
- initMsgs();
- }
-
- private static Received newReceivedInstance() {
- final Received recv = new Received();
- recv.setCount(INITIAL_COUNTER);
- return recv;
- }
-
- private static Sent newSentInstance() {
- final Sent sent = new Sent();
- sent.setCount(INITIAL_COUNTER);
- return sent;
- }
-
- private static void updateReceivedMsg(final Received received) {
- requireNonNull(received);
- final long count = received.getCount() == null ? 0L : received.getCount().getValue();
- received.setCount(new ZeroBasedCounter32(count + 1));
- received.setTimestamp(new Timestamp(StatisticsUtil.getCurrentTimestampInSeconds()));
- }
-
- private static void updateSentMsg(final Sent sent) {
- requireNonNull(sent);
- final long count = sent.getCount() == null ? 0L : sent.getCount().getValue();
- sent.setCount(new ZeroBasedCounter32(count + 1));
- sent.setTimestamp(new Timestamp(StatisticsUtil.getCurrentTimestampInSeconds()));
- }
-
- private static AdvertizedTableTypes addTableType(final BgpTableType type) {
- requireNonNull(type);
- final AdvertizedTableTypes att = new AdvertizedTableTypes();
- final QName afi = BindingReflections.findQName(type.getAfi()).intern();
- final QName safi = BindingReflections.findQName(type.getSafi()).intern();
- att.setAfi(new IdentityAttributeRef(afi.toString()));
- att.setSafi(new IdentityAttributeRef(safi.toString()));
- return att;
- }
-
- private static AdvertisedAddPathTableTypes addAddPathTableType(final AddressFamilies addressFamilies) {
- requireNonNull(addressFamilies);
- final AdvertisedAddPathTableTypes att = new AdvertisedAddPathTableTypes();
- att.setAfi(new IdentityAttributeRef(BindingReflections.findQName(addressFamilies.getAfi()).intern().toString()));
- att.setSafi(new IdentityAttributeRef(BindingReflections.findQName(addressFamilies.getSafi()).intern().toString()));
- att.setSendReceive(addressFamilies.getSendReceive());
- return att;
- }
-
- private static RemotePeerPreferences setRemotePeerPref(final Channel channel, final Optional<BGPSessionPreferences> localPreferences) {
- requireNonNull(channel);
- final RemotePeerPreferences pref = new RemotePeerPreferences();
- final InetSocketAddress isa = (InetSocketAddress) channel.localAddress();
- pref.setHost(IpAddressBuilder.getDefaultInstance(isa.getAddress().getHostAddress()));
- pref.setPort(new PortNumber(isa.getPort()));
- final List<AdvertizedTableTypes> tt = new ArrayList<>();
- final List<AdvertisedAddPathTableTypes> attList = new ArrayList<>();
- if (localPreferences.isPresent()) {
- final BGPSessionPreferences localPref = localPreferences.get();
- pref.setBgpId(localPref.getBgpId());
- pref.setAs(localPref.getMyAs());
- pref.setHoldtimer(localPref.getHoldTime());
- if (localPref.getParams() != null) {
- for (final BgpParameters param : localPref.getParams()) {
- for (final OptionalCapabilities capa : param.getOptionalCapabilities()) {
- final CParameters cParam = capa.getCParameters();
- final CParameters1 capabilities = cParam.getAugmentation(CParameters1.class);
- if (capabilities != null) {
- final MultiprotocolCapability mc = capabilities.getMultiprotocolCapability();
- if (mc != null) {
- final AdvertizedTableTypes att = new AdvertizedTableTypes();
- att.setAfi(new IdentityAttributeRef(BindingReflections.findQName(mc.getAfi()).intern().toString()));
- att.setSafi(new IdentityAttributeRef(BindingReflections.findQName(mc.getSafi()).intern().toString()));
- tt.add(att);
- }
- if (capabilities.getGracefulRestartCapability() != null) {
- pref.setGrCapability(true);
- }
- if (capabilities.getAddPathCapability() != null) {
- final List<AdvertisedAddPathTableTypes> addPathTableTypeList = capabilities.getAddPathCapability()
- .getAddressFamilies()
- .stream()
- .map(BGPSessionStatsImpl::addAddPathTableType)
- .collect(Collectors.toList());
- attList.addAll(addPathTableTypeList);
- }
- if (capabilities.getRouteRefreshCapability() != null) {
- pref.setRouteRefreshCapability(true);
- }
- }
- if (cParam.getAs4BytesCapability() != null) {
- pref.setFourOctetAsCapability(true);
- }
- if (cParam.getBgpExtendedMessageCapability() != null) {
- pref.setBgpExtendedMessageCapability(true);
- }
- }
- }
- }
- }
- pref.setAdvertizedTableTypes(tt);
- pref.setAdvertisedAddPathTableTypes(attList);
- return pref;
- }
-
- private static LocalPeerPreferences setLocalPeerPref(final Open remoteOpen, final Channel channel, final Collection<BgpTableType> tableTypes,
- final List<AddressFamilies> addPathTypes) {
- requireNonNull(remoteOpen);
- requireNonNull(channel);
- final LocalPeerPreferences pref = new LocalPeerPreferences();
- final InetSocketAddress isa = (InetSocketAddress) channel.remoteAddress();
- pref.setHost(IpAddressBuilder.getDefaultInstance(isa.getAddress().getHostAddress()));
- pref.setPort(new PortNumber(isa.getPort()));
- pref.setBgpId(new BgpId(remoteOpen.getBgpIdentifier()));
- pref.setAs(new AsNumber(remoteOpen.getMyAsNumber().longValue()));
- pref.setHoldtimer(remoteOpen.getHoldTimer());
-
- final List<AdvertizedTableTypes> tt = tableTypes.stream().map(BGPSessionStatsImpl::addTableType).collect(Collectors.toList());
- final List<AdvertisedAddPathTableTypes> addPathTableTypeList = addPathTypes.stream().map(BGPSessionStatsImpl::addAddPathTableType)
- .collect(Collectors.toList());
-
- if (remoteOpen.getBgpParameters() != null) {
- for (final BgpParameters param : remoteOpen.getBgpParameters()) {
- for (final OptionalCapabilities capa : param.getOptionalCapabilities()) {
- final CParameters cParam = capa.getCParameters();
- final CParameters1 capabilities = cParam.getAugmentation(CParameters1.class);
- if (cParam.getAs4BytesCapability() != null) {
- pref.setFourOctetAsCapability(true);
- }
- if (capabilities != null) {
- if (capabilities.getGracefulRestartCapability() != null) {
- pref.setGrCapability(true);
- }
- if (capabilities.getRouteRefreshCapability() != null) {
- pref.setRouteRefreshCapability(true);
- }
- }
- if (cParam.getBgpExtendedMessageCapability() != null) {
- pref.setBgpExtendedMessageCapability(true);
- }
- }
-
- }
- }
- pref.setAdvertizedTableTypes(tt);
- pref.setAdvertisedAddPathTableTypes(addPathTableTypeList);
- return pref;
- }
-
- private void initMsgs() {
- this.totalMsgs.setReceived(newReceivedInstance());
- this.totalMsgs.setSent(newSentInstance());
- this.kaMsgs.setReceived(newReceivedInstance());
- this.kaMsgs.setSent(newSentInstance());
- this.updMsgs.setReceived(newReceivedInstance());
- this.updMsgs.setSent(newSentInstance());
- this.rrMsgs.setReceived(newReceivedInstance());
- this.rrMsgs.setSent(newSentInstance());
- this.errMsgsSentTotal.setCount(INITIAL_COUNTER);
- this.errMsgsRecvTotal.setCount(INITIAL_COUNTER);
- this.errMsgs.getErrorSent().clear();
- this.errMsgs.getErrorReceived().clear();
- }
-
- public void startSessionStopwatch() {
- this.sessionStopwatch.start();
- }
-
- private void updateSentMsgTotal() {
- updateSentMsg(this.totalMsgs.getSent());
- }
-
- private void updateReceivedMsgTotal() {
- updateReceivedMsg(this.totalMsgs.getReceived());
- }
-
- private void updateReceivedMsgKA() {
- updateReceivedMsg(this.kaMsgs.getReceived());
- }
-
- public void updateSentMsgKA() {
- updateSentMsg(this.kaMsgs.getSent());
- }
-
- private void updateSentMsgUpd() {
- updateSentMsg(this.updMsgs.getSent());
- }
-
- private void updateReceivedMsgUpd() {
- updateReceivedMsg(this.updMsgs.getReceived());
- }
-
- private void updateSentMsgRR() {
- updateSentMsg(this.rrMsgs.getSent());
- }
-
- private void updateReceivedMsgRR() {
- updateReceivedMsg(this.rrMsgs.getReceived());
- }
-
- private void updateReceivedMsgErr(@Nonnull final Notify error) {
- requireNonNull(error);
- final List<ErrorReceived> errList = this.errMsgs.getErrorReceived();
- ErrorReceived received = null;
- for (ErrorReceived err : errList) {
- if (err.getErrorCode().equals(error.getErrorCode()) && err.getErrorSubcode().equals(error.getErrorSubcode())) {
- received = err;
- break;
- }
- }
- if (null == received) {
- received = new ErrorReceived();
- received.setErrorCode(error.getErrorCode());
- received.setErrorSubcode(error.getErrorSubcode());
- received.setCount(INITIAL_COUNTER);
- errList.add(received);
- }
- received.setCount(new ZeroBasedCounter32(received.getCount().getValue() + 1));
- final Timestamp curTimestamp = new Timestamp(StatisticsUtil.getCurrentTimestampInSeconds());
- received.setTimestamp(curTimestamp);
- this.errMsgsRecvTotal.setCount(new ZeroBasedCounter32(this.errMsgsRecvTotal.getCount().getValue() + 1));
- this.errMsgsRecvTotal.setTimestamp(curTimestamp);
- }
-
- private void updateSentMsgErr(@Nonnull final Notify error) {
- requireNonNull(error);
- final List<ErrorSent> errList = this.errMsgs.getErrorSent();
- ErrorSent sent = null;
- for (ErrorSent err : errList) {
- if (err.getErrorCode().equals(error.getErrorCode()) && err.getErrorSubcode().equals(error.getErrorSubcode())) {
- sent = err;
- break;
- }
- }
- if (null == sent) {
- sent = new ErrorSent();
- sent.setErrorCode(error.getErrorCode());
- sent.setErrorSubcode(error.getErrorSubcode());
- sent.setCount(INITIAL_COUNTER);
- errList.add(sent);
- }
- sent.setCount(new ZeroBasedCounter32(sent.getCount().getValue() + 1));
- final Timestamp curTimestamp = new Timestamp(StatisticsUtil.getCurrentTimestampInSeconds());
- sent.setTimestamp(curTimestamp);
- this.errMsgsSentTotal.setCount(new ZeroBasedCounter32(this.errMsgsSentTotal.getCount().getValue() + 1));
- this.errMsgsSentTotal.setTimestamp(curTimestamp);
- }
-
- @Override
- public BgpSessionState getBgpSessionState() {
- final MessagesStats msgs = new MessagesStats();
- msgs.setTotalMsgs(this.totalMsgs);
- msgs.setErrorMsgs(this.errMsgs);
- msgs.setKeepAliveMsgs(this.kaMsgs);
- msgs.setUpdateMsgs(this.updMsgs);
- msgs.setRouteRefreshMsgs(this.rrMsgs);
- this.stats.setSessionDuration(StatisticsUtil.formatElapsedTime(this.sessionStopwatch.elapsed(TimeUnit.SECONDS)));
- this.stats.setSessionState(this.session.getState().toString());
- this.stats.setMessagesStats(msgs);
- return this.stats;
- }
-
- @Override
- public void resetBgpSessionStats() {
- initMsgs();
- }
-
- public void updateReceivedMsg(Notification msg) {
- LOG.trace("Updating received BGP session message count..");
- this.updateReceivedMsgTotal();
- if (msg instanceof Notify) {
- this.updateReceivedMsgErr((Notify) msg);
- } else if (msg instanceof Keepalive) {
- this.updateReceivedMsgKA();
- } else if (msg instanceof RouteRefresh) {
- this.updateReceivedMsgRR();
- } else if (msg instanceof Update) {
- this.updateReceivedMsgUpd();
- }
- }
-
- public void updateSentMsg(Notification msg) {
- LOG.trace("Updating sent BGP session message count..");
- this.updateSentMsgTotal();
- if (msg instanceof Update) {
- this.updateSentMsgUpd();
- } else if (msg instanceof Notify) {
- this.updateSentMsgErr((Notify) msg);
- } else if (msg instanceof RouteRefresh) {
- this.updateSentMsgRR();
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.bgp.rib.impl.stats.peer.route;
-
-import static java.util.Objects.requireNonNull;
-
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.LongAdder;
-import javax.annotation.Nonnull;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class PerTableTypeRouteCounter {
- private static final Logger LOG = LoggerFactory.getLogger(PerTableTypeRouteCounter.class);
-
- private final Map<TablesKey, LongAdder> counters = new ConcurrentHashMap<>();
-
- public PerTableTypeRouteCounter(@Nonnull final Set<TablesKey> tablesKeySet) {
- init(tablesKeySet);
- }
-
- public PerTableTypeRouteCounter() {
- }
-
- private synchronized void init(@Nonnull final Set<TablesKey> tablesKeySet) {
- tablesKeySet.forEach(this::init);
- }
-
- public final synchronized LongAdder init(@Nonnull final TablesKey tablesKey) {
- LongAdder counter = this.counters.get(requireNonNull(tablesKey));
- if (counter == null) {
- counter = new LongAdder();
- this.counters.put(tablesKey, counter);
- }
- LOG.debug("Initializing route counter for tablesKey {}", tablesKey);
- counter.reset();
- return counter;
- }
-
- /**
- * 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
- */
- @Nonnull public final LongAdder getCounterOrDefault(@Nonnull final TablesKey tablesKey) {
- return this.counters.getOrDefault(requireNonNull(tablesKey), new LongAdder());
- }
-
- /**
- * 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
- */
- public final LongAdder getCounterOrSetDefault(@Nonnull final TablesKey tablesKey) {
- if (!this.counters.containsKey(tablesKey)) {
- return init(tablesKey);
- }
-
- return this.counters.get(requireNonNull(tablesKey));
- }
-
- public final Map<TablesKey, LongAdder> getCounters() {
- return this.counters;
- }
-
- public final void resetAll() {
- 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);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.bgp.rib.impl.stats.rib.impl;
-
-import java.util.concurrent.atomic.LongAdder;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.RIBImplRuntimeMXBean;
-
-public interface BGPRenderStats extends RIBImplRuntimeMXBean {
- LongAdder getConfiguredPeerCounter();
-
- LongAdder getConnectedPeerCounter();
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.protocol.bgp.rib.impl.stats.rib.impl;
-
-import static java.util.Objects.requireNonNull;
-import static org.opendaylight.protocol.bgp.rib.impl.CountersUtil.toZeroBasedCounter32;
-
-import java.util.ArrayList;
-import java.util.List;
-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.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;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.ClusterIdentifier;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.common.QName;
-
-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 = new LongAdder();
- private final LongAdder connectedPeerCounter = new LongAdder();
- private final BGPRIBState globalState;
- private final Set<TablesKey> tablesKeys;
-
- 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<TablesKey> tablesKeys) {
- this.bgpId = requireNonNull(bgpId);
- this.ribId = requireNonNull(ribId);
- this.globalState = requireNonNull(globalState);
- this.tablesKeys = requireNonNull(tablesKeys);
- this.localAs = localAs;
- this.clusterId = clusterId;
- }
-
- @Override
- public BgpRenderState getBgpRenderState() {
- final BgpRenderState renderState = new BgpRenderState();
- renderState.setRibId(this.ribId);
- renderState.setBgpRibId(this.bgpId);
- renderState.setClusterId(this.clusterId);
- renderState.setLocalAs(this.localAs);
- renderState.setConfiguredPeerCount(toZeroBasedCounter32(this.configuredPeerCounter));
- renderState.setConnectedPeerCount(toZeroBasedCounter32(this.connectedPeerCounter));
- // fill in the the statistic part
- final LongAdder totalRouteCount = new LongAdder();
- final List<LocRibRouteTable> locRibRouteTableList = new ArrayList<>();
- this.tablesKeys.forEach(e -> generateCounters(e, locRibRouteTableList, totalRouteCount));
- renderState.setLocRibRouteTable(locRibRouteTableList);
- renderState.setLocRibRoutesCount(toZeroBasedCounter32(totalRouteCount));
- return renderState;
- }
-
- private void generateCounters(final TablesKey tablesKey, final List<LocRibRouteTable> locRibRouteTableList,
- final LongAdder totalRouteCount) {
- final LocRibRouteTable table = new LocRibRouteTable();
- 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()));
- final long count = this.globalState.getPathCount(tablesKey);
- table.setRoutesCount(new ZeroBasedCounter32(count));
- locRibRouteTableList.add(table);
- totalRouteCount.add(count);
-
- }
-
- @Override
- public LongAdder getConfiguredPeerCounter() {
- return this.configuredPeerCounter;
- }
-
- @Override
- public LongAdder getConnectedPeerCounter() {
- return this.connectedPeerCounter;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.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.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;
-
-/**
- * @author Kevin Wang
- */
-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,
- @Nonnull final BGPRIBState globalState,
- @Nonnull final Set<TablesKey> tablesKeys) {
- this.renderStats = new BGPRenderStatsImpl(bgpId, ribId, localAs, clusterId, globalState, tablesKeys);
- }
-
- @Override
- public BgpRenderState getBgpRenderState() {
- return this.renderStats.getBgpRenderState();
- }
-
- @Override
- public LongAdder getConfiguredPeerCounter() {
- return this.renderStats.getConfiguredPeerCounter();
- }
-
- @Override
- public LongAdder getConnectedPeerCounter() {
- return this.renderStats.getConnectedPeerCounter();
- }
-}
+++ /dev/null
-module bgp-stats-peer {
- namespace "urn:opendaylight:params:xml:ns:yang:controller:bgp:stats:peer";
- prefix "bgp-stats-peer";
-
- import bgp-peer { prefix peer; revision-date 2016-06-06; }
- import bgp-multiprotocol { prefix bgp-mp; revision-date 2013-09-19; }
- import bgp-message { prefix bgp-msg; revision-date 2013-09-19; }
- import ietf-yang-types { prefix yang; revision-date 2013-07-15; }
-
- organization "Brocade Communications Systems, Inc.";
- contact "Kevin Wang <kwang@brocade.com>";
-
- description
- "This module contains the base data model of BGP peer statistic.
-
- Copyright (c) 2016 Brocade Communications Systems, Inc. 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";
-
- revision 2016-06-06 {
- description "Initial revision";
- }
-
- grouping bgp-message-state {
- leaf count {
- description "Total number of BGP messages.";
- type yang:zero-based-counter32;
- }
-
- leaf timestamp {
- description "The BGP message timestamp (seconds).";
- type yang:timestamp;
- }
- }
-
- grouping bgp-message-stats {
- container received {
- description "The received BGP messages statistics.";
- uses bgp-message-state;
- }
-
- container sent {
- description "The sent BGP messages statistics.";
- uses bgp-message-state;
- }
- }
-
- grouping bgp-peer-state {
- container bgp-peer-state {
- list route-table {
- key "afi safi";
- uses bgp-mp:bgp-table-type;
-
- leaf adj-rib-in-routes-count {
- description "The total number of Adj-RIB-In routes in table.";
- type yang:zero-based-counter32;
- }
-
- leaf adj-rib-out-routes-count {
- description "The total number of Adj-RIB-Out routes in table.";
- type yang:zero-based-counter32;
- }
-
- leaf effective-rib-in-routes-count {
- description "The total number of Effective-RIB-In routes in table.";
- type yang:zero-based-counter32;
- }
- }
-
- leaf session-established-count {
- description "The total number of time the BGP session was transitioned to Up state.";
- type yang:zero-based-counter32;
- }
- }
- }
-
- grouping bgp-session-state {
- container bgp-session-state {
-
- leaf session-state {
- description "The BGP peer connection state.";
- type string;
- }
-
- leaf session-duration {
- description "The session duration (time formated d:HH:mm:ss).";
- type string;
- }
-
- leaf holdtime-current {
- description "Time interval (in seconds) for HoldTimer established with the peer.";
- type uint16;
- default 0;
- }
-
- leaf keepalive-current {
- description "Time interval (in seconds) for KeepAlive established with the peer.";
- type uint16;
- default 0;
- }
-
- container remote-peer-preferences {
- description "The BGP remote peer preferences, to which this BGP peer is connected.";
- uses peer:bgp-peer-preferences;
- }
-
- container local-peer-preferences {
- description "The BGP local peer preferences.";
- uses peer:bgp-peer-preferences;
- }
-
- container messages-stats {
- description "The BGP messages statistics.";
- container total-msgs {
- description "The statistics for all received/sent BGP messages.";
- uses bgp-message-stats;
- }
-
- container keep-alive-msgs {
- description "The statistics for received/sent BGP Keep-Alive messages.";
- uses bgp-message-stats;
- }
-
- container update-msgs {
- description "The statistics for received/sent BGP Update messages.";
- uses bgp-message-stats;
- }
-
- container route-refresh-msgs {
- description "The statistics for received/sent BGP Route Refresh messages.";
- uses bgp-message-stats;
- }
-
- container error-msgs {
- container error-received-total {
- description "The total number of received BGP Error (notification) messages.";
- uses bgp-message-state;
- }
-
- list error-received {
- description "The received BGP Error (notification) messages.";
- key "error-code error-subcode";
-
- uses bgp-message-state;
- uses bgp-msg:notify-message;
- }
-
- container error-sent-total {
- description "The total number of sent BGP Error (notification) messages.";
- uses bgp-message-state;
- }
-
- list error-sent {
- description "The sent BGP Error (notification) messages.";
- key "error-code error-subcode";
-
- uses bgp-message-state;
- uses bgp-msg:notify-message;
- }
- }
- }
- }
- }
-
- grouping bgp-peer-stats {
- uses bgp-peer-state;
- uses bgp-session-state;
- }
-}
\ No newline at end of file
+++ /dev/null
-module bgp-stats-rib-impl {
- namespace "urn:opendaylight:params:xml:ns:yang:controller:bgp:stats:rib:impl";
- prefix "bgp-stats-rib-impl";
-
- import bgp-rib-impl { prefix rib-impl; revision-date 2016-06-06; }
- import bgp-multiprotocol { prefix bgp-mp; revision-date 2013-09-19; }
- import ietf-yang-types { prefix yang; revision-date 2013-07-15; }
-
- organization "Brocade Communications Systems, Inc.";
- contact "Kevin Wang <kwang@brocade.com>";
-
- description
- "This module contains the base data model of BGP render statistic.
-
- Copyright (c) 2016 Brocade Communications Systems, Inc. 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";
-
- revision 2016-06-06 {
- description "Initial revision";
- }
-
- grouping bgp-render-stats {
- container bgp-render-state {
- uses rib-impl:bgp-rib-impl-identifiers;
-
- leaf configured-peer-count {
- description "The total number of BGP peer configured to be associated with this RIB instance.";
- type yang:zero-based-counter32;
- }
-
- leaf connected-peer-count {
- description "The total number of BGP peer connected to this RIB instance.";
- type yang:zero-based-counter32;
- }
-
- leaf loc-rib-routes-count {
- description "The total number of routes in loc-rib.";
- type yang:zero-based-counter32;
- }
-
- list loc-rib-route-table {
- key "afi safi";
- uses bgp-mp:bgp-table-type;
-
- leaf routes-count {
- description "The total number of routes in table.";
- type yang:zero-based-counter32;
- }
- }
- }
- }
-}
\ No newline at end of file
import rpc-context { prefix rpcx; revision-date 2013-06-17; }
import odl-bgp-path-selection-mode { prefix bps; revision-date 2016-03-01;}
import bgp-peer { prefix peer; revision-date 2016-06-06; }
- import bgp-stats-peer { prefix peer-stats; revision-date 2016-06-06; }
- import bgp-stats-rib-impl { prefix rib-impl-stats; revision-date 2016-06-06; }
organization "Cisco Systems, Inc.";
when "/config:modules/config:module/config:type = 'bgp-peer'";
rpcx:rpc-context-instance "peer-rpc";
- uses peer-stats:bgp-peer-stats;
- }
-
- case rib-impl {
- when "/config:modules/config:module/config:type = 'rib-impl'";
-
- uses rib-impl-stats:bgp-render-stats;
}
}
}
}
- rpc reset-stats {
- description "Reset the BGP peer statistics.";
- input {
- uses rpcx:rpc-context-ref {
- refine context-instance {
- rpcx:rpc-context-instance peer-rpc;
- }
- }
- }
- }
-
identity bgp-path-selection-mode {
description
"Service representing an address family + path selection mode.";
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
import org.opendaylight.protocol.bgp.parser.BGPError;
import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
import org.opendaylight.protocol.bgp.rib.spi.State;
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.KeepaliveBuilder;
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.NotifyBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Open;
assertEquals(1, this.bgpSession.getAdvertisedTableTypes().size());
Assert.assertEquals(State.UP, this.listener.getState());
- //test stats
- final BgpSessionState state = this.bgpSession.getBgpSessionState();
- assertEquals(HOLD_TIMER, state.getHoldtimeCurrent().intValue());
- assertEquals(1, state.getKeepaliveCurrent().intValue());
- assertEquals(State.UP.name(), state.getSessionState());
- assertEquals(BGP_ID.getValue(), new String(state.getLocalPeerPreferences().getHost().getValue()));
- assertEquals(AS_NUMBER.getValue(), state.getLocalPeerPreferences().getAs().getValue());
- assertTrue(state.getLocalPeerPreferences().getBgpExtendedMessageCapability());
- assertEquals(BGP_ID.getValue(), state.getLocalPeerPreferences().getBgpId().getValue());
- assertEquals(1, state.getLocalPeerPreferences().getAdvertizedTableTypes().size());
- assertEquals(HOLD_TIMER, state.getLocalPeerPreferences().getHoldtimer().intValue());
- assertTrue(state.getLocalPeerPreferences().getFourOctetAsCapability());
- assertTrue(state.getLocalPeerPreferences().getBgpExtendedMessageCapability());
- assertTrue(state.getLocalPeerPreferences().getGrCapability());
- assertEquals(LOCAL_IP, new String(state.getRemotePeerPreferences().getHost().getValue()));
- assertEquals(LOCAL_PORT, state.getRemotePeerPreferences().getPort().getValue().intValue());
- assertEquals(0, state.getMessagesStats().getTotalMsgs().getReceived().getCount().getValue().longValue());
- assertEquals(0, state.getMessagesStats().getTotalMsgs().getSent().getCount().getValue().longValue());
-
this.bgpSession.handleMessage(new UpdateBuilder().build());
assertEquals(1, this.listener.getListMsg().size());
assertTrue(this.listener.getListMsg().get(0) instanceof Update);
- assertEquals(1, state.getMessagesStats().getTotalMsgs().getReceived().getCount().getValue().longValue());
- assertEquals(1, state.getMessagesStats().getUpdateMsgs().getReceived().getCount().getValue().longValue());
- assertEquals(0, state.getMessagesStats().getUpdateMsgs().getSent().getCount().getValue().longValue());
-
- this.bgpSession.handleMessage(new KeepaliveBuilder().build());
- this.bgpSession.handleMessage(new KeepaliveBuilder().build());
- assertEquals(3, state.getMessagesStats().getTotalMsgs().getReceived().getCount().getValue().longValue());
- assertEquals(2, state.getMessagesStats().getKeepAliveMsgs().getReceived().getCount().getValue().longValue());
- assertEquals(0, state.getMessagesStats().getKeepAliveMsgs().getSent().getCount().getValue().longValue());
-
this.bgpSession.close();
assertEquals(State.IDLE, this.bgpSession.getState());
assertEquals(1, this.receivedMsgs.size());
assertEquals(BGPError.CEASE.getCode(), error.getErrorCode().shortValue());
assertEquals(BGPError.CEASE.getSubcode(), error.getErrorSubcode().shortValue());
Mockito.verify(this.speakerListener).close();
- assertEquals(3, state.getMessagesStats().getTotalMsgs().getReceived().getCount().getValue().longValue());
- assertEquals(1, state.getMessagesStats().getTotalMsgs().getSent().getCount().getValue().longValue());
- assertEquals(1, state.getMessagesStats().getErrorMsgs().getErrorSentTotal().getCount().getValue().longValue());
- assertEquals(1, state.getMessagesStats().getErrorMsgs().getErrorSent().get(0).getCount().getValue().longValue());
- assertEquals(BGPError.CEASE.getCode(), state.getMessagesStats().getErrorMsgs().getErrorSent().get(0).getErrorCode().shortValue());
- assertEquals(BGPError.CEASE.getSubcode(), state.getMessagesStats().getErrorMsgs().getErrorSent().get(0).getErrorSubcode().shortValue());
-
- this.bgpSession.resetBgpSessionStats();
- assertEquals(0, state.getMessagesStats().getTotalMsgs().getReceived().getCount().getValue().longValue());
- assertEquals(0, state.getMessagesStats().getTotalMsgs().getSent().getCount().getValue().longValue());
- assertEquals(0, state.getMessagesStats().getErrorMsgs().getErrorSentTotal().getCount().getValue().longValue());
}
@Test
@Test
public void testHandleNotifyMsg() throws BGPDocumentedException {
- this.bgpSession.handleMessage(new NotifyBuilder().setErrorCode(BGPError.BAD_BGP_ID.getCode()).setErrorSubcode(BGPError.BAD_BGP_ID.getSubcode()).build());
- assertEquals(1, this.bgpSession.getBgpSessionState().getMessagesStats().getErrorMsgs().getErrorReceivedTotal().getCount().getValue().longValue());
- assertEquals(1, this.bgpSession.getBgpSessionState().getMessagesStats().getErrorMsgs().getErrorReceived().get(0).getCount().getValue().longValue());
- assertEquals(BGPError.BAD_BGP_ID.getCode(), this.bgpSession.getBgpSessionState().getMessagesStats().getErrorMsgs().getErrorReceived().get(0).getErrorCode().shortValue());
- assertEquals(BGPError.BAD_BGP_ID.getSubcode(), this.bgpSession.getBgpSessionState().getMessagesStats().getErrorMsgs().getErrorReceived().get(0).getErrorSubcode().shortValue());
+ this.bgpSession.handleMessage(new NotifyBuilder().setErrorCode(BGPError.BAD_BGP_ID.getCode())
+ .setErrorSubcode(BGPError.BAD_BGP_ID.getSubcode()).build());
Assert.assertEquals(State.IDLE, this.bgpSession.getState());
Mockito.verify(this.speakerListener).close();
}
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
-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;
import org.opendaylight.protocol.bgp.parser.BGPError;
@Test
public void testClassicPeer() throws Exception {
this.classic = new BGPPeer(this.neighborAddress.getValue(), getRib(), PeerRole.Ibgp, null, Collections.emptySet(),
- Collections.emptySet());
+ Collections.emptySet());
this.classic.instantiateServiceInstance();
this.mockSession();
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=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());
//create new peer so that it gets advertized routes from RIB
final BGPPeer testingPeer = new BGPPeer(this.neighborAddress.getValue(), getRib(), PeerRole.Ibgp, null,
- Collections.emptySet(), Collections.emptySet());
+ Collections.emptySet(), Collections.emptySet());
testingPeer.instantiateServiceInstance();
testingPeer.onSessionUp(this.session);
assertEquals(3, this.routes.size());
- assertEquals(1, testingPeer.getBgpPeerState().getSessionEstablishedCount().getValue().intValue());
- final List<RouteTable> routeTables = testingPeer.getBgpPeerState().getRouteTable();
- assertEquals(1, routeTables.size());
- final RouteTable routeTable = routeTables.get(0);
- assertEquals(AFI_QNAME.toString(), routeTable.getAfi().getqNameOfIdentity());
- assertEquals(SAFI_QNAME.toString(), routeTable.getSafi().getqNameOfIdentity());
- assertNotNull(testingPeer.getBgpSessionState());
final List<Ipv4Prefix> prefs2 = Lists.newArrayList(new Ipv4Prefix("8.0.1.0/28"), new Ipv4Prefix("8.0.1.16/28"));
ub.setNlri(new NlriBuilder().setNlri(prefs2).build());
assertEquals(2, this.routes.size());
this.classic.onMessage(this.session, new KeepaliveBuilder().build());
this.classic.onMessage(this.session, new UpdateBuilder().setAttributes(
- new AttributesBuilder().addAugmentation(
- Attributes2.class,
- new Attributes2Builder().setMpUnreachNlri(
- new MpUnreachNlriBuilder().setAfi(AFI).setSafi(SAFI).build()).build()).build()).build());
+ new AttributesBuilder().addAugmentation(
+ Attributes2.class,
+ new Attributes2Builder().setMpUnreachNlri(
+ new MpUnreachNlriBuilder().setAfi(AFI).setSafi(SAFI).build()).build()).build()).build());
this.classic.onMessage(this.session, new RouteRefreshBuilder().setAfi(AFI).setSafi(SAFI).build());
this.classic.onMessage(this.session, new RouteRefreshBuilder().setAfi(Ipv6AddressFamily.class).setSafi(SAFI).build());
assertEquals(2, this.routes.size());
Mockito.doReturn(new InetSocketAddress("localhost", 12345)).when(channel).remoteAddress();
Mockito.doReturn(new InetSocketAddress("localhost", 12345)).when(channel).localAddress();
final List<BgpParameters> params = Lists.newArrayList(new BgpParametersBuilder().setOptionalCapabilities(
- Lists.newArrayList(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(
- CParameters1.class, new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder()
- .setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class).build()).build()).build()).build())).build());
+ Lists.newArrayList(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(
+ CParameters1.class, new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder()
+ .setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class).build()).build()).build()).build())).build());
final Open openObj = new OpenBuilder().setBgpIdentifier(new Ipv4Address("1.1.1.1")).setHoldTimer(50).setMyAsNumber(72).setBgpParameters(params).build();
this.session = new BGPSessionImpl(this.classic, channel, openObj, 30, null);
this.session.setChannelExtMsgCoder(openObj);
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.stats.rib.impl.BGPRenderStats;
import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
import org.opendaylight.protocol.concepts.KeyMapping;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
@Mock
protected DOMTransactionChain domTx;
@Mock
- protected BGPRenderStats render;
- @Mock
protected BGPDispatcher dispatcher;
@Mock
protected ServiceRegistration<?> serviceRegistration;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- Mockito.doAnswer(invocationOnMock->{
+ Mockito.doAnswer(invocationOnMock -> {
this.singletonService = (ClusterSingletonService) invocationOnMock.getArguments()[0];
return this.singletonServiceRegistration;
}).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();
+ .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();
Mockito.doReturn(null).when(checkedFuture).get();
Mockito.doReturn(true).when(checkedFuture).isDone();
Mockito.doReturn("checkedFuture").when(checkedFuture).toString();
- Mockito.doAnswer(invocationOnMock->{
+ Mockito.doAnswer(invocationOnMock -> {
this.singletonService.closeServiceInstance();
return null;
}).when(this.singletonServiceRegistration).close();
Mockito.doReturn(new BgpId("127.0.0.1")).when(this.rib).getBgpIdentifier();
Mockito.doReturn(true).when(this.future).cancel(true);
Mockito.doReturn(this.future).when(this.dispatcher)
- .createReconnectingClient(any(InetSocketAddress.class), anyInt(), any(KeyMapping.class));
+ .createReconnectingClient(any(InetSocketAddress.class), anyInt(), any(KeyMapping.class));
Mockito.doReturn(this.dispatcher).when(this.rib).getDispatcher();
Mockito.doReturn(java.util.Optional.of(new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class)))
- .when(this.tableTypeRegistry).getTableType(any());
+ .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();
+ .when(this.rib).getLocalTables();
Mockito.doNothing().when(this.configurationWriter).apply();
Mockito.doNothing().when(this.bgpPeerRegistry).addPeer(any(IpAddress.class), any(BGPSessionListener.class), any(BGPSessionPreferences.class));
Mockito.verify(this.rib).registerClusterSingletonService(any(ClusterSingletonService.class));
this.singletonService.instantiateServiceInstance();
- Mockito.verify(this.render).getConfiguredPeerCounter();
Mockito.verify(this.configurationWriter).apply();
Mockito.verify(this.bgpPeerRegistry).addPeer(any(), any(), any());
Mockito.verify(this.dispatcher).createReconnectingClient(any(InetSocketAddress.class),
Mockito.verify(this.rib, times(2)).getRibIServiceGroupIdentifier();
Mockito.verify(this.rib, times(2)).registerClusterSingletonService(any(ClusterSingletonService.class));
this.singletonService.instantiateServiceInstance();
- Mockito.verify(this.render, times(2)).getConfiguredPeerCounter();
- assertNotNull(this.bgpPeer.getBgpPeerState());
- assertNotNull(this.bgpPeer.getBgpSessionState());
- this.bgpPeer.resetStats();
- this.bgpPeer.resetSession();
final Neighbor neighborExpected = createNeighborExpected(NEIGHBOR_ADDRESS);
assertTrue(this.bgpPeer.containsEqualConfiguration(neighborExpected));
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.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.Collections;
-import java.util.List;
-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;
-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;
-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;
-
-public class BGPRenderStatsImplTest {
- private static final BgpId BGP_ID = new BgpId("127.0.0.1");
- private static final RibId RIB_ID = new RibId("test-rib");
- 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, this.bgpGlobalState,
- Collections.singleton(this.tk));
-
- final BgpRenderState renderStateExpected = new BgpRenderState();
- renderStateExpected.setRibId(RIB_ID);
- renderStateExpected.setBgpRibId(BGP_ID);
- renderStateExpected.setClusterId(CLUSTER_ID);
- renderStateExpected.setLocalAs(AS);
- renderStateExpected.setConfiguredPeerCount(COUTER);
- renderStateExpected.setConnectedPeerCount(COUTER);
- final LocRibRouteTable locRibTable = new LocRibRouteTable();
- locRibTable.setAfi(new IdentityAttributeRef(Ipv4AddressFamily.QNAME.toString()));
- locRibTable.setSafi(new IdentityAttributeRef(UnicastSubsequentAddressFamily.QNAME.toString()));
- locRibTable.setRoutesCount(COUTER);
- final List<LocRibRouteTable> locRibRouteTableList = Collections.singletonList(locRibTable);
- renderStateExpected.setLocRibRouteTable(locRibRouteTableList);
- renderStateExpected.setLocRibRoutesCount(COUTER);
- doReturn(0L).when(this.bgpGlobalState).getPathCount(eq(this.tk));
-
- assertEquals(renderStateExpected, render.getBgpRenderState());
- 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