Bump upstreams
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / RIBImpl.java
index 02978342ce9a6c30ddcb5d6f3c5d595b5246d9f8..622171aac35fe85ae52dc6f94ef55d07a26b52b5 100644 (file)
  */
 package org.opendaylight.protocol.bgp.rib.impl;
 
-import com.google.common.annotations.VisibleForTesting;
+import static com.google.common.base.Verify.verifyNotNull;
+import static java.util.Objects.requireNonNull;
+import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.BGPRIB_NID;
+import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.LOCRIB_NID;
+import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.PEER_NID;
+import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.RIB_NID;
+import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.TABLES_NID;
+
 import com.google.common.base.MoreObjects;
-import com.google.common.base.MoreObjects.ToStringHelper;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableSet;
+import com.google.common.util.concurrent.FluentFuture;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.MoreExecutors;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
-import java.util.Map.Entry;
+import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
-import javax.annotation.concurrent.ThreadSafe;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataBrokerExtension;
-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.protocol.bgp.rib.DefaultRibReference;
+import java.util.stream.Collectors;
+import org.checkerframework.checker.lock.qual.GuardedBy;
+import org.opendaylight.mdsal.common.api.CommitInfo;
+import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
+import org.opendaylight.mdsal.dom.api.DOMDataBroker;
+import org.opendaylight.mdsal.dom.api.DOMDataBroker.DataTreeChangeExtension;
+import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
+import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
+import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode;
+import org.opendaylight.protocol.bgp.mode.impl.base.BasePathSelectionModeFactory;
+import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
+import org.opendaylight.protocol.bgp.rib.impl.spi.CodecsRegistry;
 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
+import org.opendaylight.protocol.bgp.rib.impl.spi.RibOutRefresh;
+import org.opendaylight.protocol.bgp.rib.impl.state.BGPRibStateImpl;
+import org.opendaylight.protocol.bgp.rib.spi.BGPPeerTracker;
 import org.opendaylight.protocol.bgp.rib.spi.RIBExtensionConsumerContext;
-import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
-import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.bgp.rib.rib.loc.rib.tables.routes.Ipv4RoutesCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.bgp.rib.rib.loc.rib.tables.routes.Ipv6RoutesCase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.BgpRib;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.RibId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.Rib;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.RibKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.LocRib;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.ClusterIdentifier;
-import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeFactory;
-import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
+import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
+import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRibRoutingPolicy;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.BgpTableType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.BgpRib;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.RibId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.Rib;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.RibKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.Routes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.BgpId;
+import org.opendaylight.yangtools.yang.binding.ChildOf;
+import org.opendaylight.yangtools.yang.binding.ChoiceIn;
+import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.common.Empty;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
-import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-@ThreadSafe
-public final class RIBImpl extends DefaultRibReference implements AutoCloseable, RIB, TransactionChainListener, SchemaContextListener {
+// This class is thread-safe
+public final class RIBImpl extends BGPRibStateImpl implements RIB {
     private static final Logger LOG = LoggerFactory.getLogger(RIBImpl.class);
-    @VisibleForTesting
-    public static final QName RIB_ID_QNAME = QName.cachedReference(QName.create(Rib.QNAME, "id"));
-    @VisibleForTesting
-    public static final ContainerNode EMPTY_TABLE_ATTRIBUTES = ImmutableNodes.containerNode(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Attributes.QNAME);
-
-    private final ReconnectStrategyFactory tcpStrategyFactory;
-    private final ReconnectStrategyFactory sessionStrategyFactory;
+    private static final QName RIB_ID_QNAME = QName.create(Rib.QNAME, "id").intern();
 
     private final BGPDispatcher dispatcher;
-    private final DOMTransactionChain domChain;
     private final AsNumber localAs;
-    private final Ipv4Address bgpIdentifier;
+    private final BgpId bgpIdentifier;
     private final Set<BgpTableType> localTables;
     private final Set<TablesKey> localTablesKeys;
-    private final DataBroker dataBroker;
     private final DOMDataBroker domDataBroker;
     private final RIBExtensionConsumerContext extensions;
     private final YangInstanceIdentifier yangRibId;
     private final RIBSupportContextRegistryImpl ribContextRegistry;
-    private final EffectiveRibInWriter efWriter;
-    private final DOMDataBrokerExtension service;
-
-    public RIBImpl(final RibId ribId, final AsNumber localAs, final Ipv4Address localBgpId, final Ipv4Address clusterId, final RIBExtensionConsumerContext extensions,
-        final BGPDispatcher dispatcher, final ReconnectStrategyFactory tcpStrategyFactory, final BindingCodecTreeFactory codecFactory,
-        final ReconnectStrategyFactory sessionStrategyFactory, final DataBroker dps, final DOMDataBroker domDataBroker, final List<BgpTableType> localTables, final GeneratedClassLoadingStrategy classStrategy) {
-        super(InstanceIdentifier.create(BgpRib.class).child(Rib.class, new RibKey(Preconditions.checkNotNull(ribId))));
-        this.domChain = domDataBroker.createTransactionChain(this);
-        this.localAs = Preconditions.checkNotNull(localAs);
-        this.bgpIdentifier = Preconditions.checkNotNull(localBgpId);
-        this.dispatcher = Preconditions.checkNotNull(dispatcher);
-        this.sessionStrategyFactory = Preconditions.checkNotNull(sessionStrategyFactory);
-        this.tcpStrategyFactory = Preconditions.checkNotNull(tcpStrategyFactory);
-        this.localTables = ImmutableSet.copyOf(localTables);
-        this.localTablesKeys = new HashSet<TablesKey>();
-        this.dataBroker = dps;
-        this.domDataBroker = Preconditions.checkNotNull(domDataBroker);
-        this.extensions = Preconditions.checkNotNull(extensions);
-        this.ribContextRegistry = RIBSupportContextRegistryImpl.create(extensions, codecFactory, classStrategy);
-        this.yangRibId = YangInstanceIdentifier.builder().node(BgpRib.QNAME).node(Rib.QNAME).nodeWithKey(Rib.QNAME, RIB_ID_QNAME, ribId.getValue()).build();
-
-        LOG.debug("Instantiating RIB table {} at {}", ribId, this.yangRibId);
-
-        final ContainerNode rib = Builders.containerBuilder()
-            .withNodeIdentifier(new NodeIdentifier(BgpRib.QNAME))
-            .addChild(ImmutableNodes.mapNodeBuilder(Rib.QNAME)
-                .addChild(ImmutableNodes.mapEntryBuilder(Rib.QNAME, RIB_ID_QNAME, ribId.getValue())
-                    .addChild(ImmutableNodes.leafNode(RIB_ID_QNAME, ribId.getValue()))
-                    .addChild(ImmutableNodes.mapNodeBuilder(Peer.QNAME).build())
-                    .addChild(Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(LocRib.QNAME))
-                        .addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build())
-                        .build())
-                    .build())
-                    .build())
-            .build();
-
-
-        final DOMDataWriteTransaction trans = this.domChain.newWriteOnlyTransaction();
-
-        // put empty BgpRib if not exists
-        trans.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.builder().node(BgpRib.QNAME).build(), rib);
-
-        try {
-            trans.submit().checkedGet();
-        } catch (final TransactionCommitFailedException e) {
-            LOG.error("Failed to initiate RIB {}", this.yangRibId, e);
-        }
-        final ClusterIdentifier cId = (clusterId == null) ? new ClusterIdentifier(localBgpId) : new ClusterIdentifier(clusterId);
-        final PolicyDatabase pd  = new PolicyDatabase(localAs.getValue(), localBgpId, cId);
-
-        final DOMDataBrokerExtension domDatatreeChangeService = this.domDataBroker.getSupportedExtensions().get(DOMDataTreeChangeService.class);
-        this.service = domDatatreeChangeService;
-        this.efWriter = EffectiveRibInWriter.create(getService(), this.createPeerChain(this), getYangRibId(), pd, this.ribContextRegistry);
-        LOG.debug("Effective RIB created.");
+    private final CodecsRegistry codecsRegistry;
+    private final BGPTableTypeRegistryConsumer tableTypeRegistry;
+    private final DataTreeChangeExtension domService;
+    private final Map<DOMTransactionChain, LocRibWriter<?, ?>> txChainToLocRibWriter = new HashMap<>();
+    private final Map<TablesKey, RibOutRefresh> vpnTableRefresher = new HashMap<>();
+    private final Map<TablesKey, PathSelectionMode> bestPathSelectionStrategies;
+    private final RibId ribId;
+    private final BGPPeerTracker peerTracker = new BGPPeerTrackerImpl();
+    private final BGPRibRoutingPolicy ribPolicies;
+    @GuardedBy("this")
+    private DOMTransactionChain domChain;
+    @GuardedBy("this")
+    private boolean isServiceInstantiated;
+
+    public RIBImpl(
+            final BGPTableTypeRegistryConsumer tableTypeRegistry,
+            final RibId ribId,
+            final AsNumber localAs,
+            final BgpId localBgpId,
+            final RIBExtensionConsumerContext extensions,
+            final BGPDispatcher dispatcher,
+            final CodecsRegistry codecsRegistry,
+            final DOMDataBroker domDataBroker,
+            final BGPRibRoutingPolicy ribPolicies,
+            final List<BgpTableType> localTables,
+            final Map<TablesKey, PathSelectionMode> bestPathSelectionStrategies
+    ) {
+        super(InstanceIdentifier.create(BgpRib.class).child(Rib.class, new RibKey(requireNonNull(ribId))),
+                localBgpId, localAs);
+        this.tableTypeRegistry = requireNonNull(tableTypeRegistry);
+        this.localAs = requireNonNull(localAs);
+        bgpIdentifier = requireNonNull(localBgpId);
+        this.dispatcher = requireNonNull(dispatcher);
 
-        for (final BgpTableType t : this.localTables) {
-            final TablesKey key = new TablesKey(t.getAfi(), t.getSafi());
-            this.localTablesKeys.add(key);
-            startLocRib(key, pd);
-        }
+        this.localTables = ImmutableSet.copyOf(localTables);
+        // FIXME: can this be immutable?
+        localTablesKeys = localTables.stream()
+            .map(t -> new TablesKey(t.getAfi(), t.getSafi()))
+            .collect(Collectors.toCollection(HashSet::new));
+
+        this.domDataBroker = requireNonNull(domDataBroker);
+        domService = domDataBroker.extension(DataTreeChangeExtension.class);
+        this.extensions = requireNonNull(extensions);
+        this.ribPolicies = requireNonNull(ribPolicies);
+        this.codecsRegistry = codecsRegistry;
+        ribContextRegistry = RIBSupportContextRegistryImpl.create(extensions, codecsRegistry);
+        yangRibId = YangInstanceIdentifier.builder().node(BGPRIB_NID).node(RIB_NID)
+                .nodeWithKey(Rib.QNAME, RIB_ID_QNAME, ribId.getValue()).build();
+        this.bestPathSelectionStrategies = requireNonNull(bestPathSelectionStrategies);
+        this.ribId = ribId;
     }
 
-    private void startLocRib(final TablesKey key, final PolicyDatabase pd) {
+    // FIXME: make this asynchronous?
+    private synchronized void startLocRib(final TablesKey key) {
         LOG.debug("Creating LocRib table for {}", key);
         // create locRibWriter for each table
-        final DOMDataWriteTransaction tx = this.domChain.newWriteOnlyTransaction();
-
-        final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> table = ImmutableNodes.mapEntryBuilder();
-        table.withNodeIdentifier(RibSupportUtils.toYangTablesKey(key));
-        table.withChild(EMPTY_TABLE_ATTRIBUTES);
-
-        final NodeIdentifierWithPredicates tableKey = RibSupportUtils.toYangTablesKey(key);
-        final InstanceIdentifierBuilder tableId = YangInstanceIdentifier.builder(this.yangRibId.node(LocRib.QNAME).node(Tables.QNAME));
-        tableId.nodeWithKey(tableKey.getNodeType(), tableKey.getKeyValues());
-        for (final Entry<QName, Object> e : tableKey.getKeyValues().entrySet()) {
-            table.withChild(ImmutableNodes.leafNode(e.getKey(), e.getValue()));
+        final DOMDataTreeWriteTransaction tx = domChain.newWriteOnlyTransaction();
+
+        final RIBSupport<? extends Routes, ?> ribSupport = ribContextRegistry.getRIBSupport(key);
+        if (ribSupport != null) {
+            final MapEntryNode emptyTable = ribSupport.emptyTable();
+            final InstanceIdentifierBuilder tableId = YangInstanceIdentifier
+                    .builder(yangRibId.node(LOCRIB_NID).node(TABLES_NID)).node(emptyTable.name());
+
+            tx.put(LogicalDatastoreType.OPERATIONAL, tableId.build(), emptyTable);
+            try {
+                tx.commit().get();
+            } catch (final InterruptedException | ExecutionException e) {
+                LOG.error("Failed to initiate LocRIB for key {}", key, e);
+            }
+        } else {
+            LOG.warn("There's no registered RIB Context for {}", key.getAfi());
         }
+    }
 
-        final ChoiceNode routes = this.ribContextRegistry.getRIBSupportContext(key).getRibSupport().emptyRoutes();
-        table.withChild(routes);
-
-        tx.put(LogicalDatastoreType.OPERATIONAL, tableId.build(), table.build());
-        try {
-            tx.submit().checkedGet();
-        } catch (final TransactionCommitFailedException e1) {
-            LOG.error("Failed to initiate LocRIB for key {}", key, e1);
+    private synchronized <C extends Routes & DataObject & ChoiceIn<Tables>, S extends ChildOf<? super C>>
+            void createLocRibWriter(final TablesKey key) {
+        final RIBSupport<C, S> ribSupport = ribContextRegistry.getRIBSupport(key);
+        if (ribSupport == null) {
+            return;
+        }
+        LOG.debug("Creating LocRIB writer for key {}", key);
+        final DOMTransactionChain txChain = createPeerDOMChain();
+        addCallback(txChain);
+        PathSelectionMode pathSelectionStrategy = bestPathSelectionStrategies.get(key);
+        if (pathSelectionStrategy == null) {
+            pathSelectionStrategy = BasePathSelectionModeFactory.createBestPathSelectionStrategy();
         }
 
-        // FIXME: do not lose the writer so we clean it up on shutdown
-        LocRibWriter.create(this.ribContextRegistry, key, this.createPeerChain(this), getYangRibId(), this.localAs, getService(), pd);
+        final LocRibWriter<C, S> locRibWriter = LocRibWriter.create(
+                ribSupport,
+                verifyNotNull(tableTypeRegistry.getAfiSafiType(key)),
+                txChain,
+                yangRibId,
+                localAs,
+                getService(),
+                ribPolicies,
+                peerTracker,
+                pathSelectionStrategy);
+        vpnTableRefresher.put(key, locRibWriter);
+        registerTotalPathCounter(key, locRibWriter);
+        registerTotalPrefixesCounter(key, locRibWriter);
+        txChainToLocRibWriter.put(txChain, locRibWriter);
     }
 
     @Override
     public String toString() {
-        return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
+        return MoreObjects.toStringHelper(this).add("bgpId", bgpIdentifier).add("localTables", localTables).toString();
     }
 
-    protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
-        return toStringHelper;
+    @Override
+    public AsNumber getLocalAs() {
+        return localAs;
     }
 
     @Override
-    public synchronized void close() throws InterruptedException, ExecutionException {
-        final DOMDataWriteTransaction t = this.domChain.newWriteOnlyTransaction();
-        t.delete(LogicalDatastoreType.OPERATIONAL, getYangRibId());
-        t.submit().get();
-        this.domChain.close();
-        this.efWriter.close();
+    public BgpId getBgpIdentifier() {
+        return bgpIdentifier;
     }
 
     @Override
-    public AsNumber getLocalAs() {
-        return this.localAs;
+    public Set<? extends BgpTableType> getLocalTables() {
+        return localTables;
     }
 
     @Override
-    public Ipv4Address getBgpIdentifier() {
-        return this.bgpIdentifier;
+    public BGPDispatcher getDispatcher() {
+        return dispatcher;
     }
 
-    @Override
-    public Set<? extends BgpTableType> getLocalTables() {
-        return this.localTables;
+    private void addCallback(final DOMTransactionChain txChain) {
+        txChain.addCallback(new FutureCallback<Empty>() {
+            @Override
+            public void onSuccess(final Empty result) {
+                LOG.info("RIB {} closed successfully", getInstanceIdentifier());
+            }
+
+            @Override
+            public void onFailure(final Throwable cause) {
+                RIBImpl.this.onFailure(txChain, cause);
+            }
+        });
     }
 
-    @Override
-    public ReconnectStrategyFactory getTcpStrategyFactory() {
-        return this.tcpStrategyFactory;
+    private synchronized void onFailure(final DOMTransactionChain chain, final Throwable cause) {
+        LOG.error("Broken chain in RIB {}", getInstanceIdentifier(), cause);
+        final LocRibWriter<?, ?> locRibWriter = txChainToLocRibWriter.remove(chain);
+        if (locRibWriter != null) {
+            final DOMTransactionChain newChain = createPeerDOMChain();
+            addCallback(newChain);
+            startLocRib(locRibWriter.getTableKey());
+            locRibWriter.restart(newChain);
+            txChainToLocRibWriter.put(newChain, locRibWriter);
+        }
     }
 
     @Override
-    public ReconnectStrategyFactory getSessionStrategyFactory() {
-        return this.sessionStrategyFactory;
+    public Set<TablesKey> getLocalTablesKeys() {
+        return localTablesKeys;
     }
 
     @Override
-    public BGPDispatcher getDispatcher() {
-        return this.dispatcher;
+    public boolean supportsTable(final TablesKey tableKey) {
+        return localTablesKeys.contains(tableKey);
     }
 
     @Override
-    public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
-        LOG.error("Broken chain in RIB {} transaction {}", getInstanceIdentifier(), transaction.getIdentifier(), cause);
+    public BGPRibRoutingPolicy getRibPolicies() {
+        return ribPolicies;
     }
 
     @Override
-    public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
-        LOG.info("RIB {} closed successfully", getInstanceIdentifier());
+    public BGPPeerTracker getPeerTracker() {
+        return peerTracker;
     }
 
     @Override
-    public long getRoutesCount(final TablesKey key) {
-        try (final ReadOnlyTransaction tx = this.dataBroker.newReadOnlyTransaction()) {
-            final Optional<Tables> tableMaybe = tx.read(LogicalDatastoreType.OPERATIONAL,
-                    getInstanceIdentifier().child(LocRib.class).child(Tables.class, key)).checkedGet();
-            if (tableMaybe.isPresent()) {
-                final Tables table = tableMaybe.get();
-                if (table.getRoutes() instanceof Ipv4RoutesCase) {
-                    final Ipv4RoutesCase routesCase = (Ipv4RoutesCase) table.getRoutes();
-                    if (routesCase.getIpv4Routes() != null && routesCase.getIpv4Routes().getIpv4Route() != null) {
-                        return routesCase.getIpv4Routes().getIpv4Route().size();
-                    }
-                } else if (table.getRoutes() instanceof Ipv6RoutesCase) {
-                    final Ipv6RoutesCase routesCase = (Ipv6RoutesCase) table.getRoutes();
-                    if (routesCase.getIpv6Routes() != null && routesCase.getIpv6Routes().getIpv6Route() != null) {
-                        return routesCase.getIpv6Routes().getIpv6Route().size();
-                    }
-                }
-            }
-        } catch (final ReadFailedException e) {
-            LOG.debug("Failed to read tables", e);
+    public void refreshTable(final TablesKey tk, final PeerId peerId) {
+        final RibOutRefresh table = vpnTableRefresher.get(tk);
+        if (table != null) {
+            table.refreshTable(tk, peerId);
         }
-        return 0;
-    }
-
-    public Set<TablesKey> getLocalTablesKeys() {
-        return this.localTablesKeys;
     }
 
-    public DOMDataTreeChangeService getService() {
-        return (DOMDataTreeChangeService) this.service;
+    @Override
+    public DataTreeChangeExtension getService() {
+        return domService;
     }
 
     @Override
     public YangInstanceIdentifier getYangRibId() {
-        return this.yangRibId;
+        return yangRibId;
     }
 
     @Override
-    public DOMTransactionChain createPeerChain(final TransactionChainListener listener) {
-        return this.domDataBroker.createTransactionChain(listener);
+    public DOMTransactionChain createPeerDOMChain() {
+        return domDataBroker.createMergingTransactionChain();
     }
 
     @Override
     public RIBExtensionConsumerContext getRibExtensions() {
-        return this.extensions;
+        return extensions;
     }
 
     @Override
     public RIBSupportContextRegistry getRibSupportContext() {
-        return this.ribContextRegistry;
+        return ribContextRegistry;
     }
 
     @Override
-    public void onGlobalContextUpdated(final SchemaContext context) {
-        this.ribContextRegistry.onSchemaContextUpdated(context);
+    public CodecsRegistry getCodecsRegistry() {
+        return codecsRegistry;
+    }
+
+    public synchronized void instantiateServiceInstance() {
+        LOG.debug("Instantiating RIB table {} at {}", ribId, yangRibId);
+
+        isServiceInstantiated = true;
+        setActive(true);
+        domChain = domDataBroker.createMergingTransactionChain();
+        addCallback(domChain);
+
+        final ContainerNode bgpRib = Builders.containerBuilder().withNodeIdentifier(BGPRIB_NID)
+                .addChild(ImmutableNodes.mapNodeBuilder(RIB_NID).build()).build();
+
+        final MapEntryNode ribInstance = Builders.mapEntryBuilder().withNodeIdentifier(
+                NodeIdentifierWithPredicates.of(Rib.QNAME, RIB_ID_QNAME, ribId.getValue()))
+                .addChild(ImmutableNodes.leafNode(RIB_ID_QNAME, ribId.getValue()))
+                .addChild(ImmutableNodes.mapNodeBuilder(PEER_NID).build())
+                .addChild(Builders.containerBuilder().withNodeIdentifier(LOCRIB_NID)
+                        .addChild(ImmutableNodes.mapNodeBuilder(TABLES_NID).build())
+                        .build()).build();
+
+        final DOMDataTreeWriteTransaction trans = domChain.newWriteOnlyTransaction();
+
+        // merge empty BgpRib + Rib, to make sure the top-level parent structure is present
+        trans.merge(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of(BGPRIB_NID), bgpRib);
+        trans.put(LogicalDatastoreType.OPERATIONAL, yangRibId, ribInstance);
+
+        try {
+            trans.commit().get();
+        } catch (final InterruptedException | ExecutionException e) {
+            LOG.error("Failed to initiate RIB {}", yangRibId, e);
+        }
+
+        LOG.debug("Effective RIB created.");
+
+        localTablesKeys.forEach(this::startLocRib);
+        localTablesKeys.forEach(this::createLocRibWriter);
+    }
+
+    public synchronized FluentFuture<? extends CommitInfo> closeServiceInstance() {
+        if (!isServiceInstantiated) {
+            LOG.trace("RIB {} already closed", ribId.getValue());
+            return CommitInfo.emptyFluentFuture();
+        }
+        LOG.info("Close RIB {}", ribId.getValue());
+        isServiceInstantiated = false;
+        setActive(false);
+
+        txChainToLocRibWriter.values().forEach(LocRibWriter::close);
+        txChainToLocRibWriter.clear();
+
+        final DOMDataTreeWriteTransaction t = domChain.newWriteOnlyTransaction();
+        t.delete(LogicalDatastoreType.OPERATIONAL, getYangRibId());
+        final FluentFuture<? extends CommitInfo> cleanFuture = t.commit();
+        cleanFuture.addCallback(new FutureCallback<CommitInfo>() {
+            @Override
+            public void onSuccess(final CommitInfo result) {
+                LOG.info("RIB cleaned {}", ribId.getValue());
+            }
+
+            @Override
+            public void onFailure(final Throwable throwable) {
+                LOG.error("Failed to clean RIB {}",
+                        ribId.getValue(), throwable);
+            }
+        }, MoreExecutors.directExecutor());
+        domChain.close();
+        return cleanFuture;
     }
 }