import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+
/**
* Writer of Adjacency-RIB-In for a single peer. An instance of this object
* is attached to each {@link BGPPeer} and {@link ApplicationPeer}.
*/
@NotThreadSafe
final class AdjRibInWriter {
+
private static final Logger LOG = LoggerFactory.getLogger(AdjRibInWriter.class);
+
@VisibleForTesting
static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_FALSE = ImmutableNodes.leafNode(QName.create(Attributes.QNAME, "uptodate"), Boolean.FALSE);
- private static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_TRUE = ImmutableNodes.leafNode(ATTRIBUTES_UPTODATE_FALSE.getNodeType(), Boolean.TRUE);
@VisibleForTesting
static final QName PEER_ID_QNAME = QName.create(Peer.QNAME, "peer-id").intern();
+ private static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_TRUE = ImmutableNodes.leafNode(ATTRIBUTES_UPTODATE_FALSE.getNodeType(), Boolean.TRUE);
private static final QName PEER_ROLE_QNAME = QName.create(Peer.QNAME, "peer-role").intern();
private static final NodeIdentifier ADJRIBIN = new NodeIdentifier(AdjRibIn.QNAME);
private static final NodeIdentifier ADJRIBOUT = new NodeIdentifier(AdjRibOut.QNAME);
private final Optional<SimpleRoutingPolicy> simpleRoutingPolicy;
private AdjRibInWriter(final YangInstanceIdentifier ribPath, final DOMTransactionChain chain, final PeerRole role,
- final Optional<SimpleRoutingPolicy> simpleRoutingPolicy, final YangInstanceIdentifier peerPath, final Map<TablesKey, TableContext> tables) {
+ final Optional<SimpleRoutingPolicy> simpleRoutingPolicy, final YangInstanceIdentifier peerPath,
+ final Map<TablesKey, TableContext> tables) {
this.ribPath = requireNonNull(ribPath);
this.chain = requireNonNull(chain);
this.tables = requireNonNull(tables);
/**
* Create a new writer using a transaction chain.
*
- * @param role peer's role
+ * @param role peer's role
* @param simpleRoutingPolicy simple Routing Policy {@link SimpleRoutingPolicy}
- *@param chain transaction chain @return A fresh writer instance
+ * @param chain transaction chain @return A fresh writer instance
*/
static AdjRibInWriter create(@Nonnull final YangInstanceIdentifier ribId, @Nonnull final PeerRole role,
- final Optional<SimpleRoutingPolicy> simpleRoutingPolicy, @Nonnull final DOMTransactionChain chain) {
+ final Optional<SimpleRoutingPolicy> simpleRoutingPolicy, @Nonnull final DOMTransactionChain chain) {
return new AdjRibInWriter(ribId, chain, role, simpleRoutingPolicy, null, Collections.emptyMap());
}
* Empty tables are created for new entries and old tables are deleted. Once this
* method returns, the old instance must not be reasonably used.
*
- * @param newPeerId new peer BGP identifier
- * @param registry RIB extension registry
- * @param tableTypes New tables, must not be null
+ * @param newPeerId new peer BGP identifier
+ * @param registry RIB extension registry
+ * @param tableTypes New tables, must not be null
* @param addPathTablesType
* @return New writer
*/
AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry,
- final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType) {
+ final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType) {
return transform(newPeerId, registry, tableTypes, addPathTablesType, null);
}
AdjRibInWriter transform(final PeerId newPeerId, final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes,
- final Map<TablesKey, SendReceive> addPathTablesType, @Nullable final RegisterAppPeerListener registerAppPeerListener) {
+ final Map<TablesKey, SendReceive> addPathTablesType, @Nullable final RegisterAppPeerListener registerAppPeerListener) {
final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
final YangInstanceIdentifier newPeerPath;
newPeerPath = createEmptyPeerStructure(newPeerId, tx);
final ImmutableMap<TablesKey, TableContext> tb = createNewTableInstances(newPeerPath, registry, tableTypes,
- addPathTablesType, tx);
+ addPathTablesType, tx);
Futures.addCallback(tx.submit(), new FutureCallback<Void>() {
@Override
public void onSuccess(final Void result) {
- if(registerAppPeerListener != null) {
+ if (registerAppPeerListener != null) {
LOG.trace("Application Peer Listener registered");
registerAppPeerListener.register();
}
@Override
public void onFailure(final Throwable throwable) {
- if(registerAppPeerListener != null) {
+ if (registerAppPeerListener != null) {
LOG.error("Failed to create Empty Structure, Application Peer Listener won't be registered",
- throwable);
+ throwable);
} else {
LOG.error("Failed to create Empty Structure", throwable);
}
/**
* Create new table instances, potentially creating their empty entries
+ *
* @param newPeerPath
* @param registry
* @param tableTypes
* @return
*/
private ImmutableMap<TablesKey, TableContext> createNewTableInstances(final YangInstanceIdentifier newPeerPath,
- final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType,
- final DOMDataWriteTransaction tx) {
+ final RIBSupportContextRegistry registry, final Set<TablesKey> tableTypes, final Map<TablesKey, SendReceive> addPathTablesType,
+ final DOMDataWriteTransaction tx) {
final Builder<TablesKey, TableContext> tb = ImmutableMap.builder();
for (final TablesKey tableKey : tableTypes) {
}
private void installAdjRibsOutTables(final YangInstanceIdentifier newPeerPath, final RIBSupportContext rs,
- final NodeIdentifierWithPredicates instanceIdentifierKey, final TablesKey tableKey, final SendReceive sendReceive,
- final DOMDataWriteTransaction tx) {
+ final NodeIdentifierWithPredicates instanceIdentifierKey, final TablesKey tableKey, final SendReceive sendReceive,
+ final DOMDataWriteTransaction tx) {
if (!isAnnounceNone(this.simpleRoutingPolicy)) {
final NodeIdentifierWithPredicates supTablesKey = RibSupportUtils.toYangKey(SupportedTables.QNAME, tableKey);
final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> tt = Builders.mapEntryBuilder().withNodeIdentifier(supTablesKey);
for (final Entry<QName, Object> e : supTablesKey.getKeyValues().entrySet()) {
tt.withChild(ImmutableNodes.leafNode(e.getKey(), e.getValue()));
}
- if(sendReceive != null) {
+ if (sendReceive != null) {
tt.withChild(ImmutableNodes.leafNode(SEND_RECEIVE, sendReceive.toString().toLowerCase()));
}
tx.put(LogicalDatastoreType.OPERATIONAL, newPeerPath.node(PEER_TABLES).node(supTablesKey), tt.build());
}
pb.withChild(ImmutableMapNodeBuilder.create().withNodeIdentifier(PEER_TABLES).build());
pb.withChild(EMPTY_ADJRIBIN);
- if(!isLearnNone(this.simpleRoutingPolicy)) {
+ if (!isLearnNone(this.simpleRoutingPolicy)) {
pb.withChild(EMPTY_EFFRIBIN);
}
if (!isAnnounceNone(this.simpleRoutingPolicy)) {
return pb.build();
}
- ListenableFuture<Void> removePeer() {
- if(this.peerPath != null) {
+ synchronized ListenableFuture<Void> removePeer() {
+ if (this.peerPath != null) {
+
+ LOG.info("AdjRibInWriter closed per Peer {} removed", AdjRibInWriter.this.peerPath);
final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
tx.delete(LogicalDatastoreType.OPERATIONAL, this.peerPath);
final ListenableFuture<Void> future = tx.submit();
private static String simpleRoutingPolicyString(final SimpleRoutingPolicy simpleRoutingPolicy) {
switch (simpleRoutingPolicy) {
- case AnnounceNone:
- return "announce-none";
- case LearnNone:
- return "learn-none";
- default:
- throw new IllegalArgumentException("Unhandled Simple Routing Policy " + simpleRoutingPolicy);
+ case AnnounceNone:
+ return "announce-none";
+ case LearnNone:
+ return "learn-none";
+ default:
+ throw new IllegalArgumentException("Unhandled Simple Routing Policy " + simpleRoutingPolicy);
}
}
}
}
@Override
- public void onDataTreeChanged(@Nonnull final Collection<DataTreeCandidate> changes) {
+ public synchronized void onDataTreeChanged(@Nonnull final Collection<DataTreeCandidate> changes) {
LOG.trace("Data changed called to effective RIB. Change : {}", changes);
// we have a lot of transactions created for 'nothing' because a lot of changes
}
@Override
- public void close() {
+ public synchronized void close() {
this.reg.close();
this.prefixesReceived.values().forEach(LongAdder::reset);
this.prefixesInstalled.values().forEach(LongAdder::reset);
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
+import java.util.concurrent.Future;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
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.mdsal.singleton.common.api.ServiceGroupIdentifier;
import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode;
import org.opendaylight.protocol.bgp.mode.impl.base.BasePathSelectionModeFactory;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
import org.slf4j.LoggerFactory;
@ThreadSafe
-public final class RIBImpl extends BGPRIBStateImpl implements ClusterSingletonService, RIB, TransactionChainListener,
+public final class RIBImpl extends BGPRIBStateImpl implements RIB, TransactionChainListener,
SchemaContextListener, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(RIBImpl.class);
private static final QName RIB_ID_QNAME = QName.create(Rib.QNAME, "id").intern();
private final YangInstanceIdentifier yangRibId;
private final RIBSupportContextRegistryImpl ribContextRegistry;
private final CodecsRegistryImpl codecsRegistry;
- private final ServiceGroupIdentifier serviceGroupIdentifier;
- private final ClusterSingletonServiceProvider provider;
+ private ClusterSingletonServiceRegistration registration;
private final DOMDataBrokerExtension service;
private final Map<TransactionChain<?, ?>, LocRibWriter> txChainToLocRibWriter = new HashMap<>();
private final Map<TablesKey, PathSelectionMode> bestPathSelectionStrategies;
private final ImportPolicyPeerTracker importPolicyPeerTracker;
private final RibId ribId;
private final Map<TablesKey, ExportPolicyPeerTracker> exportPolicyPeerTrackerMap;
- private ClusterSingletonServiceRegistration registration;
+
private DOMTransactionChain domChain;
@GuardedBy("this")
private boolean isServiceInstantiated;
- public RIBImpl(final ClusterSingletonServiceProvider provider, final RibId ribId, final AsNumber localAs, final BgpId localBgpId,
+ public RIBImpl(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) {
+ @Nonnull final Map<TablesKey, PathSelectionMode> bestPathSelectionStrategies, final GeneratedClassLoadingStrategy classStrategy) {
super(InstanceIdentifier.create(BgpRib.class).child(Rib.class, new RibKey(requireNonNull(ribId))),
localBgpId, localAs);
this.localAs = requireNonNull(localAs);
this.ribId = ribId;
final PolicyDatabase policyDatabase = new PolicyDatabase(this.localAs.getValue(), localBgpId, cId);
this.importPolicyPeerTracker = new ImportPolicyPeerTrackerImpl(policyDatabase);
- this.serviceGroupIdentifier = ServiceGroupIdentifier.create(this.ribId.getValue() + "-service-group");
- requireNonNull(provider, "ClusterSingletonServiceProvider is null");
- this.provider = provider;
final ImmutableMap.Builder<TablesKey, ExportPolicyPeerTracker> exportPolicies = new ImmutableMap.Builder<>();
for (final BgpTableType t : this.localTables) {
exportPolicies.put(key, new ExportPolicyPeerTrackerImpl(policyDatabase, key));
}
this.exportPolicyPeerTrackerMap = exportPolicies.build();
- LOG.info("RIB Singleton Service {} registered, RIB {}", getIdentifier().getValue(), this.ribId.getValue());
- //this need to be always the last step
- this.registration = registerClusterSingletonService(this);
}
private void startLocRib(final TablesKey key) {
return this.exportPolicyPeerTrackerMap.get(tablesKey);
}
- @Override
public synchronized void instantiateServiceInstance() {
this.isServiceInstantiated = true;
setActive(true);
this.domChain = this.domDataBroker.createTransactionChain(this);
- LOG.info("RIB Singleton Service {} instantiated, RIB {}", getIdentifier().getValue(), this.ribId.getValue());
LOG.debug("Instantiating RIB table {} at {}", this.ribId, this.yangRibId);
final ContainerNode bgpRib = Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(BgpRib.QNAME))
this.localTablesKeys.forEach(this::startLocRib);
}
- @Override
public synchronized ListenableFuture<Void> closeServiceInstance() {
if (!this.isServiceInstantiated) {
- LOG.trace("RIB Singleton Service {} already closed, RIB {}", getIdentifier().getValue(),
- this.ribId.getValue());
+ LOG.trace("RIB {} already closed", this.ribId.getValue());
return Futures.immediateFuture(null);
}
- LOG.info("Close RIB Singleton Service {}, RIB {}", getIdentifier().getValue(), this.ribId.getValue());
+ LOG.info("Close RIB {}", this.ribId.getValue());
this.isServiceInstantiated = false;
setActive(false);
this.domChain.close();
return cleanFuture;
}
-
- @Override
- public ServiceGroupIdentifier getIdentifier() {
- return this.serviceGroupIdentifier;
- }
-
- @Override
- public ClusterSingletonServiceRegistration registerClusterSingletonService(
- final ClusterSingletonService clusterSingletonService) {
- return ClusterSingletonServiceRegistrationHelper
- .registerSingletonService(this.provider, clusterSingletonService);
- }
-
- @Override
- public ServiceGroupIdentifier getRibIServiceGroupIdentifier() {
- return getIdentifier();
- }
}
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
-import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
import org.opendaylight.protocol.bgp.rib.impl.ApplicationPeer;
import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
@Override
public synchronized void close() {
if (this.bgpAppPeerSingletonService != null) {
- try {
- this.bgpAppPeerSingletonService.close();
- this.bgpAppPeerSingletonService = null;
- } catch (final Exception e) {
- LOG.warn("Failed to close application peer instance", e);
- }
+ this.bgpAppPeerSingletonService = null;
}
if (this.serviceRegistration != null) {
this.serviceRegistration.unregister();
}
}
+ @Override
+ public synchronized void instantiateServiceInstance() {
+ if (this.bgpAppPeerSingletonService != null) {
+ this.bgpAppPeerSingletonService.instantiateServiceInstance();
+ }
+ }
+
@Override
public synchronized ListenableFuture<Void> closeServiceInstance() {
if (this.bgpAppPeerSingletonService != null) {
this.serviceRegistration = serviceRegistration;
}
- private final class BgpAppPeerSingletonService implements ClusterSingletonService, BGPPeerStateConsumer,
- AutoCloseable {
+ private final class BgpAppPeerSingletonService implements BGPPeerStateConsumer {
private final ApplicationPeer applicationPeer;
private final DOMDataTreeChangeService dataTreeChangeService;
private final ApplicationRibId appRibId;
- private final ServiceGroupIdentifier serviceGroupIdentifier;
- private ClusterSingletonServiceRegistration singletonServiceRegistration;
@GuardedBy("this")
private boolean isServiceInstantiated;
this.applicationPeer = new ApplicationPeer(appRibId, neighborAddress, rib);
this.appRibId = appRibId;
this.dataTreeChangeService = rib.getService();
- this.serviceGroupIdentifier = rib.getRibIServiceGroupIdentifier();
- LOG.info("Application Peer Singleton Service {} registered, Application peer {}",
- getIdentifier().getValue(), this.appRibId.getValue());
- //this need to be always the last step
- this.singletonServiceRegistration = rib.registerClusterSingletonService(this);
}
- @Override
- public void close() throws Exception {
- if (this.singletonServiceRegistration != null) {
- this.singletonServiceRegistration.close();
- this.singletonServiceRegistration = null;
- }
- }
-
- @Override
public synchronized void instantiateServiceInstance() {
this.isServiceInstantiated = true;
- LOG.info("Application Peer Singleton Service {} instantiated, Application peer {}",
- getIdentifier().getValue(), this.appRibId.getValue());
final YangInstanceIdentifier yangIId = YangInstanceIdentifier.builder().node(ApplicationRib.QNAME)
.nodeWithKey(ApplicationRib.QNAME, APP_ID_QNAME, this.appRibId.getValue())
.node(Tables.QNAME).node(Tables.QNAME).build();
new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, yangIId));
}
- @Override
public synchronized ListenableFuture<Void> closeServiceInstance() {
if (!this.isServiceInstantiated) {
- LOG.trace("Application Peer Singleton Service {} instance already closed, Application peer {}",
- getIdentifier().getValue(), this.appRibId.getValue());
+ LOG.trace("Application peer already closed {}", this.appRibId.getValue());
return Futures.immediateFuture(null);
}
- LOG.info("Application Peer Singleton Service {} instance closed, Application peer {}",
- getIdentifier().getValue(), this.appRibId.getValue());
+ LOG.info("Application peer instance closed {}", this.appRibId.getValue());
this.isServiceInstantiated = false;
return this.applicationPeer.close();
}
- @Override
- public ServiceGroupIdentifier getIdentifier() {
- return this.serviceGroupIdentifier;
- }
-
@Override
public BGPPeerState getPeerState() {
return this.applicationPeer.getPeerState();
--- /dev/null
+/*
+ * Copyright (c) 2017 AT&T Intellectual Property. 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.config;
+
+import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getNeighborInstanceIdentifier;
+import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getNeighborInstanceName;
+import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getRibInstanceName;
+
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.google.common.util.concurrent.SettableFuture;
+import java.util.ArrayList;
+import java.util.Dictionary;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+import javax.annotation.Nonnull;
+import javax.annotation.concurrent.GuardedBy;
+import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
+import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
+import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
+import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
+import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
+import org.opendaylight.protocol.bgp.rib.impl.spi.InstanceType;
+import org.opendaylight.protocol.bgp.rib.spi.util.ClusterSingletonServiceRegistrationHelper;
+import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.Neighbor;
+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.bgp.rev151009.bgp.top.bgp.Neighbors;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceRegistration;
+import org.osgi.service.blueprint.container.BlueprintContainer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public final class BGPClusterSingletonService implements ClusterSingletonService, AutoCloseable {
+
+ private static final Logger LOG = LoggerFactory.getLogger(BGPClusterSingletonService.class);
+
+ private static final long TIMEOUT_NS = TimeUnit.SECONDS.toNanos(5);
+ private final InstanceIdentifier<Bgp> bgpIid;
+ @GuardedBy("this")
+ private final Map<InstanceIdentifier<Neighbor>, PeerBean> peers = new HashMap<>();
+ private final BGPTableTypeRegistryConsumer tableTypeRegistry;
+ private final BlueprintContainer container;
+ private final BundleContext bundleContext;
+ private final ServiceGroupIdentifier serviceGroupIdentifier;
+ private final AtomicBoolean instantiated = new AtomicBoolean(false);
+ private RibImpl ribImpl;
+
+ BGPClusterSingletonService(
+ @Nonnull final ClusterSingletonServiceProvider provider,
+ @Nonnull final BGPTableTypeRegistryConsumer tableTypeRegistry,
+ @Nonnull final BlueprintContainer container,
+ @Nonnull final BundleContext bundleContext,
+ @Nonnull final InstanceIdentifier<Bgp> bgpIid) {
+ this.tableTypeRegistry = tableTypeRegistry;
+ this.container = container;
+ this.bundleContext = bundleContext;
+ this.bgpIid = bgpIid;
+ final String ribInstanceName = getRibInstanceName(bgpIid);
+ this.serviceGroupIdentifier = ServiceGroupIdentifier.create(ribInstanceName + "-service-group");
+ LOG.info("BGPClusterSingletonService {} registered", this.serviceGroupIdentifier.getValue());
+ ClusterSingletonServiceRegistrationHelper
+ .registerSingletonService(provider, this);
+ }
+
+ @Override
+ public synchronized void instantiateServiceInstance() {
+ if (this.ribImpl != null) {
+ this.ribImpl.instantiateServiceInstance();
+ this.peers.values().forEach(PeerBean::instantiateServiceInstance);
+ }
+ this.instantiated.set(true);
+ LOG.info("BGPClusterSingletonService {} instantiated", this.serviceGroupIdentifier.getValue());
+ }
+
+ @Override
+ public synchronized ListenableFuture<Void> closeServiceInstance() {
+ LOG.info("BGPClusterSingletonService {} close service instance", this.serviceGroupIdentifier.getValue());
+ this.instantiated.set(false);
+
+ final List<ListenableFuture<Void>> futurePeerCloseList = this.peers.values().stream()
+ .map(PeerBean::closeServiceInstance).collect(Collectors.toList());
+ final SettableFuture<Void> done = SettableFuture.create();
+ Futures.addCallback(Futures.allAsList(futurePeerCloseList), new FutureCallback<List<Void>>() {
+ @Override
+ public void onSuccess(final List<Void> result) {
+ done.setFuture(BGPClusterSingletonService.this.ribImpl.closeServiceInstance());
+ }
+
+ @Override
+ public void onFailure(final Throwable throwable) {
+ LOG.warn("Failed removing peers {}", throwable);
+ }
+ }, MoreExecutors.directExecutor());
+ return done;
+ }
+
+ @Nonnull
+ @Override
+ public ServiceGroupIdentifier getIdentifier() {
+ return this.serviceGroupIdentifier;
+ }
+
+ synchronized void onGlobalChanged(final DataObjectModification<Global> dataObjectModification) {
+ switch (dataObjectModification.getModificationType()) {
+ case DELETE:
+ LOG.debug("Removing RIB instance: {}", this.bgpIid);
+ if (this.ribImpl != null) {
+ LOG.debug("RIB instance removed {}", this.ribImpl);
+ closeAllBindedPeers();
+ closeRibService();
+ }
+ break;
+ case SUBTREE_MODIFIED:
+ case WRITE:
+ final Global global = dataObjectModification.getDataAfter();
+ if (this.ribImpl == null) {
+ onGlobalCreated(global);
+ } else if (!this.ribImpl.isGlobalEqual(global)) {
+ onGlobalUpdated(global);
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ private synchronized void onGlobalCreated(final Global global) {
+ LOG.debug("Creating RIB instance with configuration: {}", global);
+ this.ribImpl = (RibImpl) this.container.getComponentInstance(InstanceType.RIB.getBeanName());
+ initiateRibInstance(global, this.ribImpl);
+ LOG.debug("RIB instance created: {}", this.ribImpl);
+ }
+
+ private synchronized void onGlobalUpdated(final Global global) {
+ LOG.debug("Modifying RIB instance with configuration: {}", global);
+ final List<PeerBean> closedPeers = closeAllBindedPeers();
+ closeRibService();
+ initiateRibInstance(global, this.ribImpl);
+ closedPeers.forEach(peer -> peer.restart(this.ribImpl, this.tableTypeRegistry));
+ if (this.instantiated.get()) {
+ closedPeers.forEach(PeerBean::instantiateServiceInstance);
+ }
+ LOG.debug("RIB instance created: {}", this.ribImpl);
+ }
+
+ private void closeRibService() {
+ try {
+ this.ribImpl.closeServiceInstance().get(TIMEOUT_NS, TimeUnit.NANOSECONDS);
+ } catch (final Exception e) {
+ LOG.error("RIB instance failed to close service instance", e);
+ }
+ this.ribImpl.close();
+ }
+
+ private synchronized void initiateRibInstance(final Global global, final RibImpl ribImpl) {
+ final String ribInstanceName = getRibInstanceName(this.bgpIid);
+ ribImpl.start(global, ribInstanceName, this.tableTypeRegistry);
+ registerRibInstance(ribImpl, ribInstanceName);
+ if (this.instantiated.get()) {
+ this.ribImpl.instantiateServiceInstance();
+ }
+ }
+
+ private synchronized List<PeerBean> closeAllBindedPeers() {
+ final List<PeerBean> filtered = new ArrayList<>();
+ this.peers.forEach((key, peer) -> {
+ try {
+ peer.closeServiceInstance().get();
+ } catch (final Exception e) {
+ LOG.error("Peer instance failed to close service instance", e);
+ }
+ peer.close();
+ filtered.add(peer);
+ });
+ return filtered;
+ }
+
+ private synchronized void registerRibInstance(final RibImpl ribImpl, final String ribInstanceName) {
+ final Dictionary<String, String> properties = new Hashtable<>();
+ properties.put(InstanceType.RIB.getBeanName(), ribInstanceName);
+ final ServiceRegistration<?> serviceRegistration = this.bundleContext.registerService(
+ InstanceType.RIB.getServices(), ribImpl, properties);
+ ribImpl.setServiceRegistration(serviceRegistration);
+ }
+
+ @Override
+ public void close() throws Exception {
+ LOG.info("BGPClusterSingletonService {} close", this.serviceGroupIdentifier.getValue());
+ this.peers.values().iterator().forEachRemaining(PeerBean::close);
+ this.ribImpl.close();
+ this.peers.clear();
+ this.ribImpl = null;
+ }
+
+ synchronized void onNeighborsChanged(final DataObjectModification<Neighbors> dataObjectModification) {
+ for (final DataObjectModification<? extends DataObject> neighborModification :
+ dataObjectModification.getModifiedChildren()) {
+ switch (neighborModification.getModificationType()) {
+ case DELETE:
+ onNeighborRemoved((Neighbor) neighborModification.getDataBefore());
+ break;
+ case SUBTREE_MODIFIED:
+ case WRITE:
+ onNeighborModified((Neighbor) neighborModification.getDataAfter());
+ break;
+ default:
+ break;
+ }
+ }
+ }
+
+ private synchronized void onNeighborModified(final Neighbor neighbor) {
+ //restart peer instance with a new configuration
+ final PeerBean bgpPeer = this.peers.get(getNeighborInstanceIdentifier(this.bgpIid, neighbor.getKey()));
+ if (bgpPeer == null) {
+ onNeighborCreated(neighbor);
+ } else if (!bgpPeer.containsEqualConfiguration(neighbor)) {
+ onNeighborUpdated(bgpPeer, neighbor);
+ }
+ }
+
+
+ private synchronized void onNeighborCreated(final Neighbor neighbor) {
+ LOG.debug("Creating Peer instance with configuration: {}", neighbor);
+ final PeerBean bgpPeer;
+ if (OpenConfigMappingUtil.isApplicationPeer(neighbor)) {
+ bgpPeer = (PeerBean) this.container.getComponentInstance(InstanceType.APP_PEER.getBeanName());
+ } else {
+ bgpPeer = (PeerBean) this.container.getComponentInstance(InstanceType.PEER.getBeanName());
+ }
+ final InstanceIdentifier<Neighbor> neighborInstanceIdentifier =
+ getNeighborInstanceIdentifier(this.bgpIid, neighbor.getKey());
+ initiatePeerInstance(neighborInstanceIdentifier, neighbor, bgpPeer);
+ this.peers.put(neighborInstanceIdentifier, bgpPeer);
+ LOG.debug("Peer instance created {}", bgpPeer);
+ }
+
+ private synchronized void onNeighborUpdated(final PeerBean bgpPeer, final Neighbor neighbor) {
+ LOG.debug("Updating Peer instance with configuration: {}", neighbor);
+ closePeer(bgpPeer);
+
+ final InstanceIdentifier<Neighbor> neighborInstanceIdentifier = getNeighborInstanceIdentifier(this.bgpIid,
+ neighbor.getKey());
+ initiatePeerInstance(neighborInstanceIdentifier, neighbor, bgpPeer);
+ LOG.debug("Peer instance updated {}", bgpPeer);
+ }
+
+ private void closePeer(final PeerBean bgpPeer) {
+ if (bgpPeer != null) {
+ try {
+ bgpPeer.closeServiceInstance().get();
+ bgpPeer.close();
+ LOG.debug("Peer instance closed {}", bgpPeer);
+ } catch (final Exception e) {
+ LOG.error("Peer instance failed to close service instance", e);
+ }
+ }
+ }
+
+ private synchronized void onNeighborRemoved(final Neighbor neighbor) {
+ LOG.debug("Removing Peer instance: {}", neighbor);
+ final PeerBean bgpPeer = this.peers.remove(getNeighborInstanceIdentifier(this.bgpIid, neighbor.getKey()));
+ closePeer(bgpPeer);
+ }
+
+ private synchronized void registerPeerInstance(final BgpPeer bgpPeer, final String peerInstanceName) {
+ final Dictionary<String, String> properties = new Hashtable<>();
+ properties.put(InstanceType.PEER.getBeanName(), peerInstanceName);
+ final ServiceRegistration<?> serviceRegistration = this.bundleContext
+ .registerService(InstanceType.PEER.getServices(), bgpPeer, properties);
+ bgpPeer.setServiceRegistration(serviceRegistration);
+ }
+
+ private synchronized void registerAppPeerInstance(final AppPeer appPeer, final String peerInstanceName) {
+ final Dictionary<String, String> properties = new Hashtable<>();
+ properties.put(InstanceType.PEER.getBeanName(), peerInstanceName);
+ final ServiceRegistration<?> serviceRegistration = this.bundleContext
+ .registerService(InstanceType.APP_PEER.getServices(), appPeer, properties);
+ appPeer.setServiceRegistration(serviceRegistration);
+ }
+
+ private synchronized void initiatePeerInstance(final InstanceIdentifier<Neighbor> neighborIdentifier,
+ final Neighbor neighbor, final PeerBean bgpPeer) {
+ final String peerInstanceName = getNeighborInstanceName(neighborIdentifier);
+ if (this.ribImpl != null) {
+ bgpPeer.start(this.ribImpl, neighbor, this.tableTypeRegistry);
+ if (bgpPeer instanceof BgpPeer) {
+ registerPeerInstance((BgpPeer) bgpPeer, peerInstanceName);
+ } else if (bgpPeer instanceof AppPeer) {
+ registerAppPeerInstance((AppPeer) bgpPeer, peerInstanceName);
+ }
+ }
+ if (this.instantiated.get()) {
+ bgpPeer.instantiateServiceInstance();
+ }
+ }
+}
package org.opendaylight.protocol.bgp.rib.impl.config;
-import static com.google.common.util.concurrent.Futures.transform;
import static java.util.Objects.requireNonNull;
-import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getNeighborInstanceIdentifier;
-import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getNeighborInstanceName;
-import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getRibInstanceName;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
-import java.util.ArrayList;
import java.util.Collection;
-import java.util.Dictionary;
import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.List;
import java.util.Map;
-import java.util.stream.Collectors;
import javax.annotation.concurrent.GuardedBy;
import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
-import org.opendaylight.protocol.bgp.rib.impl.spi.InstanceType;
-import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.Neighbor;
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.bgp.rev151009.bgp.top.bgp.Neighbors;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
import org.osgi.service.blueprint.container.BlueprintContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final BlueprintContainer container;
private final BundleContext bundleContext;
private final BGPTableTypeRegistryConsumer tableTypeRegistry;
+ private final ClusterSingletonServiceProvider provider;
+ private ListenerRegistration<BgpDeployerImpl> registration;
@GuardedBy("this")
- private final Map<InstanceIdentifier<Bgp>, RibImpl> ribs = new HashMap<>();
- @GuardedBy("this")
- private final Map<InstanceIdentifier<Neighbor>, PeerBean> peers = new HashMap<>();
+ private final Map<InstanceIdentifier<Bgp>, BGPClusterSingletonService> bgpCss = new HashMap<>();
private final DataBroker dataBroker;
- private ListenerRegistration<BgpDeployerImpl> registration;
+ private final String networkInstanceName;
@GuardedBy("this")
private boolean closed;
- public BgpDeployerImpl(final String networkInstanceName, final BlueprintContainer container,
+ public BgpDeployerImpl(final String networkInstanceName, final ClusterSingletonServiceProvider provider,
+ final BlueprintContainer container,
final BundleContext bundleContext, final DataBroker dataBroker,
final BGPTableTypeRegistryConsumer mappingService) {
this.dataBroker = requireNonNull(dataBroker);
+ this.provider = requireNonNull(provider);
+ this.networkInstanceName = requireNonNull(networkInstanceName);
this.container = requireNonNull(container);
this.bundleContext = requireNonNull(bundleContext);
this.tableTypeRegistry = requireNonNull(mappingService);
this.networkInstanceIId = InstanceIdentifier.create(NetworkInstances.class)
.child(NetworkInstance.class, new NetworkInstanceKey(networkInstanceName));
- }
-
- private static ListenableFuture<Void> initializeNetworkInstance(
- final DataBroker dataBroker, final InstanceIdentifier<NetworkInstance> networkInstance) {
- final WriteTransaction wTx = dataBroker.newWriteOnlyTransaction();
- wTx.merge(LogicalDatastoreType.CONFIGURATION, networkInstance,
- new NetworkInstanceBuilder().setName(networkInstance.firstKeyOf(NetworkInstance.class).getName())
- .setProtocols(new ProtocolsBuilder().build()).build());
- return wTx.submit();
- }
-
- public synchronized void init() {
Futures.addCallback(initializeNetworkInstance(dataBroker, this.networkInstanceIId), new FutureCallback<Void>() {
@Override
public void onSuccess(final Void result) {
- LOG.debug("Network Instance {} initialized successfully.", BgpDeployerImpl.this.networkInstanceIId);
+ LOG.debug("Network Instance {} initialized successfully.", networkInstanceName);
}
@Override
public void onFailure(final Throwable t) {
- LOG.error("Failed to initialize Network Instance {}.", BgpDeployerImpl.this.networkInstanceIId, t);
+ LOG.error("Failed to initialize Network Instance {}.", networkInstanceName, t);
}
}, MoreExecutors.directExecutor());
- this.registration = dataBroker.registerDataTreeChangeListener(
- new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, this.networkInstanceIId.child(Protocols.class)
- .child(Protocol.class).augmentation(Protocol1.class).child(Bgp.class)), this);
- LOG.info("BGP Deployer {} started.", BgpDeployerImpl.this.networkInstanceIId);
+ }
+
+ public synchronized void init() {
+ this.registration = this.dataBroker.registerDataTreeChangeListener(
+ new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
+ this.networkInstanceIId.child(Protocols.class)
+ .child(Protocol.class).augmentation(Protocol1.class).child(Bgp.class)), this);
+ LOG.info("BGP Deployer {} started.", this.networkInstanceName);
}
@Override
final InstanceIdentifier<Bgp> rootIdentifier = dataTreeModification.getRootPath().getRootIdentifier();
final DataObjectModification<Bgp> rootNode = dataTreeModification.getRootNode();
LOG.trace("BGP configuration has changed: {}", rootNode);
- for (final DataObjectModification<? extends DataObject> dataObjectModification : rootNode.getModifiedChildren()) {
+ for (final DataObjectModification<? extends DataObject> dataObjectModification :
+ rootNode.getModifiedChildren()) {
if (dataObjectModification.getDataType().equals(Global.class)) {
onGlobalChanged((DataObjectModification<Global>) dataObjectModification, rootIdentifier);
} else if (dataObjectModification.getDataType().equals(Neighbors.class)) {
}
}
- @VisibleForTesting
- public InstanceIdentifier<NetworkInstance> getInstanceIdentifier() {
- return this.networkInstanceIId;
- }
-
@Override
public synchronized void close() throws Exception {
LOG.info("Closing BGP Deployer.");
}
this.closed = true;
- final List<ListenableFuture<Void>> futurePeerCloseList = this.peers.values().stream()
- .map(PeerBean::closeServiceInstance).collect(Collectors.toList());
- final ListenableFuture<List<Void>> futureOfRelevance = Futures.allAsList(futurePeerCloseList);
-
- final ListenableFuture<ListenableFuture<List<Void>>> maxRelevanceFuture = transform(futureOfRelevance,
- futurePeersClose -> {
- this.peers.values().forEach(PeerBean::close);
- BgpDeployerImpl.this.peers.clear();
-
- final List<ListenableFuture<Void>> futureRIBCloseList = BgpDeployerImpl.this.ribs.values().stream()
- .map(RibImpl::closeServiceInstance).collect(Collectors.toList());
- return Futures.allAsList(futureRIBCloseList);
- }, MoreExecutors.directExecutor());
-
- final ListenableFuture<Void> ribFutureClose = transform(maxRelevanceFuture, futurePeersClose -> {
- BgpDeployerImpl.this.ribs.values().forEach(RibImpl::close);
- this.ribs.clear();
- return null;
- }, MoreExecutors.directExecutor());
-
- ribFutureClose.get();
- }
-
- private synchronized void onGlobalChanged(final DataObjectModification<Global> dataObjectModification,
- final InstanceIdentifier<Bgp> rootIdentifier) {
- switch (dataObjectModification.getModificationType()) {
- case DELETE:
- onGlobalRemoved(rootIdentifier);
- break;
- case SUBTREE_MODIFIED:
- case WRITE:
- onGlobalModified(rootIdentifier, dataObjectModification.getDataAfter());
- break;
- default:
- break;
- }
- }
-
- @VisibleForTesting
- synchronized void onGlobalModified(final InstanceIdentifier<Bgp> rootIdentifier, final Global global) {
- final RibImpl ribImpl = this.ribs.get(rootIdentifier);
- if (ribImpl == null) {
- onGlobalCreated(rootIdentifier, global);
- } else if (!ribImpl.isGlobalEqual(global)) {
- onGlobalUpdated(rootIdentifier, global, ribImpl);
- }
- }
-
- private synchronized List<PeerBean> closeAllBindedPeers(final InstanceIdentifier<Bgp> rootIdentifier) {
- final List<PeerBean> filtered = new ArrayList<>();
- this.peers.entrySet().stream().filter(entry -> entry.getKey().firstIdentifierOf(Bgp.class)
- .contains(rootIdentifier)).forEach(entry -> {
- final PeerBean peer = entry.getValue();
+ this.bgpCss.values().iterator().forEachRemaining(service -> {
try {
- peer.closeServiceInstance().get();
- } catch (final Exception e) {
- LOG.error("Peer instance failed to close service instance", e);
+ service.close();
+ } catch (Exception e) {
+ LOG.warn("Failed to close BGP Cluster Singleton Service.");
}
- peer.close();
- filtered.add(peer);
});
- return filtered;
- }
- private synchronized void onGlobalCreated(final InstanceIdentifier<Bgp> rootIdentifier, final Global global) {
- LOG.debug("Creating RIB instance with configuration: {}", global);
- final RibImpl ribImpl = (RibImpl) this.container.getComponentInstance(InstanceType.RIB.getBeanName());
- initiateRibInstance(rootIdentifier, global, ribImpl);
- this.ribs.put(rootIdentifier, ribImpl);
- LOG.debug("RIB instance created: {}", ribImpl);
}
- private synchronized void onGlobalUpdated(final InstanceIdentifier<Bgp> rootIdentifier, final Global global,
- final RibImpl ribImpl) {
- LOG.debug("Modifying RIB instance with configuration: {}", global);
- final List<PeerBean> closedPeers = closeAllBindedPeers(rootIdentifier);
- try {
- ribImpl.closeServiceInstance().get();
- } catch (final Exception e) {
- LOG.error("RIB instance failed to close service instance", e);
- }
- ribImpl.close();
- initiateRibInstance(rootIdentifier, global, ribImpl);
- closedPeers.forEach(peer -> peer.restart(ribImpl, this.tableTypeRegistry));
- LOG.debug("RIB instance created: {}", ribImpl);
+ private static ListenableFuture<Void> initializeNetworkInstance(
+ final DataBroker dataBroker, final InstanceIdentifier<NetworkInstance> networkInstance) {
+ final WriteTransaction wTx = dataBroker.newWriteOnlyTransaction();
+ wTx.merge(LogicalDatastoreType.CONFIGURATION, networkInstance,
+ new NetworkInstanceBuilder().setName(networkInstance.firstKeyOf(NetworkInstance.class).getName())
+ .setProtocols(new ProtocolsBuilder().build()).build());
+ return wTx.submit();
}
@VisibleForTesting
- synchronized void onGlobalRemoved(final InstanceIdentifier<Bgp> rootIdentifier) {
- LOG.debug("Removing RIB instance: {}", rootIdentifier);
- final RibImpl ribImpl = this.ribs.remove(rootIdentifier);
- if (ribImpl != null) {
- LOG.debug("RIB instance removed {}", ribImpl);
- closeAllBindedPeers(rootIdentifier);
- ribImpl.closeServiceInstance();
- ribImpl.close();
- }
- }
-
- private synchronized void registerRibInstance(final RibImpl ribImpl, final String ribInstanceName) {
- final Dictionary<String, String> properties = new Hashtable<>();
- properties.put(InstanceType.RIB.getBeanName(), ribInstanceName);
- final ServiceRegistration<?> serviceRegistration = this.bundleContext.registerService(
- InstanceType.RIB.getServices(), ribImpl, properties);
- ribImpl.setServiceRegistration(serviceRegistration);
- }
-
- private synchronized void initiateRibInstance(final InstanceIdentifier<Bgp> rootIdentifier, final Global global,
- final RibImpl ribImpl) {
- final String ribInstanceName = getRibInstanceName(rootIdentifier);
- ribImpl.start(global, ribInstanceName, this.tableTypeRegistry);
- registerRibInstance(ribImpl, ribInstanceName);
- }
-
- private synchronized void onNeighborsChanged(final DataObjectModification<Neighbors> dataObjectModification,
+ synchronized void onGlobalChanged(final DataObjectModification<Global> dataObjectModification,
final InstanceIdentifier<Bgp> rootIdentifier) {
- for (final DataObjectModification<? extends DataObject> neighborModification : dataObjectModification.getModifiedChildren()) {
- switch (neighborModification.getModificationType()) {
- case DELETE:
- onNeighborRemoved(rootIdentifier, (Neighbor) neighborModification.getDataBefore());
- break;
- case SUBTREE_MODIFIED:
- case WRITE:
- onNeighborModified(rootIdentifier, (Neighbor) neighborModification.getDataAfter());
- break;
- default:
- break;
- }
+ BGPClusterSingletonService old = this.bgpCss.get(rootIdentifier);
+ if (old == null) {
+ old = new BGPClusterSingletonService(this.provider, this.tableTypeRegistry, this.container,
+ this.bundleContext, rootIdentifier);
+ this.bgpCss.put(rootIdentifier, old);
}
+ old.onGlobalChanged(dataObjectModification);
}
@VisibleForTesting
- synchronized void onNeighborModified(final InstanceIdentifier<Bgp> rootIdentifier, final Neighbor neighbor) {
- //restart peer instance with a new configuration
- final PeerBean bgpPeer = this.peers.get(getNeighborInstanceIdentifier(rootIdentifier, neighbor.getKey()));
- if (bgpPeer == null) {
- onNeighborCreated(rootIdentifier, neighbor);
- } else if (!bgpPeer.containsEqualConfiguration(neighbor)) {
- onNeighborUpdated(bgpPeer, rootIdentifier, neighbor);
- }
- }
-
- private synchronized void onNeighborCreated(final InstanceIdentifier<Bgp> rootIdentifier, final Neighbor neighbor) {
- LOG.debug("Creating Peer instance with configuration: {}", neighbor);
- final PeerBean bgpPeer;
- if (OpenConfigMappingUtil.isApplicationPeer(neighbor)) {
- bgpPeer = (PeerBean) this.container.getComponentInstance(InstanceType.APP_PEER.getBeanName());
- } else {
- bgpPeer = (PeerBean) this.container.getComponentInstance(InstanceType.PEER.getBeanName());
- }
- final InstanceIdentifier<Neighbor> neighborInstanceIdentifier =
- getNeighborInstanceIdentifier(rootIdentifier, neighbor.getKey());
- initiatePeerInstance(rootIdentifier, neighborInstanceIdentifier, neighbor, bgpPeer);
- this.peers.put(neighborInstanceIdentifier, bgpPeer);
- LOG.debug("Peer instance created {}", bgpPeer);
- }
-
- private synchronized void onNeighborUpdated(final PeerBean bgpPeer, final InstanceIdentifier<Bgp> rootIdentifier,
- final Neighbor neighbor) {
- LOG.debug("Updating Peer instance with configuration: {}", neighbor);
- bgpPeer.close();
- final InstanceIdentifier<Neighbor> neighborInstanceIdentifier =
- getNeighborInstanceIdentifier(rootIdentifier, neighbor.getKey());
- initiatePeerInstance(rootIdentifier, neighborInstanceIdentifier, neighbor, bgpPeer);
- LOG.debug("Peer instance updated {}", bgpPeer);
- }
-
- @VisibleForTesting
- synchronized void onNeighborRemoved(final InstanceIdentifier<Bgp> rootIdentifier, final Neighbor neighbor) {
- LOG.debug("Removing Peer instance: {}", rootIdentifier);
- final PeerBean bgpPeer = this.peers.remove(getNeighborInstanceIdentifier(rootIdentifier, neighbor.getKey()));
- if (bgpPeer != null) {
- bgpPeer.close();
- LOG.debug("Peer instance removed {}", bgpPeer);
+ synchronized void onNeighborsChanged(final DataObjectModification<Neighbors> dataObjectModification,
+ final InstanceIdentifier<Bgp> rootIdentifier) {
+ BGPClusterSingletonService old = this.bgpCss.get(rootIdentifier);
+ if (old == null) {
+ old = new BGPClusterSingletonService(this.provider, this.tableTypeRegistry, this.container,
+ this.bundleContext, rootIdentifier);
+ this.bgpCss.put(rootIdentifier, old);
}
+ old.onNeighborsChanged(dataObjectModification);
}
- private synchronized void registerPeerInstance(final BgpPeer bgpPeer, final String peerInstanceName) {
- final Dictionary<String, String> properties = new Hashtable<>();
- properties.put(InstanceType.PEER.getBeanName(), peerInstanceName);
- final ServiceRegistration<?> serviceRegistration = this.bundleContext
- .registerService(InstanceType.PEER.getServices(), bgpPeer, properties);
- bgpPeer.setServiceRegistration(serviceRegistration);
- }
-
- private synchronized void registerAppPeerInstance(final AppPeer appPeer, final String peerInstanceName) {
- final Dictionary<String, String> properties = new Hashtable<>();
- properties.put(InstanceType.PEER.getBeanName(), peerInstanceName);
- final ServiceRegistration<?> serviceRegistration = this.bundleContext
- .registerService(InstanceType.APP_PEER.getServices(), appPeer, properties);
- appPeer.setServiceRegistration(serviceRegistration);
- }
-
- private synchronized void initiatePeerInstance(final InstanceIdentifier<Bgp> rootIdentifier,
- final InstanceIdentifier<Neighbor> neighborIdentifier, final Neighbor neighbor,
- final PeerBean bgpPeer) {
- final String peerInstanceName = getNeighborInstanceName(neighborIdentifier);
- final RibImpl rib = this.ribs.get(rootIdentifier);
- if (rib != null) {
- bgpPeer.start(rib, neighbor, this.tableTypeRegistry);
- if (bgpPeer instanceof BgpPeer) {
- registerPeerInstance((BgpPeer) bgpPeer, peerInstanceName);
- } else if (bgpPeer instanceof AppPeer) {
- registerAppPeerInstance((AppPeer) bgpPeer, peerInstanceName);
- }
- }
- }
@VisibleForTesting
BGPTableTypeRegistryConsumer getTableTypeRegistry() {
import java.util.Set;
import javax.annotation.concurrent.GuardedBy;
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.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
import org.opendaylight.protocol.bgp.parser.spi.MultiprotocolCapabilitiesUtil;
final List<AddressFamilies> addPathCapability = OpenConfigMappingUtil
.toAddPathCapability(afiSafi, tableTypeRegistry);
if (!addPathCapability.isEmpty()) {
- caps.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder()
- .addAugmentation(CParameters1.class, new CParameters1Builder().setAddPathCapability(
- new AddPathCapabilityBuilder().setAddressFamilies(addPathCapability)
- .build()).build()).build()).build());
+ caps.add(new OptionalCapabilitiesBuilder()
+ .setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class,
+ new CParameters1Builder().setAddPathCapability(
+ new AddPathCapabilityBuilder()
+ .setAddressFamilies(addPathCapability).build()).build()).build()).build());
}
final List<BgpTableType> tableTypes = OpenConfigMappingUtil.toTableTypes(afiSafi, tableTypeRegistry);
for (final BgpTableType tableType : tableTypes) {
if (!rib.getLocalTables().contains(tableType)) {
- LOG.info("RIB instance does not list {} in its local tables. Incoming data will be dropped.",
- tableType);
+ LOG.info("RIB instance does not list {} " +
+ "in its local tables. Incoming data will be dropped.", tableType);
}
caps.add(new OptionalCapabilitiesBuilder().setCParameters(
}
}
+ @Override
+ public synchronized void instantiateServiceInstance() {
+ if (this.bgpPeerSingletonService != null) {
+ this.bgpPeerSingletonService.instantiateServiceInstance();
+ }
+ }
+
@Override
public synchronized ListenableFuture<Void> closeServiceInstance() {
if (this.bgpPeerSingletonService != null) {
this.serviceRegistration = serviceRegistration;
}
- private final class BgpPeerSingletonService implements BGPPeerStateConsumer, ClusterSingletonService,
- AutoCloseable {
- private final ServiceGroupIdentifier serviceGroupIdentifier;
+ private final class BgpPeerSingletonService implements BGPPeerStateConsumer, AutoCloseable {
private final boolean activeConnection;
private final BGPDispatcher dispatcher;
private final InetSocketAddress inetAddress;
private final int retryTimer;
private final KeyMapping keys;
+ private ClusterSingletonServiceRegistration registration;
private final BGPPeer bgpPeer;
private final IpAddress neighborAddress;
private final BGPSessionPreferences prefs;
- private ClusterSingletonServiceRegistration registration;
private Future<Void> connection;
@GuardedBy("this")
private boolean isServiceInstantiated;
final Set<TablesKey> afiSafisAdvertized = OpenConfigMappingUtil
.toTableKey(afisSAfis.getAfiSafi(), tableTypeRegistry);
this.bgpPeer = new BGPPeer(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));
this.activeConnection = OpenConfigMappingUtil.isActive(neighbor);
this.dispatcher = rib.getDispatcher();
- this.inetAddress = Ipv4Util.toInetSocketAddress(this.neighborAddress, OpenConfigMappingUtil.getPort(neighbor));
+ this.inetAddress = Ipv4Util.toInetSocketAddress(this.neighborAddress,
+ OpenConfigMappingUtil.getPort(neighbor));
this.retryTimer = OpenConfigMappingUtil.getRetryTimer(neighbor);
this.keys = keyMapping;
- this.serviceGroupIdentifier = rib.getRibIServiceGroupIdentifier();
- LOG.info("Peer Singleton Service {} registered", this.serviceGroupIdentifier.getValue());
- //this need to be always the last step
- this.registration = rib.registerClusterSingletonService(this);
}
@Override
}
}
- @Override
- public synchronized void instantiateServiceInstance() {
+ private synchronized void instantiateServiceInstance() {
this.isServiceInstantiated = true;
- LOG.info("Peer Singleton Service {} instantiated, Peer {}", getIdentifier().getValue(),
- this.neighborAddress);
+ LOG.info("Peer instantiated {}", this.neighborAddress);
this.bgpPeer.instantiateServiceInstance();
this.dispatcher.getBGPPeerRegistry().addPeer(this.neighborAddress, this.bgpPeer, this.prefs);
if (this.activeConnection) {
}
}
- @Override
- public synchronized ListenableFuture<Void> closeServiceInstance() {
+ private synchronized ListenableFuture<Void> closeServiceInstance() {
if (!this.isServiceInstantiated) {
- LOG.info("Peer Singleton Service {} already closed, Peer {}", getIdentifier().getValue(),
- this.neighborAddress);
+ LOG.info("Peer {} already closed", this.neighborAddress);
return Futures.immediateFuture(null);
}
- LOG.info("Close Peer Singleton Service {}, Peer {}", getIdentifier().getValue(), this.neighborAddress);
+ LOG.info("Close Peer {}", this.neighborAddress);
this.isServiceInstantiated = false;
if (this.connection != null) {
this.connection.cancel(true);
return future;
}
- @Override
- public ServiceGroupIdentifier getIdentifier() {
- return this.serviceGroupIdentifier;
- }
-
@Override
public BGPPeerState getPeerState() {
return this.bgpPeer.getPeerState();
@Override
void close();
+ void instantiateServiceInstance();
+
ListenableFuture<Void> closeServiceInstance();
Boolean containsEqualConfiguration(Neighbor neighbor);
package org.opendaylight.protocol.bgp.rib.impl.config;
-import static java.util.Objects.requireNonNull;
import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getAfiSafiWithDefault;
import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.getClusterIdentifier;
import static org.opendaylight.protocol.bgp.rib.impl.config.OpenConfigMappingUtil.toTableTypes;
import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
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.mdsal.singleton.common.api.ServiceGroupIdentifier;
import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
import org.opendaylight.protocol.bgp.rib.impl.RIBImpl;
private RIBImpl ribImpl;
private ServiceRegistration<?> serviceRegistration;
private ListenerRegistration<SchemaContextListener> schemaContextRegistration;
- private final ClusterSingletonServiceProvider provider;
private List<AfiSafi> afiSafi;
private AsNumber asNumber;
private Ipv4Address routerId;
private ClusterIdentifier clusterId;
- public RibImpl(final ClusterSingletonServiceProvider provider, final RIBExtensionConsumerContext contextProvider,
- final BGPDispatcher dispatcher, final BindingCodecTreeFactory codecTreeFactory, final DOMDataBroker domBroker,
+ public RibImpl(final RIBExtensionConsumerContext contextProvider, final BGPDispatcher dispatcher,
+ final BindingCodecTreeFactory codecTreeFactory, final DOMDataBroker domBroker,
final DOMSchemaService domSchemaService) {
- this.provider = requireNonNull(provider);
this.extensions = contextProvider;
this.dispatcher = dispatcher;
this.codecTreeFactory = codecTreeFactory;
return this.ribImpl.getService();
}
- public ListenableFuture<Void> closeServiceInstance() {
+ ListenableFuture<Void> closeServiceInstance() {
if (this.ribImpl != null) {
return this.ribImpl.closeServiceInstance();
}
return this.ribImpl.getLocalTablesKeys();
}
- @Override
- public ServiceGroupIdentifier getRibIServiceGroupIdentifier() {
- return this.ribImpl.getRibIServiceGroupIdentifier();
- }
-
@Override
public String toString() {
return this.ribImpl != null ? this.ribImpl.toString() : null;
.stream()
.collect(Collectors.toMap(entry ->
new TablesKey(entry.getKey().getAfi(), entry.getKey().getSafi()), Map.Entry::getValue));
- return new RIBImpl(this.provider,
+ return new RIBImpl(
new RibId(bgpInstanceName),
this.asNumber,
new BgpId(this.routerId),
this.extensions.getClassLoadingStrategy());
}
- @Override
- public ClusterSingletonServiceRegistration registerClusterSingletonService(
- final ClusterSingletonService clusterSingletonService) {
- return this.ribImpl.registerClusterSingletonService(clusterSingletonService);
- }
-
@Override
public BGPRIBState getRIBState() {
return this.ribImpl.getRIBState();
}
+
+ public void instantiateServiceInstance() {
+ if (this.ribImpl != null) {
+ this.ribImpl.instantiateServiceInstance();
+ }
+ }
}
/**
* Internal reference to a RIB instance.
*/
-public interface RIB extends RibReference, ClusterSingletonServiceProvider {
+public interface RIB extends RibReference {
AsNumber getLocalAs();
BgpId getBgpIdentifier();
ExportPolicyPeerTracker getExportPolicyPeerTracker(TablesKey tablesKey);
Set<TablesKey> getLocalTablesKeys();
-
- /**
- * Return common ServiceGroupIdentifier to be used between same group cluster service
- *
- * @return ServiceGroupIdentifier
- */
- ServiceGroupIdentifier getRibIServiceGroupIdentifier();
}
init-method="init"
destroy-method="close">
<argument value="global-bgp"/>
+ <argument ref="clusterSingletonServiceProvider"/>
<argument ref="blueprintContainer"/>
<argument ref="blueprintBundleContext"/>
<argument ref="dataBroker"/>
</bean>
<bean id="ribImpl" class="org.opendaylight.protocol.bgp.rib.impl.config.RibImpl" scope="prototype">
- <argument ref="clusterSingletonServiceProvider"/>
<argument ref="globalBgpExtensions"/>
<argument ref="BGPDispatcher"/>
<argument ref="codecTreeFactory"/>
package org.opendaylight.protocol.bgp.rib.impl;
import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doCallRealMethod;
+import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
import org.junit.After;
import org.junit.Before;
import org.mockito.Mock;
-import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
protected static final Class<? extends AddressFamily> AFI = Ipv4AddressFamily.class;
protected static final Class<? extends SubsequentAddressFamily> SAFI = UnicastSubsequentAddressFamily.class;
+ protected static final QName AFI_QNAME = BindingReflections.findQName(AFI).intern();
+ protected static final QName SAFI_QNAME = BindingReflections.findQName(SAFI).intern();
protected static final TablesKey KEY = new TablesKey(AFI, SAFI);
protected static final QName PREFIX_QNAME = QName.create(Ipv4Route.QNAME, "prefix").intern();
private static final ClusterIdentifier CLUSTER_ID = new ClusterIdentifier("128.0.0.1");
}
private static BindingCodecTreeFactory createCodecFactory(final ClassLoadingStrategy str, final SchemaContext ctx) {
- final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(ClassPool.getDefault()));
+ final DataObjectSerializerGenerator generator = StreamWriterGenerator
+ .create(JavassistUtils.forClassPool(ClassPool.getDefault()));
final BindingNormalizedNodeCodecRegistry codec = new BindingNormalizedNodeCodecRegistry(generator);
codec.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(str, ctx));
return codec;
this.a1 = new RIBActivator();
this.a1.startRIBExtensionProvider(context);
mockedMethods();
- doReturn(Mockito.mock(ClusterSingletonServiceRegistration.class)).when(this.clusterSingletonServiceProvider)
+ doReturn(mock(ClusterSingletonServiceRegistration.class)).when(this.clusterSingletonServiceProvider)
.registerClusterSingletonService(any(ClusterSingletonService.class));
- this.rib = new RIBImpl(this.clusterSingletonServiceProvider, new RibId("test"),
- new AsNumber(5L), RIB_ID, CLUSTER_ID, context,
+ this.rib = new RIBImpl(new RibId("test"), new AsNumber(5L), RIB_ID, CLUSTER_ID, context,
this.dispatcher, this.codecFactory, this.dom, localTables,
Collections.singletonMap(new TablesKey(AFI, SAFI),
BasePathSelectionModeFactory.createBestPathSelectionStrategy()),
@SuppressWarnings("unchecked")
private void mockedMethods() throws Exception {
MockitoAnnotations.initMocks(this);
- final ReadOnlyTransaction readTx = Mockito.mock(ReadOnlyTransaction.class);
- Mockito.doReturn(new listenerRegistration()).when(this.service).registerDataTreeChangeListener(Mockito.any(DOMDataTreeIdentifier.class), Mockito.any(ClusteredDOMDataTreeChangeListener.class));
+ final ReadOnlyTransaction readTx = mock(ReadOnlyTransaction.class);
+ doReturn(new listenerRegistration()).when(this.service)
+ .registerDataTreeChangeListener(any(DOMDataTreeIdentifier.class),
+ any(ClusteredDOMDataTreeChangeListener.class));
final Map<Class<? extends DOMDataBrokerExtension>, DOMDataBrokerExtension> map = new HashMap<>();
map.put(DOMDataTreeChangeService.class, this.service);
- Mockito.doNothing().when(readTx).close();
- final CheckedFuture<Optional<DataObject>, ReadFailedException> readFuture = Mockito.mock(CheckedFuture.class);
- Mockito.doNothing().when(this.domTransWrite).put(Mockito.eq(LogicalDatastoreType.OPERATIONAL), Mockito.any(YangInstanceIdentifier.class), Mockito.any(NormalizedNode.class));
- Mockito.doNothing().when(this.domTransWrite).delete(Mockito.eq(LogicalDatastoreType.OPERATIONAL), Mockito.any(YangInstanceIdentifier.class));
- Mockito.doNothing().when(this.domTransWrite).merge(Mockito.eq(LogicalDatastoreType.OPERATIONAL), Mockito.any(YangInstanceIdentifier.class), Mockito.any(NormalizedNode.class));
- Mockito.doReturn(Optional.absent()).when(readFuture).checkedGet();
- Mockito.doReturn(readFuture).when(readTx).read(Mockito.eq(LogicalDatastoreType.OPERATIONAL), Mockito.any(InstanceIdentifier.class));
- Mockito.doNothing().when(this.domChain).close();
- Mockito.doReturn(this.domTransWrite).when(this.domChain).newWriteOnlyTransaction();
- Mockito.doNothing().when(getTransaction()).put(Mockito.eq(LogicalDatastoreType.OPERATIONAL), Mockito.eq(YangInstanceIdentifier.of(BgpRib.QNAME)), Mockito.any(NormalizedNode.class));
- Mockito.doReturn(map).when(this.dom).getSupportedExtensions();
- Mockito.doReturn(this.domChain).when(this.dom).createTransactionChain(Mockito.any(BGPPeer.class));
- Mockito.doReturn(this.transWrite).when(this.chain).newWriteOnlyTransaction();
- Mockito.doReturn(false).when(this.o).isPresent();
- Mockito.doReturn(this.o).when(this.future).checkedGet();
- Mockito.doReturn(this.future).when(this.domTransWrite).submit();
- Mockito.doNothing().when(this.future).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
- Mockito.doNothing().when(this.transWrite).put(Mockito.eq(LogicalDatastoreType.OPERATIONAL), Mockito.any(InstanceIdentifier.class), Mockito.any(DataObject.class), Mockito.eq(true));
- Mockito.doNothing().when(this.transWrite).put(Mockito.eq(LogicalDatastoreType.OPERATIONAL), Mockito.any(InstanceIdentifier.class), Mockito.any(DataObject.class));
- Mockito.doReturn(this.future).when(this.transWrite).submit();
+ doNothing().when(readTx).close();
+ final CheckedFuture<Optional<DataObject>, ReadFailedException> readFuture = mock(CheckedFuture.class);
+ doNothing().when(this.domTransWrite).put(eq(LogicalDatastoreType.OPERATIONAL),
+ any(YangInstanceIdentifier.class), any(NormalizedNode.class));
+ doNothing().when(this.domTransWrite).delete(eq(LogicalDatastoreType.OPERATIONAL),
+ any(YangInstanceIdentifier.class));
+ doNothing().when(this.domTransWrite).merge(eq(LogicalDatastoreType.OPERATIONAL),
+ any(YangInstanceIdentifier.class), any(NormalizedNode.class));
+ doReturn(Optional.absent()).when(readFuture).checkedGet();
+ doReturn(readFuture).when(readTx).read(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class));
+ doNothing().when(this.domChain).close();
+ doReturn(this.domTransWrite).when(this.domChain).newWriteOnlyTransaction();
+ doNothing().when(getTransaction()).put(eq(LogicalDatastoreType.OPERATIONAL),
+ eq(YangInstanceIdentifier.of(BgpRib.QNAME)), any(NormalizedNode.class));
+ doReturn(map).when(this.dom).getSupportedExtensions();
+ doReturn(this.domChain).when(this.dom).createTransactionChain(any(BGPPeer.class));
+ doReturn(this.transWrite).when(this.chain).newWriteOnlyTransaction();
+ doReturn(false).when(this.o).isPresent();
+ doReturn(this.o).when(this.future).checkedGet();
+ doReturn(this.future).when(this.domTransWrite).submit();
+ doNothing().when(this.future).addListener(any(Runnable.class), any(Executor.class));
+ doNothing().when(this.transWrite).put(eq(LogicalDatastoreType.OPERATIONAL),
+ any(InstanceIdentifier.class), any(DataObject.class), eq(true));
+ doNothing().when(this.transWrite).put(eq(LogicalDatastoreType.OPERATIONAL),
+ any(InstanceIdentifier.class), any(DataObject.class));
+ doReturn(this.future).when(this.transWrite).submit();
}
- public Collection<DataTreeCandidate> ipv4Input(final YangInstanceIdentifier target, final ModificationType type, final Ipv4Prefix... prefix) {
+ public Collection<DataTreeCandidate> ipv4Input(final YangInstanceIdentifier target,
+ final ModificationType type, final Ipv4Prefix... prefix) {
final Collection<DataTreeCandidate> col = new HashSet<>();
- final DataTreeCandidate candidate = Mockito.mock(DataTreeCandidate.class);
- final DataTreeCandidateNode rootNode = Mockito.mock(DataTreeCandidateNode.class);
- Mockito.doReturn(rootNode).when(candidate).getRootNode();
- Mockito.doReturn(type).when(rootNode).getModificationType();
- Mockito.doCallRealMethod().when(rootNode).toString();
- Mockito.doReturn(target).when(candidate).getRootPath();
- Mockito.doCallRealMethod().when(candidate).toString();
+ final DataTreeCandidate candidate = mock(DataTreeCandidate.class);
+ final DataTreeCandidateNode rootNode = mock(DataTreeCandidateNode.class);
+ doReturn(rootNode).when(candidate).getRootNode();
+ doReturn(type).when(rootNode).getModificationType();
+ doCallRealMethod().when(rootNode).toString();
+ doReturn(target).when(candidate).getRootPath();
+ doCallRealMethod().when(candidate).toString();
final Collection<DataTreeCandidateNode> children = new HashSet<>();
for (final Ipv4Prefix p : prefix) {
- final NodeIdentifierWithPredicates routekey = new NodeIdentifierWithPredicates(Ipv4Route.QNAME, PREFIX_QNAME, p);
- final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> b = ImmutableNodes.mapEntryBuilder();
+ final NodeIdentifierWithPredicates routekey =
+ new NodeIdentifierWithPredicates(Ipv4Route.QNAME, PREFIX_QNAME, p);
+ final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> b =
+ ImmutableNodes.mapEntryBuilder();
b.withNodeIdentifier(routekey);
- b.addChild(Builders.leafBuilder().withNodeIdentifier(new NodeIdentifier(PREFIX_QNAME)).withValue(p).build());
+ b.addChild(Builders.leafBuilder()
+ .withNodeIdentifier(new NodeIdentifier(PREFIX_QNAME)).withValue(p).build());
- final DataTreeCandidateNode child = Mockito.mock(DataTreeCandidateNode.class);
- Mockito.doReturn(createIdentifier(p)).when(child).getIdentifier();
- Mockito.doReturn(Optional.of(b.build())).when(child).getDataAfter();
- Mockito.doReturn(type).when(child).getModificationType();
+ final DataTreeCandidateNode child = mock(DataTreeCandidateNode.class);
+ doReturn(createIdentifier(p)).when(child).getIdentifier();
+ doReturn(Optional.of(b.build())).when(child).getDataAfter();
+ doReturn(type).when(child).getModificationType();
children.add(child);
}
- Mockito.doReturn(children).when(rootNode).getChildNodes();
+ doReturn(children).when(rootNode).getChildNodes();
col.add(candidate);
return col;
}
public PathArgument createIdentifier(final Ipv4Prefix prefix) {
- final NodeIdentifierWithPredicates routekey = new NodeIdentifierWithPredicates(Ipv4Route.QNAME, PREFIX_QNAME, prefix);
+ final NodeIdentifierWithPredicates routekey =
+ new NodeIdentifierWithPredicates(Ipv4Route.QNAME, PREFIX_QNAME, prefix);
return YangInstanceIdentifier.of(PREFIX_QNAME).node(routekey).getLastPathArgument();
}
super.setUp();
final Map<TablesKey, PathSelectionMode> pathTables = ImmutableMap.of(TABLES_KEY, new AllPathSelection());
- this.ribImpl = new RIBImpl(this.clusterSingletonServiceProvider, new RibId("test-rib"),
- AS_NUMBER, BGP_ID, null, this.ribExtension, this.serverDispatcher, this.mappingService.getCodecFactory(),
+ this.ribImpl = new RIBImpl(new RibId("test-rib"), AS_NUMBER, BGP_ID, null,
+ this.ribExtension, this.serverDispatcher, this.mappingService.getCodecFactory(),
getDomBroker(), TABLES_TYPE, pathTables, this.ribExtension.getClassLoadingStrategy());
this.ribImpl.instantiateServiceInstance();
final Map<TablesKey, PathSelectionMode> pathTables = ImmutableMap.of(tk,
BasePathSelectionModeFactory.createBestPathSelectionStrategy());
- this.ribImpl = new RIBImpl(this.clusterSingletonServiceProvider, new RibId("test-rib"),
+ this.ribImpl = new RIBImpl(new RibId("test-rib"),
AS_NUMBER, new BgpId(RIB_ID), null, this.ribExtension, this.serverDispatcher,
this.mappingService.getCodecFactory(), getDomBroker(), TABLES_TYPE, pathTables,
this.ribExtension.getClassLoadingStrategy());
public void setUp() throws Exception {
super.setUp();
final TablesKey tk = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
- final Map<TablesKey, PathSelectionMode> pathTables = ImmutableMap.of(tk, new AddPathBestNPathSelection(2L));
+ final Map<TablesKey, PathSelectionMode> pathTables = ImmutableMap.of(tk,
+ new AddPathBestNPathSelection(2L));
- this.ribImpl = new RIBImpl(this.clusterSingletonServiceProvider, new RibId("test-rib"),
+ this.ribImpl = new RIBImpl(new RibId("test-rib"),
AS_NUMBER, new BgpId(RIB_ID), null, this.ribExtension, this.serverDispatcher,
this.mappingService.getCodecFactory(), getDomBroker(), TABLES_TYPE, pathTables,
this.ribExtension.getClassLoadingStrategy());
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doReturn;
import static org.opendaylight.protocol.bgp.rib.impl.AbstractAddPathTest.AS_NUMBER;
import static org.opendaylight.protocol.bgp.rib.impl.AbstractAddPathTest.BGP_ID;
import static org.opendaylight.protocol.util.CheckUtil.readDataOperational;
import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeFactory;
import org.opendaylight.mdsal.binding.generator.impl.GeneratedClassLoadingStrategy;
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.inet.RIBActivator;
import org.opendaylight.protocol.bgp.mode.impl.base.BasePathSelectionModeFactory;
import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
@Mock
private BGPDispatcher dispatcher;
- @Mock
- private ClusterSingletonServiceProvider clusterSingletonServiceProvider;
private BindingCodecTreeFactory codecFactory;
private DOMSchemaService schemaService;
final String hexMessages = "/bgp_hex.txt";
final List<byte[]> bgpMessages = HexDumpBGPFileParser.parseMessages(ParserToSalTest.class.getResourceAsStream(hexMessages));
this.mock = new BGPMock(new EventBus("test"), ServiceLoaderBGPExtensionProviderContext
- .getSingletonInstance().getMessageRegistry(), Lists.newArrayList(fixMessages(bgpMessages)));
+ .getSingletonInstance().getMessageRegistry(), Lists.newArrayList(fixMessages(bgpMessages)));
Mockito.doReturn(GlobalEventExecutor.INSTANCE.newSucceededFuture(null)).when(this.dispatcher)
- .createReconnectingClient(Mockito.any(InetSocketAddress.class), Mockito.anyInt(),
- Mockito.any(KeyMapping.class));
+ .createReconnectingClient(Mockito.any(InetSocketAddress.class), Mockito.anyInt(),
+ Mockito.any(KeyMapping.class));
this.ext1 = new SimpleRIBExtensionProviderContext();
this.ext2 = new SimpleRIBExtensionProviderContext();
this.baseact.startRIBExtensionProvider(this.ext1);
this.lsact.startRIBExtensionProvider(this.ext2);
- doReturn(Mockito.mock(ClusterSingletonServiceRegistration.class)).when(this.clusterSingletonServiceProvider).
- registerClusterSingletonService(any(ClusterSingletonService.class));
}
@Override
protected Iterable<YangModuleInfo> getModuleInfos() throws Exception {
return ImmutableList.of(
- BindingReflections.getModuleInfo(Ipv4Route.class),
- BindingReflections.getModuleInfo(Ipv6Route.class),
- BindingReflections.getModuleInfo(LinkstateRoute.class));
+ BindingReflections.getModuleInfo(Ipv4Route.class),
+ BindingReflections.getModuleInfo(Ipv6Route.class),
+ BindingReflections.getModuleInfo(LinkstateRoute.class));
}
@Override
@Test
public void testWithLinkstate() throws InterruptedException, ExecutionException, ReadFailedException {
final List<BgpTableType> tables = ImmutableList.of(new BgpTableTypeImpl(LinkstateAddressFamily.class,
- LinkstateSubsequentAddressFamily.class));
- final RIBImpl rib = new RIBImpl(this.clusterSingletonServiceProvider, new RibId(TEST_RIB_ID),
- AS_NUMBER, new BgpId("127.0.0.1"), null, this.ext2, this.dispatcher,
- this.codecFactory, getDomBroker(), tables, Collections.singletonMap(TABLE_KEY,
- BasePathSelectionModeFactory.createBestPathSelectionStrategy()),
- GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy());
+ LinkstateSubsequentAddressFamily.class));
+ final RIBImpl rib = new RIBImpl(new RibId(TEST_RIB_ID),
+ AS_NUMBER, new BgpId("127.0.0.1"), null, this.ext2, this.dispatcher,
+ this.codecFactory, getDomBroker(), tables, Collections.singletonMap(TABLE_KEY,
+ BasePathSelectionModeFactory.createBestPathSelectionStrategy()),
+ GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy());
rib.instantiateServiceInstance();
assertTablesExists(tables);
rib.onGlobalContextUpdated(this.schemaService.getGlobalContext());
final BGPPeer peer = new BGPPeer(this.localAddress, rib, PeerRole.Ibgp, null, Collections.emptySet(),
- Collections.emptySet());
+ Collections.emptySet());
peer.instantiateServiceInstance();
final ListenerRegistration<?> reg = this.mock.registerUpdateListener(peer);
reg.close();
@Test
public void testWithoutLinkstate() throws InterruptedException, ExecutionException, ReadFailedException {
final List<BgpTableType> tables = ImmutableList.of(new BgpTableTypeImpl(Ipv4AddressFamily.class,
- UnicastSubsequentAddressFamily.class));
- final RIBImpl rib = new RIBImpl(this.clusterSingletonServiceProvider, new RibId(TEST_RIB_ID), AS_NUMBER, BGP_ID,
- null, this.ext1, this.dispatcher, this.codecFactory, getDomBroker(), tables,
- Collections.singletonMap(TABLE_KEY, BasePathSelectionModeFactory.createBestPathSelectionStrategy()),
- GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy());
+ UnicastSubsequentAddressFamily.class));
+ final RIBImpl rib = new RIBImpl(new RibId(TEST_RIB_ID), AS_NUMBER, BGP_ID,
+ null, this.ext1, this.dispatcher, this.codecFactory, getDomBroker(), tables,
+ Collections.singletonMap(TABLE_KEY, BasePathSelectionModeFactory.createBestPathSelectionStrategy()),
+ GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy());
rib.instantiateServiceInstance();
rib.onGlobalContextUpdated(this.schemaService.getGlobalContext());
assertTablesExists(tables);
final BGPPeer peer = new BGPPeer(this.localAddress, rib, PeerRole.Ibgp, null, Collections.emptySet(),
- Collections.emptySet());
+ Collections.emptySet());
peer.instantiateServiceInstance();
final ListenerRegistration<?> reg = this.mock.registerUpdateListener(peer);
reg.close();
}
private void assertTablesExists(final List<BgpTableType> expectedTables)
- throws InterruptedException, ExecutionException, ReadFailedException {
+ throws InterruptedException, ExecutionException, ReadFailedException {
readDataOperational(getDataBroker(), BGP_IID, bgpRib -> {
final List<Tables> tables = bgpRib.getRib().get(0).getLocRib().getTables();
assertFalse(tables.isEmpty());
.setVersion(new ProtocolVersion((short) 4)).setBgpParameters(tlvs).setBgpIdentifier(BGP_ID).build();
final List<OptionalCapabilities> capa = Lists.newArrayList();
- capa.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder()
- .addAugmentation(CParameters1.class,
- new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder()
- .setAfi(this.ipv4tt.getAfi()).setSafi(this.ipv4tt.getSafi()).build())
- .setGracefulRestartCapability(new GracefulRestartCapabilityBuilder().build()).build())
- .setAs4BytesCapability(new As4BytesCapabilityBuilder()
- .setAsNumber(AS_NUMBER).build()).build()).build());
- capa.add(new OptionalCapabilitiesBuilder()
- .setCParameters(BgpExtendedMessageUtil.EXTENDED_MESSAGE_CAPABILITY).build());
+ capa.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class,
+ new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder()
+ .setAfi(this.ipv4tt.getAfi()).setSafi(this.ipv4tt.getSafi()).build())
+ .setGracefulRestartCapability(new GracefulRestartCapabilityBuilder().build()).build())
+ .setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(AS_NUMBER).build()).build()).build());
+ capa.add(new OptionalCapabilitiesBuilder().setCParameters(BgpExtendedMessageUtil.EXTENDED_MESSAGE_CAPABILITY).build());
tlvs.add(new BgpParametersBuilder().setOptionalCapabilities(capa).build());
doReturn(null).when(mock(ChannelFuture.class)).addListener(any());
.when(this.speakerListener).localAddress();
doReturn(this.pipeline).when(this.speakerListener).pipeline();
doReturn(this.pipeline).when(this.pipeline).replace(any(ChannelHandler.class),
- any(String.class), any(ChannelHandler.class));
+ any(String.class),
+ any(ChannelHandler.class));
doReturn(null).when(this.pipeline).replace(Matchers.<Class<ChannelHandler>>any(),
- any(String.class), any(ChannelHandler.class));
+ any(String.class),
+ any(ChannelHandler.class));
doReturn(this.pipeline).when(this.pipeline).addLast(any(ChannelHandler.class));
final ChannelFuture futureChannel = mock(ChannelFuture.class);
doReturn(null).when(futureChannel).addListener(any());
@Test
public void testHandleMessageAfterException() throws InterruptedException {
final Map<TablesKey, PathSelectionMode> pathTables = ImmutableMap.of(TABLES_KEY,
- BasePathSelectionModeFactory.createBestPathSelectionStrategy());
- final RIBImpl ribImpl = new RIBImpl(this.clusterSingletonServiceProvider, new RibId(RIB_ID), AS_NUMBER,
- new BgpId(RIB_ID), null, this.ribExtension, this.serverDispatcher,
- this.mappingService.getCodecFactory(), this.domBroker, ImmutableList.of(this.ipv4tt),
- pathTables, this.ribExtension.getClassLoadingStrategy());
+ BasePathSelectionModeFactory.createBestPathSelectionStrategy());
+ final RIBImpl ribImpl = new RIBImpl( new RibId(RIB_ID), AS_NUMBER,
+ new BgpId(RIB_ID), null, this.ribExtension, this.serverDispatcher, this.mappingService.getCodecFactory(),
+ this.domBroker, ImmutableList.of(this.ipv4tt), pathTables, this.ribExtension.getClassLoadingStrategy());
ribImpl.instantiateServiceInstance();
ribImpl.onGlobalContextUpdated(this.schemaContext);
@Test
public void testUseCase1() throws InterruptedException {
final Map<TablesKey, PathSelectionMode> pathTables = ImmutableMap.of(TABLES_KEY,
- BasePathSelectionModeFactory.createBestPathSelectionStrategy());
- final RIBImpl ribImpl = new RIBImpl(this.clusterSingletonServiceProvider, new RibId(RIB_ID), AS_NUMBER,
- new BgpId(RIB_ID), null, this.ribExtension, this.serverDispatcher,
- this.mappingService.getCodecFactory(), this.domBroker, ImmutableList.of(this.ipv4tt), pathTables,
- this.ribExtension.getClassLoadingStrategy());
+ BasePathSelectionModeFactory.createBestPathSelectionStrategy());
+ final RIBImpl ribImpl = new RIBImpl( new RibId(RIB_ID), AS_NUMBER,
+ new BgpId(RIB_ID), null, this.ribExtension, this.serverDispatcher, this.mappingService.getCodecFactory(),
+ this.domBroker, ImmutableList.of(this.ipv4tt), pathTables, this.ribExtension.getClassLoadingStrategy());
ribImpl.instantiateServiceInstance();
ribImpl.onGlobalContextUpdated(this.schemaContext);
public void setUp() {
this.listener = new SimpleSessionListener();
this.ipv4m = new UpdateBuilder()
- .setNlri(Collections.singletonList(new NlriBuilder().setPrefix(new Ipv4Prefix("1.1.1.1/32")).build()))
+ .setNlri(Collections.singletonList(new NlriBuilder()
+ .setPrefix(new Ipv4Prefix("1.1.1.1/32")).build()))
.build();
MpReachNlriBuilder mpBuilder = new MpReachNlriBuilder();
import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
-import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
import org.opendaylight.protocol.bgp.rib.impl.spi.AbstractImportPolicy;
import org.osgi.framework.ServiceRegistration;
class AbstractConfig {
- protected static final AsNumber AS = new AsNumber(72L);
- protected static final RibId RIB_ID = new RibId("test");
static final TablesKey TABLES_KEY = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
- protected ClusterSingletonService singletonService;
+ protected static final AsNumber AS = new AsNumber(72L);
@Mock
protected RIB rib;
@Mock
- protected ClusterSingletonServiceRegistration singletonServiceRegistration;
- @Mock
protected BGPTableTypeRegistryConsumer tableTypeRegistry;
@Mock
protected DOMTransactionChain domTx;
private ImportPolicyPeerTracker importPolicyPeerTracker;
@Mock
private DOMDataTreeChangeService dataTreeChangeService;
+ protected static final RibId RIB_ID = new RibId("test");
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- Mockito.doAnswer(invocationOnMock -> {
- this.singletonService = (ClusterSingletonService) invocationOnMock.getArguments()[0];
- return this.singletonServiceRegistration;
- }).when(this.rib).registerClusterSingletonService(any(ClusterSingletonService.class));
Mockito.doReturn(InstanceIdentifier.create(BgpRib.class).child(org.opendaylight.yang.gen.v1.urn.opendaylight
.params.xml.ns.yang.bgp.rib.rev171207.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.doNothing().when(this.importPolicyPeerTracker).peerRoleChanged(any(YangInstanceIdentifier.class), any(PeerRole.class));
- Mockito.doReturn(mock(AbstractImportPolicy.class)).when(this.importPolicyPeerTracker).policyFor(any(PeerId.class));
+ Mockito.doNothing().when(this.importPolicyPeerTracker)
+ .peerRoleChanged(any(YangInstanceIdentifier.class), any(PeerRole.class));
+ Mockito.doReturn(mock(AbstractImportPolicy.class))
+ .when(this.importPolicyPeerTracker).policyFor(any(PeerId.class));
Mockito.doReturn(mock(RIBSupportContextRegistry.class)).when(this.rib).getRibSupportContext();
Mockito.doReturn(Collections.emptySet()).when(this.rib).getLocalTablesKeys();
Mockito.doNothing().when(this.domTx).close();
Mockito.doReturn(this.domDW).when(this.domTx).newWriteOnlyTransaction();
- Mockito.doNothing().when(this.domDW).put(eq(LogicalDatastoreType.OPERATIONAL), any(YangInstanceIdentifier.class), any(MapEntryNode.class));
- Mockito.doNothing().when(this.domDW).delete(eq(LogicalDatastoreType.OPERATIONAL), any(YangInstanceIdentifier.class));
- Mockito.doNothing().when(this.domDW).merge(eq(LogicalDatastoreType.OPERATIONAL), any(YangInstanceIdentifier.class), any(NormalizedNode.class));
+ Mockito.doNothing().when(this.domDW).put(eq(LogicalDatastoreType.OPERATIONAL),
+ any(YangInstanceIdentifier.class), any(MapEntryNode.class));
+ Mockito.doNothing().when(this.domDW).delete(eq(LogicalDatastoreType.OPERATIONAL),
+ any(YangInstanceIdentifier.class));
+ Mockito.doNothing().when(this.domDW).merge(eq(LogicalDatastoreType.OPERATIONAL),
+ any(YangInstanceIdentifier.class), any(NormalizedNode.class));
final CheckedFuture<?, ?> checkedFuture = mock(CheckedFuture.class);
Mockito.doAnswer(invocation -> {
final Runnable callback = (Runnable) invocation.getArguments()[0];
Mockito.doReturn(null).when(checkedFuture).get();
Mockito.doReturn(true).when(checkedFuture).isDone();
Mockito.doReturn("checkedFuture").when(checkedFuture).toString();
- Mockito.doAnswer(invocationOnMock -> {
- this.singletonService.closeServiceInstance();
- return null;
- }).when(this.singletonServiceRegistration).close();
Mockito.doReturn(YangInstanceIdentifier.of(Rib.QNAME)).when(this.rib).getYangRibId();
Mockito.doReturn(this.dataTreeChangeService).when(this.rib).getService();
Mockito.doReturn(this.listener).when(this.dataTreeChangeService).registerDataTreeChangeListener(any(), any());
- Mockito.doReturn(mock(ServiceGroupIdentifier.class)).when(this.rib).getRibIServiceGroupIdentifier();
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));
Mockito.doReturn(this.dispatcher).when(this.rib).getDispatcher();
- Mockito.doReturn(java.util.Optional.of(new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class)))
+ Mockito.doReturn(java.util.Optional.of(new BgpTableTypeImpl(Ipv4AddressFamily.class,
+ UnicastSubsequentAddressFamily.class)))
.when(this.tableTypeRegistry).getTableType(any());
Mockito.doReturn(java.util.Optional.of(TABLES_KEY)).when(this.tableTypeRegistry).getTableKey(any());
- Mockito.doReturn(Collections.singleton(new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class)))
+ Mockito.doReturn(Collections.singleton(new BgpTableTypeImpl(Ipv4AddressFamily.class,
+ UnicastSubsequentAddressFamily.class)))
.when(this.rib).getLocalTables();
- Mockito.doNothing().when(this.bgpPeerRegistry).addPeer(any(IpAddress.class), any(BGPSessionListener.class), any(BGPSessionPreferences.class));
+ Mockito.doNothing().when(this.bgpPeerRegistry).addPeer(any(IpAddress.class),
+ any(BGPSessionListener.class), any(BGPSessionPreferences.class));
Mockito.doNothing().when(this.bgpPeerRegistry).removePeer(any(IpAddress.class));
Mockito.doReturn("registry").when(this.bgpPeerRegistry).toString();
Mockito.doNothing().when(this.listener).close();
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
import static org.mockito.internal.verification.VerificationModeFactory.times;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.ConfigBuilder;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.Neighbor;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbors.NeighborBuilder;
public class AppPeerTest extends AbstractConfig {
private static final AppPeer APP_PEER = new AppPeer();
- private final Neighbor neighbor = new NeighborBuilder().setConfig(new ConfigBuilder().addAugmentation(Config2.class,
- new Config2Builder().setPeerGroup(OpenConfigMappingUtil.APPLICATION_PEER_GROUP_NAME).build()).build())
+ private final Neighbor neighbor = new NeighborBuilder()
+ .setConfig(new ConfigBuilder().addAugmentation(Config2.class,
+ new Config2Builder().setPeerGroup(OpenConfigMappingUtil.APPLICATION_PEER_GROUP_NAME)
+ .build()).build())
.setNeighborAddress(new IpAddress(new Ipv4Address("127.0.0.1"))).build();
@Override
APP_PEER.start(this.rib, this.neighbor, this.tableTypeRegistry);
Mockito.verify(this.rib).getYangRibId();
Mockito.verify(this.rib).getService();
- Mockito.verify(this.rib).getRibIServiceGroupIdentifier();
- Mockito.verify(this.rib).registerClusterSingletonService(any(ClusterSingletonService.class));
Mockito.verify(this.rib, times(1)).getLocalTablesKeys();
- this.singletonService.instantiateServiceInstance();
+ APP_PEER.instantiateServiceInstance();
Mockito.verify(this.rib, times(2)).getYangRibId();
Mockito.verify(this.rib).getRibSupportContext();
Mockito.verify(this.rib, times(2)).getLocalTablesKeys();
Mockito.verify(this.domTx).newWriteOnlyTransaction();
+ APP_PEER.closeServiceInstance();
APP_PEER.close();
- Mockito.verify(this.singletonServiceRegistration).close();
APP_PEER.restart(this.rib, this.tableTypeRegistry);
- this.singletonService.instantiateServiceInstance();
+ APP_PEER.instantiateServiceInstance();
Mockito.verify(this.rib, times(4)).getYangRibId();
Mockito.verify(this.rib, times(4)).getService();
- Mockito.verify(this.rib, times(2)).getRibIServiceGroupIdentifier();
- Mockito.verify(this.rib, times(2))
- .registerClusterSingletonService(any(ClusterSingletonService.class));
Mockito.verify(this.listener, times(2)).close();
assertTrue(APP_PEER.containsEqualConfiguration(this.neighbor));
assertFalse(APP_PEER.containsEqualConfiguration(new NeighborBuilder()
.setNeighborAddress(new IpAddress(new Ipv4Address("127.0.0.2"))).build()));
+ APP_PEER.closeServiceInstance();
APP_PEER.close();
- Mockito.verify(this.singletonServiceRegistration, times(2)).close();
}
}
\ No newline at end of file
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
private static final short SHORT = 0;
@Mock
- DataObjectModification<?> dObject;
+ private DataObjectModification<?> dObject;
@Mock
private BlueprintContainer blueprintContainer;
@Mock
private ListenerRegistration<?> dataTreeRegistration;
@Mock
private ServiceRegistration<?> registration;
+ @Mock
+ private ClusterSingletonServiceProvider singletonServiceProvider;
private Collection<DataTreeModification<Bgp>> collection = Collections.singleton(this.modification);
doReturn(Optional.of(TABLE_TYPE)).when(this.tableTypeRegistry).getTableType(any());
doReturn(Optional.of(TABLES_KEY)).when(this.tableTypeRegistry).getTableKey(any());
Mockito.doNothing().when(this.registration).unregister();
- doReturn(this.registration).when(this.bundleContext)
- .registerService(eq(InstanceType.RIB.getServices()), any(), any(Dictionary.class));
- doReturn(this.registration).when(this.bundleContext)
- .registerService(eq(InstanceType.PEER.getServices()), any(), any(Dictionary.class));
+ doReturn(this.registration).when(this.bundleContext).registerService(eq(InstanceType.RIB.getServices()), any()
+ , any(Dictionary.class));
+ doReturn(this.registration).when(this.bundleContext).registerService(eq(InstanceType.PEER.getServices()), any()
+ , any(Dictionary.class));
Mockito.doNothing().when(this.wTx).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class),
final RIBExtensionConsumerContext extension = mock(RIBExtensionConsumerContext.class);
doReturn(mock(GeneratedClassLoadingStrategy.class)).when(extension).getClassLoadingStrategy();
- final ClusterSingletonServiceProvider singletonServiceProvider = mock(ClusterSingletonServiceProvider.class);
final ClusterSingletonServiceRegistration serviceRegistration = mock(ClusterSingletonServiceRegistration.class);
- doReturn(serviceRegistration).when(singletonServiceProvider).registerClusterSingletonService(any());
+ doReturn(serviceRegistration).when(this.singletonServiceProvider).registerClusterSingletonService(any());
Mockito.doNothing().when(serviceRegistration).close();
final DOMSchemaService schemaService = mock(DOMSchemaService.class);
doReturn(this.dataTreeRegistration).when(schemaService).registerSchemaContextListener(any());
- final RibImpl ribImpl = new RibImpl(singletonServiceProvider, extension,
- mock(BGPDispatcher.class), mock(BindingCodecTreeFactory.class), domDataBroker, schemaService);
+ final RibImpl ribImpl = new RibImpl(extension, mock(BGPDispatcher.class), mock(BindingCodecTreeFactory.class),
+ domDataBroker, schemaService);
doReturn(ribImpl).when(this.blueprintContainer).getComponentInstance(eq("ribImpl"));
final BgpPeer bgpPeer = new BgpPeer(mock(RpcProviderRegistry.class));
@Test
public void testDeployerRib() throws Exception {
doReturn(Global.class).when(this.dObject).getDataType();
- final BgpDeployerImpl deployer = new BgpDeployerImpl(NETWORK_INSTANCE_NAME, this.blueprintContainer,
- this.bundleContext, this.dataBroker, this.tableTypeRegistry);
+ final BgpDeployerImpl deployer = new BgpDeployerImpl(NETWORK_INSTANCE_NAME, this.singletonServiceProvider,
+ this.blueprintContainer, this.bundleContext, this.dataBroker, this.tableTypeRegistry);
final BgpDeployerImpl spyDeployer = spy(deployer);
+ deployer.init();
configureGlobal(IPV4UNICAST.class);
doReturn(WRITE).when(this.dObject).getModificationType();
- spyDeployer.init();
final KeyedInstanceIdentifier<NetworkInstance, NetworkInstanceKey> networkInstanceIId =
InstanceIdentifier.create(NetworkInstances.class)
.child(NetworkInstance.class, new NetworkInstanceKey(NETWORK_INSTANCE_NAME));
.setName(networkInstanceIId.firstKeyOf(NetworkInstance.class).getName())
.setProtocols(new ProtocolsBuilder().build()).build();
verify(this.wTx).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), eq(netII));
- verify(this.dataBroker)
- .registerDataTreeChangeListener(any(DataTreeIdentifier.class), any(BgpDeployerImpl.class));
+ verify(this.dataBroker).registerDataTreeChangeListener(any(DataTreeIdentifier.class),
+ any(BgpDeployerImpl.class));
- assertEquals(networkInstanceIId, spyDeployer.getInstanceIdentifier());
assertEquals(this.tableTypeRegistry, spyDeployer.getTableTypeRegistry());
spyDeployer.onDataTreeChanged(this.collection);
- verifyPrivate(spyDeployer)
- .invoke("onGlobalChanged", any(DataObjectModification.class), any(InstanceIdentifier.class));
+ verifyPrivate(spyDeployer).invoke("onGlobalChanged", any(DataObjectModification.class),
+ any(InstanceIdentifier.class));
verify(this.blueprintContainer).getComponentInstance(eq("ribImpl"));
verify(this.bundleContext).registerService(eq(InstanceType.RIB.getServices()), any(), any(Dictionary.class));
verify(spyDeployer).onDataTreeChanged(any(Collection.class));
- verify(spyDeployer).onGlobalModified(any(InstanceIdentifier.class), any());
- verifyPrivate(spyDeployer).invoke("onGlobalCreated", any(InstanceIdentifier.class), any(Global.class));
- verifyPrivate(spyDeployer)
- .invoke("initiateRibInstance", any(InstanceIdentifier.class), any(Global.class), any(RibImpl.class));
- verifyPrivate(spyDeployer).invoke("registerRibInstance", any(RibImpl.class), anyString());
- verify(spyDeployer).onDataTreeChanged(any(Collection.class));
//change with same rib already existing
spyDeployer.onDataTreeChanged(this.collection);
- verifyPrivate(spyDeployer, times(2))
- .invoke("onGlobalChanged", any(DataObjectModification.class), any(InstanceIdentifier.class));
+ verifyPrivate(spyDeployer, times(2)).invoke("onGlobalChanged",
+ any(DataObjectModification.class), any(InstanceIdentifier.class));
verify(this.blueprintContainer).getComponentInstance(eq("ribImpl"));
verify(this.bundleContext).registerService(eq(InstanceType.RIB.getServices()), any(), any(Dictionary.class));
verify(spyDeployer, times(2)).onDataTreeChanged(any(Collection.class));
- verify(spyDeployer, times(2)).onGlobalModified(any(InstanceIdentifier.class), any());
- verifyPrivate(spyDeployer).invoke("onGlobalCreated", any(InstanceIdentifier.class), any(Global.class));
- verifyPrivate(spyDeployer)
- .invoke("initiateRibInstance", any(InstanceIdentifier.class), any(Global.class), any(RibImpl.class));
- verifyPrivate(spyDeployer).invoke("registerRibInstance", any(RibImpl.class), anyString());
- verify(spyDeployer, times(2)).onDataTreeChanged(any(Collection.class));
//Update for existing rib
configureGlobal(IPV6UNICAST.class);
spyDeployer.onDataTreeChanged(this.collection);
- verifyPrivate(spyDeployer, times(3))
- .invoke("onGlobalChanged", any(DataObjectModification.class), any(InstanceIdentifier.class));
+ verifyPrivate(spyDeployer, times(3)).invoke("onGlobalChanged",
+ any(DataObjectModification.class), any(InstanceIdentifier.class));
verify(this.blueprintContainer).getComponentInstance(eq("ribImpl"));
- verify(this.bundleContext, times(2))
- .registerService(eq(InstanceType.RIB.getServices()), any(), any(Dictionary.class));
+ verify(this.bundleContext, times(2)).registerService(eq(InstanceType.RIB.getServices()),
+ any(), any(Dictionary.class));
verify(spyDeployer, times(3)).onDataTreeChanged(any(Collection.class));
- verify(spyDeployer, times(3)).onGlobalModified(any(InstanceIdentifier.class), any());
- verifyPrivate(spyDeployer).invoke("onGlobalCreated", any(InstanceIdentifier.class), any(Global.class));
- verifyPrivate(spyDeployer)
- .invoke("onGlobalUpdated", any(InstanceIdentifier.class), any(Global.class), any(RibImpl.class));
verify(this.dataTreeRegistration).close();
verify(this.registration).unregister();
- verifyPrivate(spyDeployer).invoke("closeAllBindedPeers", any(InstanceIdentifier.class));
- verifyPrivate(spyDeployer, times(2)).invoke("initiateRibInstance",
- any(InstanceIdentifier.class), any(Global.class), any(RibImpl.class));
- verifyPrivate(spyDeployer, times(2))
- .invoke("registerRibInstance", any(RibImpl.class), anyString());
verify(spyDeployer, times(3)).onDataTreeChanged(any(Collection.class));
//Delete for existing rib
doReturn(DELETE).when(this.dObject).getModificationType();
spyDeployer.onDataTreeChanged(this.collection);
- verifyPrivate(spyDeployer, times(4))
- .invoke("onGlobalChanged", any(DataObjectModification.class), any(InstanceIdentifier.class));
+ verifyPrivate(spyDeployer, times(4)).invoke("onGlobalChanged",
+ any(DataObjectModification.class), any(InstanceIdentifier.class));
verify(this.blueprintContainer).getComponentInstance(eq("ribImpl"));
verify(this.bundleContext, times(2))
.registerService(eq(InstanceType.RIB.getServices()), any(), any(Dictionary.class));
verify(spyDeployer, times(4)).onDataTreeChanged(any(Collection.class));
- verify(spyDeployer, times(3)).onGlobalModified(any(InstanceIdentifier.class), any());
- verify(spyDeployer).onGlobalRemoved(any(InstanceIdentifier.class));
verify(this.dataTreeRegistration, times(2)).close();
verify(this.registration, times(2)).unregister();
- verifyPrivate(spyDeployer).invoke("onGlobalCreated", any(InstanceIdentifier.class), any(Global.class));
- verifyPrivate(spyDeployer)
- .invoke("onGlobalUpdated", any(InstanceIdentifier.class), any(Global.class), any(RibImpl.class));
- verifyPrivate(spyDeployer, times(2))
- .invoke("closeAllBindedPeers", any(InstanceIdentifier.class));
- verifyPrivate(spyDeployer, times(2)).invoke("initiateRibInstance",
- any(InstanceIdentifier.class), any(Global.class), any(RibImpl.class));
- verifyPrivate(spyDeployer, times(2))
- .invoke("registerRibInstance", any(RibImpl.class), anyString());
verify(spyDeployer, times(4)).onDataTreeChanged(any(Collection.class));
deployer.close();
private void configureGlobal(final Class<? extends AfiSafiType> afi) {
final Config config = new ConfigBuilder().setAs(AS).setRouterId(BGP_ID).build();
final ArrayList<AfiSafi> afiSafiList = new ArrayList<>();
- afiSafiList.add(new AfiSafiBuilder().setAfiSafiName(afi)
- .addAugmentation(AfiSafi2.class, new AfiSafi2Builder().setReceive(true)
- .setSendMax(Shorts.checkedCast(0L)).build()).build());
+ afiSafiList.add(new AfiSafiBuilder().setAfiSafiName(afi).addAugmentation(AfiSafi2.class, new AfiSafi2Builder().setReceive(true)
+ .setSendMax(Shorts.checkedCast(0L)).build()).build());
final AfiSafis afiSafi = new AfiSafisBuilder().setAfiSafi(afiSafiList).build();
doReturn(new GlobalBuilder().setConfig(config).setAfiSafis(afiSafi).build()).when(this.dObject).getDataAfter();
}
@Test
public void testDeployerCreateNeighbor() throws Exception {
- final BgpDeployerImpl deployer = new BgpDeployerImpl(NETWORK_INSTANCE_NAME, this.blueprintContainer,
- this.bundleContext, this.dataBroker, this.tableTypeRegistry);
+ final BgpDeployerImpl deployer = new BgpDeployerImpl(NETWORK_INSTANCE_NAME, this.singletonServiceProvider,
+ this.blueprintContainer, this.bundleContext, this.dataBroker, this.tableTypeRegistry);
final BgpDeployerImpl spyDeployer = spy(deployer);
-
- spyDeployer.init();
+ deployer.init();
//First create Rib
doReturn(Global.class).when(this.dObject).getDataType();
doReturn(WRITE).when(this.dObject).getModificationType();
configureGlobal(IPV4UNICAST.class);
spyDeployer.onDataTreeChanged(this.collection);
- verifyPrivate(spyDeployer)
- .invoke("onGlobalChanged", any(DataObjectModification.class), any(InstanceIdentifier.class));
+ verifyPrivate(spyDeployer).invoke("onGlobalChanged", any(DataObjectModification.class),
+ any(InstanceIdentifier.class));
verify(this.blueprintContainer).getComponentInstance(eq("ribImpl"));
verify(this.bundleContext).registerService(eq(InstanceType.RIB.getServices()), any(), any(Dictionary.class));
verify(spyDeployer).onDataTreeChanged(any(Collection.class));
- verify(spyDeployer).onGlobalModified(any(InstanceIdentifier.class), any());
- verifyPrivate(spyDeployer).invoke("onGlobalCreated", any(InstanceIdentifier.class), any(Global.class));
- verifyPrivate(spyDeployer)
- .invoke("initiateRibInstance", any(InstanceIdentifier.class), any(Global.class), any(RibImpl.class));
- verifyPrivate(spyDeployer).invoke("registerRibInstance", any(RibImpl.class), anyString());
- verify(spyDeployer).onDataTreeChanged(any(Collection.class));
-
doReturn(Neighbors.class).when(this.dObject).getDataType();
doReturn(WRITE).when(this.dObject).getModificationType();
configureNeighbor(IPV4UNICAST.class);
-
final KeyedInstanceIdentifier<NetworkInstance, NetworkInstanceKey> networkInstanceIId =
InstanceIdentifier.create(NetworkInstances.class)
.child(NetworkInstance.class, new NetworkInstanceKey(NETWORK_INSTANCE_NAME));
verify(this.dataBroker)
.registerDataTreeChangeListener(any(DataTreeIdentifier.class), any(BgpDeployerImpl.class));
- assertEquals(networkInstanceIId, spyDeployer.getInstanceIdentifier());
assertEquals(this.tableTypeRegistry, spyDeployer.getTableTypeRegistry());
spyDeployer.onDataTreeChanged(this.collection);
verify(spyDeployer, times(2)).onDataTreeChanged(any(Collection.class));
- verifyPrivate(spyDeployer)
- .invoke("onNeighborsChanged", any(DataObjectModification.class), any(InstanceIdentifier.class));
- verify(spyDeployer).onNeighborModified(any(InstanceIdentifier.class), any(Neighbor.class));
- verifyPrivate(spyDeployer).invoke("onNeighborCreated", any(InstanceIdentifier.class), any(Neighbor.class));
+ verifyPrivate(spyDeployer).invoke("onNeighborsChanged",
+ any(DataObjectModification.class), any(InstanceIdentifier.class));
verify(this.blueprintContainer).getComponentInstance(eq("bgpPeer"));
- verifyPrivate(spyDeployer)
- .invoke("initiatePeerInstance", any(InstanceIdentifier.class), any(InstanceIdentifier.class),
- any(Neighbor.class), any(PeerBean.class));
- verifyPrivate(spyDeployer).invoke("registerPeerInstance", any(BgpPeer.class), anyString());
- verify(this.bundleContext)
- .registerService(eq(InstanceType.PEER.getServices()), any(BgpPeer.class), any(Dictionary.class));
+ verify(this.bundleContext).registerService(eq(InstanceType.PEER.getServices()),
+ any(BgpPeer.class), any(Dictionary.class));
//change with same peer already existing
spyDeployer.onDataTreeChanged(this.collection);
verify(spyDeployer, times(3)).onDataTreeChanged(any(Collection.class));
- verifyPrivate(spyDeployer, times(2))
- .invoke("onNeighborsChanged", any(DataObjectModification.class), any(InstanceIdentifier.class));
- verify(spyDeployer, times(2))
- .onNeighborModified(any(InstanceIdentifier.class), any(Neighbor.class));
- verifyPrivate(spyDeployer).invoke("onNeighborCreated", any(InstanceIdentifier.class), any(Neighbor.class));
+ verifyPrivate(spyDeployer, times(2)).invoke("onNeighborsChanged",
+ any(DataObjectModification.class), any(InstanceIdentifier.class));
verify(this.blueprintContainer).getComponentInstance(eq("bgpPeer"));
- verifyPrivate(spyDeployer)
- .invoke("initiatePeerInstance", any(InstanceIdentifier.class), any(InstanceIdentifier.class),
- any(Neighbor.class), any(PeerBean.class));
- verifyPrivate(spyDeployer).invoke("registerPeerInstance", any(Neighbor.class), anyString());
- verify(this.bundleContext)
- .registerService(eq(InstanceType.PEER.getServices()), any(BgpPeer.class), any(Dictionary.class));
+ verify(this.bundleContext).registerService(eq(InstanceType.PEER.getServices()),
+ any(BgpPeer.class), any(Dictionary.class));
//Update for existing rib
configureNeighbor(IPV6UNICAST.class);
spyDeployer.onDataTreeChanged(this.collection);
verify(spyDeployer, times(4)).onDataTreeChanged(any(Collection.class));
- verifyPrivate(spyDeployer, times(3))
- .invoke("onNeighborsChanged", any(DataObjectModification.class), any(InstanceIdentifier.class));
- verify(spyDeployer, times(3))
- .onNeighborModified(any(InstanceIdentifier.class), any(Neighbor.class));
- verifyPrivate(spyDeployer).invoke("onNeighborCreated", any(InstanceIdentifier.class), any(Neighbor.class));
+ verifyPrivate(spyDeployer, times(3)).invoke("onNeighborsChanged",
+ any(DataObjectModification.class), any(InstanceIdentifier.class));
verify(this.blueprintContainer).getComponentInstance(eq("bgpPeer"));
- verifyPrivate(spyDeployer, times(2))
- .invoke("initiatePeerInstance", any(InstanceIdentifier.class), any(InstanceIdentifier.class),
- any(Neighbor.class), any(PeerBean.class));
- verifyPrivate(spyDeployer, times(2))
- .invoke("registerPeerInstance", any(Neighbor.class), anyString());
verify(this.bundleContext, times(2))
.registerService(eq(InstanceType.PEER.getServices()), any(BgpPeer.class), any(Dictionary.class));
spyDeployer.onDataTreeChanged(this.collection);
verify(spyDeployer, times(5)).onDataTreeChanged(any(Collection.class));
verify(this.dObject).getDataBefore();
- verifyPrivate(spyDeployer, times(4))
- .invoke("onNeighborsChanged", any(DataObjectModification.class), any(InstanceIdentifier.class));
- verify(spyDeployer, times(3))
- .onNeighborModified(any(InstanceIdentifier.class), any(Neighbor.class));
- verify(spyDeployer, times(1))
- .onNeighborRemoved(any(InstanceIdentifier.class), any(Neighbor.class));
- verifyPrivate(spyDeployer).invoke("onNeighborCreated", any(InstanceIdentifier.class), any(Neighbor.class));
- verify(this.blueprintContainer).getComponentInstance(eq("bgpPeer"));
- verifyPrivate(spyDeployer, times(2))
- .invoke("initiatePeerInstance", any(InstanceIdentifier.class), any(InstanceIdentifier.class),
- any(Neighbor.class), any(PeerBean.class));
- verifyPrivate(spyDeployer, times(2))
- .invoke("registerPeerInstance", any(Neighbor.class), anyString());
+ verifyPrivate(spyDeployer, times(4)).invoke("onNeighborsChanged",
+ any(DataObjectModification.class), any(InstanceIdentifier.class));
verify(this.bundleContext, times(2))
.registerService(eq(InstanceType.PEER.getServices()), any(BgpPeer.class), any(Dictionary.class));
import org.junit.Test;
import org.mockito.Mockito;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
import org.opendaylight.protocol.concepts.KeyMapping;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafi;
import org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.multiprotocol.rev151009.bgp.common.afi.safi.list.AfiSafiBuilder;
public class BgpPeerTest extends AbstractConfig {
static final short SHORT = 0;
static final IpAddress NEIGHBOR_ADDRESS = new IpAddress(new Ipv4Address("127.0.0.1"));
- static final BigDecimal DEFAULT_TIMERS = BigDecimal.valueOf(30);
static final String MD5_PASSWORD = "123";
static final PortNumber PORT = new PortNumber(179);
static final AfiSafi AFI_SAFI_IPV4 = new AfiSafiBuilder().setAfiSafiName(IPV4UNICAST.class)
.addAugmentation(AfiSafi1.class, new AfiSafi1Builder().setReceive(true).setSendMax(SHORT).build()).build();
static final List<AfiSafi> AFI_SAFI = Collections.singletonList(AFI_SAFI_IPV4);
+ private static final BigDecimal DEFAULT_TIMERS = BigDecimal.valueOf(30);
private BgpPeer bgpPeer;
static Neighbor createNeighborExpected(final IpAddress neighborAddress) {
}
static Transport createTransport() {
- return new TransportBuilder().setConfig(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp
- .rev151009.bgp.neighbor.group.transport.ConfigBuilder().setMtuDiscovery(false).setPassiveMode(false)
- .addAugmentation(Config1.class, new Config1Builder().setRemotePort(PORT).build()).build()).build();
+ return new TransportBuilder().setConfig(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.
+ rev151009.bgp.neighbor.group.transport.ConfigBuilder().setMtuDiscovery(false)
+ .setPassiveMode(false).addAugmentation(Config1.class, new Config1Builder()
+ .setRemotePort(PORT).build()).build()).build();
}
static Timers createTimers() {
return new TimersBuilder().setConfig(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009
- .bgp.neighbor.group.timers.ConfigBuilder().setHoldTime(DEFAULT_TIMERS)
+ .bgp.neighbor.group.timers.ConfigBuilder()
+ .setHoldTime(DEFAULT_TIMERS)
.setMinimumAdvertisementInterval(DEFAULT_TIMERS)
- .setKeepaliveInterval(DEFAULT_TIMERS).setConnectRetry(DEFAULT_TIMERS).build()).build();
+ .setKeepaliveInterval(DEFAULT_TIMERS)
+ .setConnectRetry(DEFAULT_TIMERS).build()).build();
}
static RouteReflector createRR() {
}
static Config createConfig() {
- return new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group
- .ConfigBuilder().setPeerAs(AS).setPeerType(PeerType.INTERNAL).setAuthPassword(MD5_PASSWORD)
- .setRouteFlapDamping(false).setSendCommunity(CommunityType.NONE).build();
+ return new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.neighbor.group.
+ ConfigBuilder()
+ .setPeerAs(AS)
+ .setPeerType(PeerType.INTERNAL)
+ .setAuthPassword(MD5_PASSWORD)
+ .setRouteFlapDamping(false)
+ .setSendCommunity(CommunityType.NONE).build();
}
static AfiSafis createAfiSafi() {
Mockito.verify(this.rib).createPeerChain(any());
Mockito.verify(this.rib, times(2)).getLocalAs();
Mockito.verify(this.rib).getLocalTables();
- Mockito.verify(this.rib).getRibIServiceGroupIdentifier();
- Mockito.verify(this.rib).registerClusterSingletonService(any(ClusterSingletonService.class));
- this.singletonService.instantiateServiceInstance();
+ this.bgpPeer.instantiateServiceInstance();
Mockito.verify(this.bgpPeerRegistry).addPeer(any(), any(), any());
Mockito.verify(this.dispatcher).createReconnectingClient(any(InetSocketAddress.class),
anyInt(), any(KeyMapping.class));
assertEquals("Previous peer instance was not closed.", expected.getMessage());
}
this.bgpPeer.setServiceRegistration(this.serviceRegistration);
+ this.bgpPeer.closeServiceInstance();
this.bgpPeer.close();
- Mockito.verify(this.singletonServiceRegistration).close();
Mockito.verify(this.future).cancel(true);
this.bgpPeer.restart(this.rib, this.tableTypeRegistry);
+ this.bgpPeer.instantiateServiceInstance();
Mockito.verify(this.rib, times(2)).createPeerChain(any());
Mockito.verify(this.rib, times(4)).getLocalAs();
Mockito.verify(this.rib, times(2)).getLocalTables();
- Mockito.verify(this.rib, times(2)).getRibIServiceGroupIdentifier();
- Mockito.verify(this.rib, times(2)).registerClusterSingletonService(any(ClusterSingletonService.class));
- this.singletonService.instantiateServiceInstance();
final Neighbor neighborExpected = createNeighborExpected(NEIGHBOR_ADDRESS);
assertTrue(this.bgpPeer.containsEqualConfiguration(neighborExpected));
- assertFalse(this.bgpPeer.containsEqualConfiguration(createNeighborExpected(new IpAddress(new Ipv4Address("127.0.0.2")))));
+ assertFalse(this.bgpPeer.containsEqualConfiguration(createNeighborExpected(
+ new IpAddress(new Ipv4Address("127.0.0.2")))));
Mockito.verify(this.bgpPeerRegistry).removePeer(any(IpAddress.class));
+ this.bgpPeer.closeServiceInstance();
this.bgpPeer.close();
- Mockito.verify(this.singletonServiceRegistration, times(2)).close();
Mockito.verify(this.serviceRegistration).unregister();
Mockito.verify(this.future, times(2)).cancel(true);
import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeFactory;
import org.opendaylight.mdsal.binding.generator.impl.GeneratedClassLoadingStrategy;
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.ServiceGroupIdentifier;
import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
import org.opendaylight.protocol.bgp.rib.impl.RIBImpl;
import org.opendaylight.protocol.bgp.rib.spi.RIBExtensionConsumerContext;
public class RibImplTest extends AbstractConfig {
private static final List<AfiSafi> AFISAFIS = new ArrayList<>();
private static final Long ALL_PATHS = 0L;
- private static final BgpTableType TABLE_TYPE =
- new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
+ private static final BgpTableType TABLE_TYPE = new BgpTableTypeImpl(Ipv4AddressFamily.class,
+ UnicastSubsequentAddressFamily.class);
private static final Ipv4Address BGP_ID = new BgpId(new Ipv4Address("127.0.0.1"));
static {
@Mock
private DOMSchemaService domSchemaService;
@Mock
- private ClusterSingletonServiceProvider clusterSingletonServiceProvider;
- @Mock
private ListenerRegistration<?> dataTreeRegistration;
@Mock
private RIBSupport ribSupport;
@Mock
private ServiceRegistration<?> serviceRegistration;
- private static Global createGlobal() {
- return new GlobalBuilder()
- .setAfiSafis(new AfiSafisBuilder().setAfiSafi(AFISAFIS).build())
- .setConfig(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.global.base
- .ConfigBuilder().setAs(AS).setRouterId(BGP_ID).build()).build();
- }
-
@Override
@Before
public void setUp() throws Exception {
super.setUp();
- Mockito.doAnswer(invocationOnMock -> {
- RibImplTest.this.singletonService = (ClusterSingletonService) invocationOnMock.getArguments()[0];
- return RibImplTest.this.singletonServiceRegistration;
- }).when(this.clusterSingletonServiceProvider)
- .registerClusterSingletonService(any(ClusterSingletonService.class));
Mockito.doReturn(mock(GeneratedClassLoadingStrategy.class)).when(this.extension).getClassLoadingStrategy();
Mockito.doReturn(this.ribSupport).when(this.extension).getRIBSupport(any(TablesKey.class));
@Test
public void testRibImpl() throws Exception {
- final RibImpl ribImpl = new RibImpl(this.clusterSingletonServiceProvider, this.extension, this.dispatcher,
+ final RibImpl ribImpl = new RibImpl(this.extension, this.dispatcher,
this.bindingCodecTreeFactory, this.domDataBroker, this.domSchemaService);
ribImpl.setServiceRegistration(this.serviceRegistration);
ribImpl.start(createGlobal(), "rib-test", this.tableTypeRegistry);
verify(this.extension).getClassLoadingStrategy();
verify(this.domDataBroker).getSupportedExtensions();
- verify(this.clusterSingletonServiceProvider).registerClusterSingletonService(any());
verify(this.domSchemaService).registerSchemaContextListener(any(RIBImpl.class));
- this.singletonService.instantiateServiceInstance();
assertEquals("RIBImpl{}", ribImpl.toString());
- assertEquals(ServiceGroupIdentifier.create("rib-test-service-group"), ribImpl.getRibIServiceGroupIdentifier());
assertEquals(Collections.singleton(new TablesKey(Ipv4AddressFamily.class,
UnicastSubsequentAddressFamily.class)), ribImpl.getLocalTablesKeys());
assertNotNull(ribImpl.getImportPolicyPeerTracker());
verify(this.dataTreeRegistration).close();
verify(this.serviceRegistration).unregister();
}
+
+ private static Global createGlobal() {
+ return new GlobalBuilder()
+ .setAfiSafis(new AfiSafisBuilder().setAfiSafi(AFISAFIS).build())
+ .setConfig(new org.opendaylight.yang.gen.v1.http.openconfig.net.yang.bgp.rev151009.bgp.global.base
+ .ConfigBuilder().setAs(AS).setRouterId(BGP_ID).build()).build();
+ }
}
\ No newline at end of file