Bump versions by x.y.(z+1)
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / RIBImpl.java
old mode 100644 (file)
new mode 100755 (executable)
index c3786f4..aa4f538
  */
 package org.opendaylight.protocol.bgp.rib.impl;
 
-import com.google.common.base.Objects;
-import com.google.common.base.Objects.ToStringHelper;
+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.ImmutableList;
-import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.Futures;
-import java.util.Collections;
+import com.google.common.util.concurrent.ListenableFuture;
+import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.LinkedBlockingQueue;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import javax.annotation.concurrent.GuardedBy;
 import javax.annotation.concurrent.ThreadSafe;
-import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
-import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
 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.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.mdsal.binding.dom.codec.api.BindingCodecTreeFactory;
+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.openconfig.spi.BGPConfigModuleTracker;
+import org.opendaylight.protocol.bgp.openconfig.spi.BGPOpenConfigProvider;
 import org.opendaylight.protocol.bgp.rib.DefaultRibReference;
-import org.opendaylight.protocol.bgp.rib.impl.spi.AdjRIBsOut;
-import org.opendaylight.protocol.bgp.rib.impl.spi.AdjRIBsOutRegistration;
 import org.opendaylight.protocol.bgp.rib.impl.spi.BGPDispatcher;
+import org.opendaylight.protocol.bgp.rib.impl.spi.BgpDeployer;
+import org.opendaylight.protocol.bgp.rib.impl.spi.CodecsRegistry;
+import org.opendaylight.protocol.bgp.rib.impl.spi.ImportPolicyPeerTracker;
 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
-import org.opendaylight.protocol.bgp.rib.spi.AbstractAdjRIBs;
-import org.opendaylight.protocol.bgp.rib.spi.AdjRIBsIn;
-import org.opendaylight.protocol.bgp.rib.spi.BGPObjectComparator;
-import org.opendaylight.protocol.bgp.rib.spi.Peer;
+import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
+import org.opendaylight.protocol.bgp.rib.impl.stats.rib.impl.BGPRenderStats;
+import org.opendaylight.protocol.bgp.rib.impl.stats.rib.impl.RIBImplRuntimeMXBeanImpl;
+import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker;
 import org.opendaylight.protocol.bgp.rib.spi.RIBExtensionConsumerContext;
-import org.opendaylight.protocol.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.message.rev130919.Update;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.UpdateBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.Nlri;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.PathAttributes;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.update.WithdrawnRoutes;
+import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
+import org.opendaylight.protocol.bgp.rib.spi.util.ClusterSingletonServiceRegistrationHelper;
+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.rev130919.BgpTableType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes1;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.PathAttributes2;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.destination.destination.type.DestinationIpv4CaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.destination.destination.type.destination.ipv4._case.DestinationIpv4Builder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpReachNlri;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpReachNlriBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpUnreachNlri;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.MpUnreachNlriBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.update.path.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
 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.BgpRibBuilder;
 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.Route;
 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.RibBuilder;
 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.LocRibBuilder;
+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.Ipv4AddressFamily;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.ClusterIdentifier;
+import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+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 {
+public final class RIBImpl extends DefaultRibReference implements ClusterSingletonService, AutoCloseable, RIB, TransactionChainListener, SchemaContextListener {
     private static final Logger LOG = LoggerFactory.getLogger(RIBImpl.class);
-    private static final Update EOR = new UpdateBuilder().build();
-    private static final TablesKey IPV4_UNICAST_TABLE = new TablesKey(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
-    private final ConcurrentMap<Peer, AdjRIBsOut> ribOuts = new ConcurrentHashMap<>();
-    private final ReconnectStrategyFactory tcpStrategyFactory;
-    private final ReconnectStrategyFactory sessionStrategyFactory;
-    private final BGPObjectComparator comparator;
+    private static final QName RIB_ID_QNAME = QName.create(Rib.QNAME, "id").intern();
+    private static final ContainerNode EMPTY_TABLE_ATTRIBUTES = ImmutableNodes.containerNode(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Attributes.QNAME);
+    private static final int MAX_REGISTRATION_ATTEMPTS = 10;
+    private static final int SLEEP_TIME = MAX_REGISTRATION_ATTEMPTS;
+
     private final BGPDispatcher dispatcher;
-    private final BindingTransactionChain chain;
     private final AsNumber localAs;
-    private final Ipv4Address bgpIdentifier;
-    private final List<BgpTableType> localTables;
-    private final RIBTables tables;
-    private final BlockingQueue<Peer> peers;
-    private final Thread scheduler = new Thread(new Runnable() {
-
-        @Override
-        public void run() {
-            try {
-                final Peer peer = RIBImpl.this.peers.take();
-                LOG.debug("Advertizing loc-rib to new peer {}.", peer);
-                for (final BgpTableType key : RIBImpl.this.localTables) {
-                    final AdjRIBsTransactionImpl trans = new AdjRIBsTransactionImpl(RIBImpl.this.ribOuts, RIBImpl.this.comparator, RIBImpl.this.chain.newWriteOnlyTransaction());
-                    final AbstractAdjRIBs<?, ?, ?> adj = (AbstractAdjRIBs<?, ?, ?>) RIBImpl.this.tables.get(new TablesKey(key.getAfi(), key.getSafi()));
-                    adj.addAllEntries(trans);
-                    Futures.addCallback(trans.commit(), new FutureCallback<Void>() {
-                        @Override
-                        public void onSuccess(final Void result) {
-                            LOG.trace("Advertizing {} to peer {} committed successfully", key.getAfi(), peer);
-                        }
-
-                        @Override
-                        public void onFailure(final Throwable t) {
-                            LOG.error("Failed to update peer {} with RIB {}", peer, t);
-                        }
-                    });
-                }
-            } catch (final InterruptedException e) {
-
-            }
-        }
-    });
-
-    public RIBImpl(final RibId ribId, final AsNumber localAs, final Ipv4Address localBgpId, final RIBExtensionConsumerContext extensions,
-        final BGPDispatcher dispatcher, final ReconnectStrategyFactory tcpStrategyFactory,
-        final ReconnectStrategyFactory sessionStrategyFactory, final DataBroker dps, final List<BgpTableType> localTables) {
-        super(InstanceIdentifier.builder(BgpRib.class).child(Rib.class, new RibKey(Preconditions.checkNotNull(ribId))).toInstance());
-        this.chain = dps.createTransactionChain(this);
+    private final BgpId bgpIdentifier;
+    private final Set<BgpTableType> localTables;
+    private final Set<TablesKey> localTablesKeys;
+    private final DOMDataBroker domDataBroker;
+    private final RIBExtensionConsumerContext extensions;
+    private final YangInstanceIdentifier yangRibId;
+    private final RIBSupportContextRegistryImpl ribContextRegistry;
+    private final CodecsRegistryImpl codecsRegistry;
+    private final ServiceGroupIdentifier serviceGroupIdentifier;
+    private final ClusterSingletonServiceProvider provider;
+    private final BgpDeployer.WriteConfiguration configurationWriter;
+    private ClusterSingletonServiceRegistration registration;
+    private final DOMDataBrokerExtension service;
+    private final Map<TransactionChain, LocRibWriter> txChainToLocRibWriter = new HashMap<>();
+    private final BGPConfigModuleTracker configModuleTracker;
+    private final BGPOpenConfigProvider openConfigProvider;
+    private final Map<TablesKey, PathSelectionMode> bestPathSelectionStrategies;
+    private final ImportPolicyPeerTracker importPolicyPeerTracker;
+    private final RIBImplRuntimeMXBeanImpl renderStats;
+    private final RibId ribId;
+    private final Map<TablesKey, ExportPolicyPeerTracker> exportPolicyPeerTrackerMap;
+
+    private DOMTransactionChain domChain;
+    @GuardedBy("this")
+    private boolean isServiceInstantiated;
+
+    public RIBImpl(final ClusterSingletonServiceProvider provider, final RibId ribId, final AsNumber localAs, final BgpId localBgpId,
+        final ClusterIdentifier clusterId, final RIBExtensionConsumerContext extensions, final BGPDispatcher dispatcher,
+        final BindingCodecTreeFactory codecFactory, final DOMDataBroker domDataBroker, final List<BgpTableType> localTables,
+        @Nonnull final Map<TablesKey, PathSelectionMode> bestPathSelectionStrategies, final GeneratedClassLoadingStrategy classStrategy,
+        final BGPConfigModuleTracker moduleTracker, final BGPOpenConfigProvider openConfigProvider,
+        final BgpDeployer.WriteConfiguration configurationWriter) {
+
+        super(InstanceIdentifier.create(BgpRib.class).child(Rib.class, new RibKey(Preconditions.checkNotNull(ribId))));
         this.localAs = Preconditions.checkNotNull(localAs);
-        this.comparator = new BGPObjectComparator(localAs);
         this.bgpIdentifier = Preconditions.checkNotNull(localBgpId);
         this.dispatcher = Preconditions.checkNotNull(dispatcher);
-        this.sessionStrategyFactory = Preconditions.checkNotNull(sessionStrategyFactory);
-        this.tcpStrategyFactory = Preconditions.checkNotNull(tcpStrategyFactory);
-        this.localTables = ImmutableList.copyOf(localTables);
-        this.tables = new RIBTables(extensions);
-        this.peers = new LinkedBlockingQueue<>();
+        this.localTables = ImmutableSet.copyOf(localTables);
+        this.localTablesKeys = new HashSet<>();
+        this.domDataBroker = Preconditions.checkNotNull(domDataBroker);
+        this.service = this.domDataBroker.getSupportedExtensions().get(DOMDataTreeChangeService.class);
+        this.extensions = Preconditions.checkNotNull(extensions);
+        this.codecsRegistry = CodecsRegistryImpl.create(codecFactory, classStrategy);
+        this.ribContextRegistry = RIBSupportContextRegistryImpl.create(extensions, this.codecsRegistry);
+        final InstanceIdentifierBuilder yangRibIdBuilder = YangInstanceIdentifier.builder().node(BgpRib.QNAME).node(Rib.QNAME);
+        this.yangRibId = yangRibIdBuilder.nodeWithKey(Rib.QNAME, RIB_ID_QNAME, ribId.getValue()).build();
+        this.configModuleTracker = moduleTracker;
+        this.openConfigProvider = openConfigProvider;
+        this.bestPathSelectionStrategies = Preconditions.checkNotNull(bestPathSelectionStrategies);
+        final ClusterIdentifier cId = (clusterId == null) ? new ClusterIdentifier(localBgpId) : clusterId;
+        this.renderStats = new RIBImplRuntimeMXBeanImpl(localBgpId, ribId, localAs, cId);
+        this.ribId = ribId;
+        final PolicyDatabase policyDatabase = new PolicyDatabase(this.localAs.getValue(), localBgpId, cId);
+        this.importPolicyPeerTracker = new ImportPolicyPeerTrackerImpl(policyDatabase);
+        this.serviceGroupIdentifier = ServiceGroupIdentifier.create(this.ribId.getValue() + "-service-group");
+        Preconditions.checkNotNull(provider, "ClusterSingletonServiceProvider is null");
+        this.provider = provider;
+        this.configurationWriter = configurationWriter;
+
+        final ImmutableMap.Builder<TablesKey, ExportPolicyPeerTracker> exportPolicies = new ImmutableMap.Builder<>();
+        for (final BgpTableType t : this.localTables) {
+            final TablesKey key = new TablesKey(t.getAfi(), t.getSafi());
+            this.localTablesKeys.add(key);
+            exportPolicies.put(key, new ExportPolicyPeerTrackerImpl(policyDatabase, key));
+        }
+        this.exportPolicyPeerTrackerMap = exportPolicies.build();
 
-        LOG.debug("Instantiating RIB table {} at {}", ribId, getInstanceIdentifier());
+        LOG.info("RIB Singleton Service {} registered, RIB {}", getIdentifier().getValue(), this.ribId.getValue());
+        //this need to be always the last step
+        this.registration = registerClusterSingletonService(this);
+    }
 
-        final ReadWriteTransaction trans = this.chain.newReadWriteTransaction();
-        Optional<Rib> o;
-        try {
-            o = trans.read(LogicalDatastoreType.OPERATIONAL, getInstanceIdentifier()).get();
-        } catch (InterruptedException | ExecutionException e) {
-            throw new IllegalStateException("Failed to read topology", e);
+    public RIBImpl(final ClusterSingletonServiceProvider provider, final RibId ribId, final AsNumber localAs, final BgpId localBgpId, @Nullable final ClusterIdentifier clusterId,
+        final RIBExtensionConsumerContext extensions, final BGPDispatcher dispatcher, final BindingCodecTreeFactory codecFactory,
+        final DOMDataBroker domDataBroker, final List<BgpTableType> localTables, final Map<TablesKey, PathSelectionMode> bestPathSelectionstrategies,
+        final GeneratedClassLoadingStrategy classStrategy, final BgpDeployer.WriteConfiguration configurationWriter) {
+        this(provider, ribId, localAs, localBgpId, clusterId, extensions, dispatcher, codecFactory,
+            domDataBroker, localTables, bestPathSelectionstrategies, classStrategy, null, null, configurationWriter);
+    }
+
+    private 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()));
         }
-        Preconditions.checkState(!o.isPresent(), "Data provider conflict detected on object {}", getInstanceIdentifier());
 
-        // put empty BgpRib if not exists
-        trans.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.builder(BgpRib.class).build(), new BgpRibBuilder().build());
-        trans.put(LogicalDatastoreType.OPERATIONAL, getInstanceIdentifier(), new RibBuilder().setKey(new RibKey(ribId)).setId(ribId).setLocRib(
-            new LocRibBuilder().setTables(Collections.<Tables> emptyList()).build()).build());
+        final ChoiceNode routes = this.ribContextRegistry.getRIBSupportContext(key).getRibSupport().emptyRoutes();
+        table.withChild(routes);
 
-        for (final BgpTableType t : localTables) {
-            final TablesKey key = new TablesKey(t.getAfi(), t.getSafi());
-            if (this.tables.create(trans, this, key) == null) {
-                LOG.debug("Did not create local table for unhandled table type {}", t);
-            }
+        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);
+        }
+        createLocRibWriter(key);
+    }
+
+    private synchronized void createLocRibWriter(final TablesKey key) {
+        LOG.debug("Creating LocRIB writer for key {}", key);
+        final DOMTransactionChain txChain = createPeerChain(this);
+        PathSelectionMode pathSelectionStrategy = this.bestPathSelectionStrategies.get(key);
+        if (pathSelectionStrategy == null) {
+            pathSelectionStrategy = BasePathSelectionModeFactory.createBestPathSelectionStrategy();
         }
 
-        Futures.addCallback(trans.submit(), new FutureCallback<Void>() {
-            @Override
-            public void onSuccess(final Void result) {
-                LOG.trace("Change committed successfully");
-            }
-
-            @Override
-            public void onFailure(final Throwable t) {
-                LOG.error("Failed to initiate RIB {}", getInstanceIdentifier(), t);
-            }
-        });
+        final LocRibWriter locRibWriter = LocRibWriter.create(this.ribContextRegistry, key, txChain,
+            getYangRibId(), this.localAs, getService(), this.exportPolicyPeerTrackerMap.get(key),
+            pathSelectionStrategy, this.renderStats.getLocRibRouteCounter().init(key));
+        this.txChainToLocRibWriter.put(txChain, locRibWriter);
     }
 
-    synchronized void initTables(final byte[] remoteBgpId) {
+    @Override
+    public String toString() {
+        return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
+    }
+
+    protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
+        return toStringHelper;
     }
 
     @Override
-    public synchronized void updateTables(final Peer peer, final Update message) {
-        final AdjRIBsTransactionImpl trans = new AdjRIBsTransactionImpl(this.ribOuts, this.comparator, this.chain.newWriteOnlyTransaction());
-
-        if (!EOR.equals(message)) {
-            final WithdrawnRoutes wr = message.getWithdrawnRoutes();
-            if (wr != null) {
-                final AdjRIBsIn<?, ?> ari = this.tables.get(IPV4_UNICAST_TABLE);
-                if (ari != null) {
-                    /*
-                     * create MPUnreach for the routes to be handled in the same way as linkstate routes
-                     */
-                    ari.removeRoutes(
-                        trans,
-                        peer,
-                        new MpUnreachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(UnicastSubsequentAddressFamily.class).setWithdrawnRoutes(
-                            new WithdrawnRoutesBuilder().setDestinationType(
-                                new DestinationIpv4CaseBuilder().setDestinationIpv4(
-                                    new DestinationIpv4Builder().setIpv4Prefixes(wr.getWithdrawnRoutes()).build()).build()).build()).build());
-                } else {
-                    LOG.debug("Not removing objects from unhandled IPv4 Unicast");
-                }
-            }
-
-            final PathAttributes attrs = message.getPathAttributes();
-            if (attrs != null) {
-                final PathAttributes2 mpu = attrs.getAugmentation(PathAttributes2.class);
-                if (mpu != null) {
-                    final MpUnreachNlri nlri = mpu.getMpUnreachNlri();
-
-                    final AdjRIBsIn<?, ?> ari = this.tables.get(new TablesKey(nlri.getAfi(), nlri.getSafi()));
-                    if (ari != null) {
-                        ari.removeRoutes(trans, peer, nlri);
-                    } else {
-                        LOG.debug("Not removing objects from unhandled NLRI {}", nlri);
-                    }
-                }
-            }
-
-            final Nlri ar = message.getNlri();
-            if (ar != null) {
-                final AdjRIBsIn<?, ?> ari = this.tables.get(IPV4_UNICAST_TABLE);
-                if (ari != null) {
-                    /*
-                     * create MPReach for the routes to be handled in the same way as linkstate routes
-                     */
-                    final MpReachNlriBuilder b = new MpReachNlriBuilder().setAfi(Ipv4AddressFamily.class).setSafi(
-                        UnicastSubsequentAddressFamily.class).setAdvertizedRoutes(
-                            new AdvertizedRoutesBuilder().setDestinationType(
-                                new DestinationIpv4CaseBuilder().setDestinationIpv4(
-                                    new DestinationIpv4Builder().setIpv4Prefixes(ar.getNlri()).build()).build()).build());
-                    if (attrs != null) {
-                        b.setCNextHop(attrs.getCNextHop());
-                    }
-
-                    ari.addRoutes(trans, peer, b.build(), attrs);
-                } else {
-                    LOG.debug("Not adding objects from unhandled IPv4 Unicast");
-                }
-            }
-
-            if (attrs != null) {
-                final PathAttributes1 mpr = attrs.getAugmentation(PathAttributes1.class);
-                if (mpr != null) {
-                    final MpReachNlri nlri = mpr.getMpReachNlri();
-
-                    final AdjRIBsIn<?, ?> ari = this.tables.get(new TablesKey(nlri.getAfi(), nlri.getSafi()));
-                    if (ari != null) {
-                        if (message.equals(ari.endOfRib())) {
-                            ari.markUptodate(trans, peer);
-                        } else {
-                            ari.addRoutes(trans, peer, nlri, attrs);
-                        }
-                    } else {
-                        LOG.debug("Not adding objects from unhandled NLRI {}", nlri);
-                    }
-                }
-            }
-        } else {
-            final AdjRIBsIn<?, ?> ari = this.tables.get(IPV4_UNICAST_TABLE);
-            if (ari != null) {
-                ari.markUptodate(trans, peer);
-            } else {
-                LOG.debug("End-of-RIB for IPv4 Unicast ignored");
-            }
+    public synchronized void close() throws Exception {
+        if (this.registration != null) {
+            this.registration.close();
+            this.registration = null;
         }
+    }
 
-        Futures.addCallback(trans.commit(), new FutureCallback<Void>() {
-            @Override
-            public void onSuccess(final Void result) {
-                LOG.debug("RIB modification successfully committed.");
-            }
-
-            @Override
-            public void onFailure(final Throwable t) {
-                LOG.error("Failed to commit RIB modification", t);
-            }
-        });
+    @Override
+    public AsNumber getLocalAs() {
+        return this.localAs;
     }
 
     @Override
-    public synchronized void clearTable(final Peer peer, final TablesKey key) {
-        final AdjRIBsIn<?, ?> ari = this.tables.get(key);
-        if (ari != null) {
-            final AdjRIBsTransactionImpl trans = new AdjRIBsTransactionImpl(this.ribOuts, this.comparator, this.chain.newWriteOnlyTransaction());
-            ari.clear(trans, peer);
-
-            Futures.addCallback(trans.commit(), new FutureCallback<Void>() {
-                @Override
-                public void onSuccess(final Void result) {
-                    LOG.trace("Table {} cleared successfully", key);
-                }
-
-                @Override
-                public void onFailure(final Throwable t) {
-                    LOG.error("Failed to clear table {}", key, t);
-                }
-            });
+    public BgpId getBgpIdentifier() {
+        return this.bgpIdentifier;
+    }
+
+    @Nonnull
+    @Override
+    public Set<? extends BgpTableType> getLocalTables() {
+        return this.localTables;
+    }
+
+    @Override
+    public BGPDispatcher getDispatcher() {
+        return this.dispatcher;
+    }
+
+    @Override
+    public synchronized void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
+        LOG.error("Broken chain in RIB {} transaction {}", getInstanceIdentifier(), transaction != null ? transaction.getIdentifier() : null, cause);
+        if (this.txChainToLocRibWriter.containsKey(chain)) {
+            final LocRibWriter locRibWriter = this.txChainToLocRibWriter.remove(chain);
+            final DOMTransactionChain newChain = createPeerChain(this);
+            locRibWriter.restart(newChain);
+            this.txChainToLocRibWriter.put(newChain, locRibWriter);
         }
     }
 
     @Override
-    public String toString() {
-        return addToStringAttributes(Objects.toStringHelper(this)).toString();
+    public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
+        LOG.info("RIB {} closed successfully", getInstanceIdentifier());
     }
 
-    protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
-        return toStringHelper;
+    @Override
+    public Set<TablesKey> getLocalTablesKeys() {
+        return this.localTablesKeys;
     }
 
-    @SuppressWarnings("unchecked")
-    protected <K, V extends Route> AdjRIBsIn<K, V> getTable(final TablesKey key) {
-        return (AdjRIBsIn<K, V>) this.tables.get(key);
+    @Override
+    public DOMDataTreeChangeService getService() {
+        return (DOMDataTreeChangeService) this.service;
     }
 
     @Override
-    public void close() throws InterruptedException, ExecutionException {
-        final WriteTransaction t = this.chain.newWriteOnlyTransaction();
-        t.delete(LogicalDatastoreType.OPERATIONAL, getInstanceIdentifier());
-        t.submit().get();
-        this.chain.close();
+    public BGPRenderStats getRenderStats() {
+        return this.renderStats;
     }
 
     @Override
-    public AsNumber getLocalAs() {
-        return this.localAs;
+    public YangInstanceIdentifier getYangRibId() {
+        return this.yangRibId;
     }
 
     @Override
-    public Ipv4Address getBgpIdentifier() {
-        return this.bgpIdentifier;
+    public DOMTransactionChain createPeerChain(final TransactionChainListener listener) {
+        return this.domDataBroker.createTransactionChain(listener);
     }
 
     @Override
-    public List<? extends BgpTableType> getLocalTables() {
-        return this.localTables;
+    public RIBExtensionConsumerContext getRibExtensions() {
+        return this.extensions;
     }
 
     @Override
-    public ReconnectStrategyFactory getTcpStrategyFactory() {
-        return this.tcpStrategyFactory;
+    public RIBSupportContextRegistry getRibSupportContext() {
+        return this.ribContextRegistry;
     }
 
     @Override
-    public ReconnectStrategyFactory getSessionStrategyFactory() {
-        return this.sessionStrategyFactory;
+    public void onGlobalContextUpdated(final SchemaContext context) {
+        this.codecsRegistry.onSchemaContextUpdated(context);
     }
 
     @Override
-    public BGPDispatcher getDispatcher() {
-        return this.dispatcher;
+    public CodecsRegistry getCodecsRegistry() {
+        return this.codecsRegistry;
     }
 
     @Override
-    public void initTable(final Peer bgpPeer, final TablesKey key) {
-        // FIXME: BUG-196: support graceful restart
+    public Optional<BGPOpenConfigProvider> getOpenConfigProvider() {
+        return Optional.fromNullable(this.openConfigProvider);
     }
 
     @Override
-    public AdjRIBsOutRegistration registerRIBsOut(final Peer peer, final AdjRIBsOut aro) {
-        final AdjRIBsOutRegistration reg = new AdjRIBsOutRegistration(aro) {
-            @Override
-            protected void removeRegistration() {
-                RIBImpl.this.ribOuts.remove(peer, aro);
-            }
-        };
-
-        this.ribOuts.put(peer, aro);
-        LOG.debug("Registering this peer {} to RIB-Out {}", peer, this.ribOuts);
+    public ImportPolicyPeerTracker getImportPolicyPeerTracker() {
+        return this.importPolicyPeerTracker;
+    }
+
+    @Override
+    public ExportPolicyPeerTracker getExportPolicyPeerTracker(final TablesKey tablesKey) {
+        return this.exportPolicyPeerTrackerMap.get(tablesKey);
+    }
+
+    @Override
+    public synchronized void instantiateServiceInstance() {
+        this.isServiceInstantiated = true;
+        this.domChain = this.domDataBroker.createTransactionChain(this);
+        if(this.configurationWriter != null) {
+            this.configurationWriter.apply();
+        }
+        LOG.info("RIB Singleton Service {} instantiated, RIB {}", getIdentifier().getValue(), this.ribId.getValue());
+        LOG.debug("Instantiating RIB table {} at {}", this.ribId , this.yangRibId);
+
+        final ContainerNode bgpRib = Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(BgpRib.QNAME))
+            .addChild(ImmutableNodes.mapNodeBuilder(Rib.QNAME).build()).build();
+
+        final MapEntryNode ribInstance = Builders.mapEntryBuilder().withNodeIdentifier(
+            new NodeIdentifierWithPredicates(Rib.QNAME, RIB_ID_QNAME, this.ribId .getValue()))
+            .addChild(ImmutableNodes.leafNode(RIB_ID_QNAME, this.ribId .getValue()))
+            .addChild(ImmutableNodes.mapNodeBuilder(Peer.QNAME).build())
+            .addChild(Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(LocRib.QNAME))
+                .addChild(ImmutableNodes.mapNodeBuilder(Tables.QNAME).build())
+                .build()).build();
+
+
+        final DOMDataWriteTransaction trans = this.domChain.newWriteOnlyTransaction();
+
+        // merge empty BgpRib + Rib, to make sure the top-level parent structure is present
+        trans.merge(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.builder().node(BgpRib.QNAME).build(), bgpRib);
+        trans.put(LogicalDatastoreType.OPERATIONAL, this.yangRibId, ribInstance);
+
         try {
-            this.peers.put(peer);
-            this.scheduler.run();
-        } catch (final InterruptedException e) {
-            //
+            trans.submit().checkedGet();
+        } catch (final TransactionCommitFailedException e) {
+            LOG.error("Failed to initiate RIB {}", this.yangRibId, e);
+        }
+
+        LOG.debug("Effective RIB created.");
+
+        this.localTablesKeys.forEach(this::startLocRib);
+        if (this.configModuleTracker != null) {
+            this.configModuleTracker.onInstanceCreate();
         }
-        return reg;
     }
 
     @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 synchronized ListenableFuture<Void> closeServiceInstance() {
+        if(!this.isServiceInstantiated) {
+            LOG.trace("RIB Singleton Service {} already closed, RIB {}", getIdentifier().getValue(),
+                this.ribId.getValue());
+            return Futures.immediateFuture(null);
+        }
+        LOG.info("Close RIB Singleton Service {}, RIB {}", getIdentifier().getValue(), this.ribId.getValue());
+        this.isServiceInstantiated = false;
+
+        this.txChainToLocRibWriter.values().forEach(LocRibWriter::close);
+        this.txChainToLocRibWriter.clear();
+
+        this.renderStats.getLocRibRouteCounter().resetAll();
+
+        if (this.configModuleTracker != null) {
+            this.configModuleTracker.onInstanceClose();
+        }
+
+        final DOMDataWriteTransaction t = this.domChain.newWriteOnlyTransaction();
+        t.delete(LogicalDatastoreType.OPERATIONAL, getYangRibId());
+        final CheckedFuture<Void, TransactionCommitFailedException> cleanFuture = t.submit();
+
+        this.domChain.close();
+
+        return cleanFuture;
     }
 
     @Override
-    public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
-        LOG.info("RIB {} closed successfully", getInstanceIdentifier());
+    public ServiceGroupIdentifier getIdentifier() {
+        return this.serviceGroupIdentifier;
+    }
+
+    @Override
+    public ClusterSingletonServiceRegistration registerClusterSingletonService(final ClusterSingletonService clusterSingletonService) {
+        return ClusterSingletonServiceRegistrationHelper.registerSingletonService(this.provider, clusterSingletonService, MAX_REGISTRATION_ATTEMPTS,
+                SLEEP_TIME);
+    }
+
+    @Override
+    public ServiceGroupIdentifier getRibIServiceGroupIdentifier() {
+        return getIdentifier();
     }
 }