BGPCEP-730: Fix ModifiedNodeDoesNotExistException 50/65850/16
authorClaudio D. Gasparini <claudio.gasparini@pantheon.tech>
Mon, 20 Nov 2017 13:44:06 +0000 (14:44 +0100)
committerClaudio D. Gasparini <claudio.gasparini@pantheon.tech>
Fri, 8 Dec 2017 17:44:58 +0000 (17:44 +0000)
Create wrapper for handle Cluster Singleton
Servise.
Previous implementation was done on RIbs and Peers,
if the registration failed for Rib, Peer could still
registering and given per true that Rib was initialized.
Ending on race condition and false assumption under DS.

Change-Id: I15263684d01220882d126ed6dcd6c152d74263dc
Signed-off-by: Claudio D. Gasparini <claudio.gasparini@pantheon.tech>
23 files changed:
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/AdjRibInWriter.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/EffectiveRibInWriter.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/RIBImpl.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/AppPeer.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BGPClusterSingletonService.java [new file with mode: 0644]
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpDeployerImpl.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpPeer.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/PeerBean.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/RibImpl.java
bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/spi/RIB.java
bgp/rib-impl/src/main/resources/org/opendaylight/blueprint/bgp-rib.xml
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AbstractRIBTestSetup.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AddPathAllPathsTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AddPathBasePathsTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AddPathNPathsTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/ParserToSalTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/SynchronizationAndExceptionTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/SynchronizationTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/AbstractConfig.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/AppPeerTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpDeployerImplTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/BgpPeerTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/config/RibImplTest.java

index 0c3807729ab318255515c8b7962ab54d4dd01215..64c9075b78f16933d611fee59303173ffc72ed9a 100644 (file)
@@ -62,18 +62,21 @@ import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContaine
 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);
@@ -98,7 +101,8 @@ final class AdjRibInWriter {
     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);
@@ -110,12 +114,12 @@ final class AdjRibInWriter {
     /**
      * 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());
     }
 
@@ -124,30 +128,30 @@ final class AdjRibInWriter {
      * 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();
                 }
@@ -155,9 +159,9 @@ final class AdjRibInWriter {
 
             @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);
                 }
@@ -168,6 +172,7 @@ final class AdjRibInWriter {
 
     /**
      * Create new table instances, potentially creating their empty entries
+     *
      * @param newPeerPath
      * @param registry
      * @param tableTypes
@@ -176,8 +181,8 @@ final class AdjRibInWriter {
      * @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) {
@@ -210,15 +215,15 @@ final class AdjRibInWriter {
     }
 
     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());
@@ -246,7 +251,7 @@ final class AdjRibInWriter {
         }
         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)) {
@@ -255,8 +260,10 @@ final class AdjRibInWriter {
         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();
@@ -320,12 +327,12 @@ final class AdjRibInWriter {
 
     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);
         }
     }
 }
index 40dce67b7fdee204c316893e2d6b5eb9619b6240..65c21974d741440ba9e053e20f625439798747c2 100644 (file)
@@ -234,7 +234,7 @@ final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesIn
         }
 
         @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
@@ -291,7 +291,7 @@ final class EffectiveRibInWriter implements PrefixesReceivedCounters, PrefixesIn
         }
 
         @Override
-        public void close() {
+        public synchronized void close() {
             this.reg.close();
             this.prefixesReceived.values().forEach(LongAdder::reset);
             this.prefixesInstalled.values().forEach(LongAdder::reset);
index 325297f6b8cfee94a77f0b4c830e0a56d844387b..86298afa2792f04688038abe451a01e88f13961d 100755 (executable)
@@ -22,6 +22,7 @@ import java.util.List;
 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;
@@ -40,7 +41,6 @@ import org.opendaylight.mdsal.binding.generator.impl.GeneratedClassLoadingStrate
 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;
@@ -84,7 +84,7 @@ import org.slf4j.Logger;
 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();
@@ -100,24 +100,22 @@ public final class RIBImpl extends BGPRIBStateImpl implements ClusterSingletonSe
     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);
@@ -137,9 +135,6 @@ public final class RIBImpl extends BGPRIBStateImpl implements ClusterSingletonSe
         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) {
@@ -148,9 +143,6 @@ public final class RIBImpl extends BGPRIBStateImpl implements ClusterSingletonSe
             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) {
@@ -305,12 +297,10 @@ public final class RIBImpl extends BGPRIBStateImpl implements ClusterSingletonSe
         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))
@@ -342,14 +332,12 @@ public final class RIBImpl extends BGPRIBStateImpl implements ClusterSingletonSe
         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);
 
@@ -363,21 +351,4 @@ public final class RIBImpl extends BGPRIBStateImpl implements ClusterSingletonSe
         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();
-    }
 }
index 43e0d8bdb52eaa2de22179a740c373e89a559483..4ea4e3fa22102e365951b3b6a323da78fe4bca65 100644 (file)
@@ -17,9 +17,6 @@ import javax.annotation.concurrent.GuardedBy;
 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;
@@ -73,12 +70,7 @@ public final class AppPeer implements PeerBean, BGPPeerStateConsumer {
     @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();
@@ -86,6 +78,13 @@ public final class AppPeer implements PeerBean, BGPPeerStateConsumer {
         }
     }
 
+    @Override
+    public synchronized void instantiateServiceInstance() {
+        if (this.bgpAppPeerSingletonService != null) {
+            this.bgpAppPeerSingletonService.instantiateServiceInstance();
+        }
+    }
+
     @Override
     public synchronized ListenableFuture<Void> closeServiceInstance() {
         if (this.bgpAppPeerSingletonService != null) {
@@ -110,13 +109,10 @@ public final class AppPeer implements PeerBean, BGPPeerStateConsumer {
         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;
 
@@ -124,26 +120,10 @@ public final class AppPeer implements PeerBean, BGPPeerStateConsumer {
             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();
@@ -151,24 +131,16 @@ public final class AppPeer implements PeerBean, BGPPeerStateConsumer {
                     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();
diff --git a/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BGPClusterSingletonService.java b/bgp/rib-impl/src/main/java/org/opendaylight/protocol/bgp/rib/impl/config/BGPClusterSingletonService.java
new file mode 100644 (file)
index 0000000..39f27b4
--- /dev/null
@@ -0,0 +1,314 @@
+/*
+ * 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();
+        }
+    }
+}
index 75560c3ccc44bf5c8b02f52445863f4b504f88ce..2b8bf6594d723f7de64b210c952bb2fc3ed8944e 100644 (file)
@@ -8,25 +8,16 @@
 
 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;
@@ -35,9 +26,8 @@ import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
 import org.opendaylight.controller.md.sal.binding.api.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;
@@ -53,7 +43,6 @@ import org.opendaylight.yangtools.concepts.ListenerRegistration;
 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;
@@ -64,51 +53,46 @@ public final class BgpDeployerImpl implements ClusteredDataTreeChangeListener<Bg
     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
@@ -121,7 +105,8 @@ public final class BgpDeployerImpl implements ClusteredDataTreeChangeListener<Bg
             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)) {
@@ -131,11 +116,6 @@ public final class BgpDeployerImpl implements ClusteredDataTreeChangeListener<Bg
         }
     }
 
-    @VisibleForTesting
-    public InstanceIdentifier<NetworkInstance> getInstanceIdentifier() {
-        return this.networkInstanceIId;
-    }
-
     @Override
     public synchronized void close() throws Exception {
         LOG.info("Closing BGP Deployer.");
@@ -145,213 +125,49 @@ public final class BgpDeployerImpl implements ClusteredDataTreeChangeListener<Bg
         }
         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() {
index ac1ee7392c1a27a388b9c664bb59c7e3344cfdce..0641841998e7360e99a8b4e08f90131c3932d73e 100644 (file)
@@ -27,9 +27,7 @@ import java.util.Objects;
 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;
@@ -96,17 +94,18 @@ public final class BgpPeer implements PeerBean, BGPPeerStateConsumer {
         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(
@@ -149,6 +148,13 @@ public final class BgpPeer implements PeerBean, BGPPeerStateConsumer {
         }
     }
 
+    @Override
+    public synchronized void instantiateServiceInstance() {
+        if (this.bgpPeerSingletonService != null) {
+            this.bgpPeerSingletonService.instantiateServiceInstance();
+        }
+    }
+
     @Override
     public synchronized ListenableFuture<Void> closeServiceInstance() {
         if (this.bgpPeerSingletonService != null) {
@@ -202,18 +208,16 @@ public final class BgpPeer implements PeerBean, BGPPeerStateConsumer {
         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;
@@ -225,21 +229,19 @@ public final class BgpPeer implements PeerBean, BGPPeerStateConsumer {
             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
@@ -250,11 +252,9 @@ public final class BgpPeer implements PeerBean, BGPPeerStateConsumer {
             }
         }
 
-        @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) {
@@ -263,14 +263,12 @@ public final class BgpPeer implements PeerBean, BGPPeerStateConsumer {
             }
         }
 
-        @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);
@@ -283,11 +281,6 @@ public final class BgpPeer implements PeerBean, BGPPeerStateConsumer {
             return future;
         }
 
-        @Override
-        public ServiceGroupIdentifier getIdentifier() {
-            return this.serviceGroupIdentifier;
-        }
-
         @Override
         public BGPPeerState getPeerState() {
             return this.bgpPeer.getPeerState();
index 1a89f4329f92264fc5cd6a7e8dc8dcc1513da200..a80326e11eec02d328b618b42095f1818de553b2 100644 (file)
@@ -25,6 +25,8 @@ public interface PeerBean extends AutoCloseable {
     @Override
     void close();
 
+    void instantiateServiceInstance();
+
     ListenableFuture<Void> closeServiceInstance();
 
     Boolean containsEqualConfiguration(Neighbor neighbor);
index b48b3390e2e1b5f9903d4b7b37b650a04c666cbc..554231d72c85512b642d46f5290c53c325303d29 100644 (file)
@@ -8,7 +8,6 @@
 
 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;
@@ -26,10 +25,6 @@ import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
 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;
@@ -74,17 +69,15 @@ public final class RibImpl implements RIB, BGPRIBStateConsumer, AutoCloseable {
     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;
@@ -166,7 +159,7 @@ public final class RibImpl implements RIB, BGPRIBStateConsumer, AutoCloseable {
         return this.ribImpl.getService();
     }
 
-    public ListenableFuture<Void> closeServiceInstance() {
+    ListenableFuture<Void> closeServiceInstance() {
         if (this.ribImpl != null) {
             return this.ribImpl.closeServiceInstance();
         }
@@ -216,11 +209,6 @@ public final class RibImpl implements RIB, BGPRIBStateConsumer, AutoCloseable {
         return this.ribImpl.getLocalTablesKeys();
     }
 
-    @Override
-    public ServiceGroupIdentifier getRibIServiceGroupIdentifier() {
-        return this.ribImpl.getRibIServiceGroupIdentifier();
-    }
-
     @Override
     public String toString() {
         return this.ribImpl != null ? this.ribImpl.toString() : null;
@@ -240,7 +228,7 @@ public final class RibImpl implements RIB, BGPRIBStateConsumer, AutoCloseable {
                 .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),
@@ -254,14 +242,14 @@ public final class RibImpl implements RIB, BGPRIBStateConsumer, AutoCloseable {
                 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();
+        }
+    }
 }
index 074a9aa54082498972e8a77e61e09145b3913745..e49bb1e8c58e1647f1588cf73ff378401f53b4f9 100755 (executable)
@@ -26,7 +26,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 /**
  * Internal reference to a RIB instance.
  */
-public interface RIB extends RibReference, ClusterSingletonServiceProvider {
+public interface RIB extends RibReference {
     AsNumber getLocalAs();
 
     BgpId getBgpIdentifier();
@@ -96,11 +96,4 @@ public interface RIB extends RibReference, ClusterSingletonServiceProvider {
     ExportPolicyPeerTracker getExportPolicyPeerTracker(TablesKey tablesKey);
 
     Set<TablesKey> getLocalTablesKeys();
-
-    /**
-     * Return common ServiceGroupIdentifier to be used between same group cluster service
-     *
-     * @return ServiceGroupIdentifier
-     */
-    ServiceGroupIdentifier getRibIServiceGroupIdentifier();
 }
index 418fd0e3d688c27fe607caf4b39d0b5bad8a0aec..b5bce64cb604e460eb05a69ca36ec15e1a782d78 100644 (file)
@@ -54,6 +54,7 @@
         init-method="init"
         destroy-method="close">
     <argument value="global-bgp"/>
+    <argument ref="clusterSingletonServiceProvider"/>
     <argument ref="blueprintContainer"/>
     <argument ref="blueprintBundleContext"/>
     <argument ref="dataBroker"/>
@@ -61,7 +62,6 @@
   </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"/>
index ac5b06faa0af579cbe126cd599ff83eb3dbbc972..08b4041d891692cf4b9623a9d4b1fe2894a828ab 100644 (file)
@@ -8,7 +8,11 @@
 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;
@@ -25,7 +29,6 @@ import javassist.ClassPool;
 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;
@@ -95,6 +98,8 @@ public class AbstractRIBTestSetup {
 
     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");
@@ -146,7 +151,8 @@ public class AbstractRIBTestSetup {
     }
 
     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;
@@ -168,10 +174,9 @@ public class AbstractRIBTestSetup {
         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()),
@@ -183,61 +188,74 @@ public class AbstractRIBTestSetup {
     @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();
     }
 
index b99d55eb42a6a958969dbae1e45c31085fa2352e..7ab75c5d9311ac047774ef99b231e3cff7c0e094 100644 (file)
@@ -54,8 +54,8 @@ public class AddPathAllPathsTest extends AbstractAddPathTest {
         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();
index e294b523023b9d154fed64e5ff76cbe8a1ea9ff1..85d7a753812baac3e73cdab77e63138671d81294 100644 (file)
@@ -42,7 +42,7 @@ public class AddPathBasePathsTest extends AbstractAddPathTest {
         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());
index 4bad2dcc2b485880b715af1b068ba3fe0692a151..f31379178ad8f52794b64b3ddb7b630f18698b22 100644 (file)
@@ -39,9 +39,10 @@ public class AddPathNPathsTest extends AbstractAddPathTest {
     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());
index ce0ae9ac25d1228850a5eeeb376b175cb3a87cad..42da7a773042f10aa40b870406e26e265f67e591 100755 (executable)
@@ -9,8 +9,6 @@ package org.opendaylight.protocol.bgp.rib.impl;
 
 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;
@@ -37,9 +35,6 @@ import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 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;
@@ -84,8 +79,6 @@ public class ParserToSalTest extends AbstractConcurrentDataBrokerTest {
 
     @Mock
     private BGPDispatcher dispatcher;
-    @Mock
-    private ClusterSingletonServiceProvider clusterSingletonServiceProvider;
     private BindingCodecTreeFactory codecFactory;
 
     private DOMSchemaService schemaService;
@@ -97,11 +90,11 @@ public class ParserToSalTest extends AbstractConcurrentDataBrokerTest {
         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();
@@ -110,16 +103,14 @@ public class ParserToSalTest extends AbstractConcurrentDataBrokerTest {
 
         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
@@ -139,17 +130,17 @@ public class ParserToSalTest extends AbstractConcurrentDataBrokerTest {
     @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();
@@ -158,16 +149,16 @@ public class ParserToSalTest extends AbstractConcurrentDataBrokerTest {
     @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();
@@ -184,7 +175,7 @@ public class ParserToSalTest extends AbstractConcurrentDataBrokerTest {
     }
 
     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());
index 54edeb000cf4303d4427f2b4051c066ff2e7ba6a..c8be49fe8bac4357e7555f021e9a7c901712f9a5 100644 (file)
@@ -143,15 +143,12 @@ public class SynchronizationAndExceptionTest extends AbstractAddPathTest {
                 .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());
@@ -172,9 +169,11 @@ public class SynchronizationAndExceptionTest extends AbstractAddPathTest {
                 .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());
@@ -207,11 +206,10 @@ public class SynchronizationAndExceptionTest extends AbstractAddPathTest {
     @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);
 
@@ -256,11 +254,10 @@ public class SynchronizationAndExceptionTest extends AbstractAddPathTest {
     @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);
 
index f5a96f6f81b840f58ff42b58f55d71118b071c2a..0377635e6df65f93e00b7b53d04a6f41046cc829 100644 (file)
@@ -52,7 +52,8 @@ public class SynchronizationTest {
     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();
index 21d3d8a744a61996da6326e690acee5fd7f6a7de..2fbd7f2f056db306517bec9b5e0d9c165472a2c1 100644 (file)
@@ -27,9 +27,6 @@ import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListen
 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;
@@ -61,15 +58,11 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 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;
@@ -89,29 +82,31 @@ class AbstractConfig {
     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];
@@ -123,27 +118,25 @@ class AbstractConfig {
         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();
index 583f5aa2cb8d88902b692c866924b0565a12c8e3..bed3355531fdce87b43eda0c120ea47e2d179c46 100644 (file)
@@ -10,13 +10,11 @@ package org.opendaylight.protocol.bgp.rib.impl.config;
 
 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;
@@ -27,8 +25,10 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.open
 
 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
@@ -42,32 +42,27 @@ public class AppPeerTest extends AbstractConfig {
         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
index 9b68453d18a041e684b56cb508bf8d70d3249aa9..8dd5d97612a30e30a66505a6d4881be1c0c1cedd 100644 (file)
@@ -10,7 +10,6 @@ package org.opendaylight.protocol.bgp.rib.impl.config;
 
 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;
@@ -118,7 +117,7 @@ public class BgpDeployerImplTest {
     private static final short SHORT = 0;
 
     @Mock
-    DataObjectModification<?> dObject;
+    private DataObjectModification<?> dObject;
     @Mock
     private BlueprintContainer blueprintContainer;
     @Mock
@@ -135,6 +134,8 @@ public class BgpDeployerImplTest {
     private ListenerRegistration<?> dataTreeRegistration;
     @Mock
     private ServiceRegistration<?> registration;
+    @Mock
+    private ClusterSingletonServiceProvider singletonServiceProvider;
 
     private Collection<DataTreeModification<Bgp>> collection = Collections.singleton(this.modification);
 
@@ -171,10 +172,10 @@ public class BgpDeployerImplTest {
         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),
@@ -201,9 +202,8 @@ public class BgpDeployerImplTest {
         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);
@@ -211,8 +211,8 @@ public class BgpDeployerImplTest {
 
         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));
@@ -223,13 +223,13 @@ public class BgpDeployerImplTest {
     @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));
@@ -237,84 +237,51 @@ public class BgpDeployerImplTest {
                 .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();
@@ -323,9 +290,8 @@ public class BgpDeployerImplTest {
     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();
     }
@@ -336,35 +302,26 @@ public class BgpDeployerImplTest {
     @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));
@@ -375,54 +332,32 @@ public class BgpDeployerImplTest {
         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));
 
@@ -432,19 +367,8 @@ public class BgpDeployerImplTest {
         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));
 
index 54c1a2a4e6f2d43ce8a4f8d08b3df1d2c3dc739b..d3d26cb51c5092dce062bb25fe1990238b181382 100644 (file)
@@ -24,7 +24,6 @@ import org.junit.Before;
 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;
@@ -57,12 +56,12 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.open
 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) {
@@ -78,16 +77,19 @@ public class BgpPeerTest extends AbstractConfig {
     }
 
     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() {
@@ -98,9 +100,13 @@ public class BgpPeerTest extends AbstractConfig {
     }
 
     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() {
@@ -129,10 +135,8 @@ public class BgpPeerTest extends AbstractConfig {
         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));
@@ -144,25 +148,24 @@ public class BgpPeerTest extends AbstractConfig {
             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);
 
index be9fd44102326840e78b522f4689a87c42690ca1..65daec2108fad2c0772c075eca4498e785126498 100644 (file)
@@ -28,9 +28,6 @@ import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
 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;
@@ -58,8 +55,8 @@ import org.osgi.framework.ServiceRegistration;
 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 {
@@ -77,30 +74,16 @@ public class RibImplTest extends AbstractConfig {
     @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));
@@ -124,17 +107,14 @@ public class RibImplTest extends AbstractConfig {
 
     @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());
@@ -153,4 +133,11 @@ public class RibImplTest extends AbstractConfig {
         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