Bug-4827: BGP Add-Path OpenConfig Support
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / LocRibWriter.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.bgp.rib.impl;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.primitives.UnsignedInteger;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.Map;
16 import javax.annotation.Nonnull;
17 import javax.annotation.concurrent.NotThreadSafe;
18 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
19 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
20 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
21 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
22 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
23 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
24 import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode;
25 import org.opendaylight.protocol.bgp.mode.api.RouteEntry;
26 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
27 import org.opendaylight.protocol.bgp.rib.spi.CacheDisconnectedPeers;
28 import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker;
29 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
30 import org.opendaylight.protocol.bgp.rib.spi.PeerExportGroup;
31 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
32 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
33 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.LocRib;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.EffectiveRibIn;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Attributes;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Routes;
44 import org.opendaylight.yangtools.concepts.ListenerRegistration;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
50 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
53 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
55 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 @NotThreadSafe
60 final class LocRibWriter implements AutoCloseable, DOMDataTreeChangeListener {
61
62     private static final Logger LOG = LoggerFactory.getLogger(LocRibWriter.class);
63
64     private static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_TRUE = ImmutableNodes.leafNode(QName.create(Attributes.QNAME, "uptodate"), Boolean.TRUE);
65     private static final NodeIdentifier EFFRIBIN_NID = new NodeIdentifier(EffectiveRibIn.QNAME);
66     private static final NodeIdentifier TABLES_NID = new NodeIdentifier(Tables.QNAME);
67
68     private final Map<PathArgument, RouteEntry> routeEntries = new HashMap<>();
69     private final YangInstanceIdentifier locRibTarget;
70     private final DOMTransactionChain chain;
71     private final ExportPolicyPeerTracker peerPolicyTracker;
72     private final NodeIdentifier attributesIdentifier;
73     private final Long ourAs;
74     private final RIBSupport ribSupport;
75     private final NodeIdentifierWithPredicates tableKey;
76     private final TablesKey localTablesKey;
77     private final ListenerRegistration<LocRibWriter> reg;
78     private final CacheDisconnectedPeers cacheDisconnectedPeers;
79     private final PathSelectionMode pathSelectionMode;
80
81     private LocRibWriter(final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier target, final Long ourAs,
82         final DOMDataTreeChangeService service, final PolicyDatabase pd, final TablesKey tablesKey, final CacheDisconnectedPeers cacheDisconnectedPeers,
83         @Nonnull final PathSelectionMode pathSelectionMode) {
84         this.chain = Preconditions.checkNotNull(chain);
85         this.tableKey = RibSupportUtils.toYangTablesKey(tablesKey);
86         this.localTablesKey = tablesKey;
87         this.locRibTarget = YangInstanceIdentifier.create(target.node(LocRib.QNAME).node(Tables.QNAME).node(this.tableKey).getPathArguments());
88         this.ourAs = Preconditions.checkNotNull(ourAs);
89         this.ribSupport = registry.getRIBSupportContext(tablesKey).getRibSupport();
90         this.attributesIdentifier = this.ribSupport.routeAttributesIdentifier();
91         this.peerPolicyTracker = new ExportPolicyPeerTrackerImpl(pd, this.localTablesKey);
92         this.cacheDisconnectedPeers = cacheDisconnectedPeers;
93         this.pathSelectionMode = pathSelectionMode;
94
95         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
96         tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Routes.QNAME), this.ribSupport.emptyRoutes());
97         tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
98         tx.submit();
99
100         final YangInstanceIdentifier tableId = target.node(Peer.QNAME).node(Peer.QNAME);
101
102         this.reg = service.registerDataTreeChangeListener(new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, tableId), this);
103     }
104
105     public static LocRibWriter create(@Nonnull final RIBSupportContextRegistry registry, @Nonnull final TablesKey tablesKey, @Nonnull final DOMTransactionChain chain,
106         @Nonnull final YangInstanceIdentifier target, @Nonnull final AsNumber ourAs, @Nonnull final DOMDataTreeChangeService service, @Nonnull final PolicyDatabase pd,
107         final CacheDisconnectedPeers cacheDisconnectedPeers, @Nonnull final PathSelectionMode pathSelectionStrategy) {
108         return new LocRibWriter(registry, chain, target, ourAs.getValue(), service, pd, tablesKey, cacheDisconnectedPeers, pathSelectionStrategy);
109     }
110
111     @Override
112     public void close() {
113         this.reg.close();
114         // FIXME: wait for the chain to close? unfortunately RIBImpl is the listener, so that may require some work
115         this.chain.close();
116     }
117
118     @Nonnull
119     private RouteEntry createEntry(final PathArgument routeId) {
120         final RouteEntry ret = this.pathSelectionMode.createRouteEntry(ribSupport.isComplexRoute());
121         this.routeEntries.put(routeId, ret);
122         LOG.trace("Created new entry for {}", routeId);
123         return ret;
124     }
125
126     @Override
127     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
128         LOG.trace("Received data change {} to LocRib {}", changes, this);
129
130         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
131         try {
132             /*
133              * We use two-stage processing here in hopes that we avoid duplicate
134              * calculations when multiple peers have changed a particular entry.
135              */
136             final Map<RouteUpdateKey, RouteEntry> toUpdate = update(tx, changes);
137
138             // Now walk all updated entries
139             walkThrough(tx, toUpdate);
140         } catch (final Exception e) {
141             LOG.error("Failed to completely propagate updates {}, state is undefined", changes, e);
142         } finally {
143             tx.submit();
144         }
145     }
146
147     private Map<RouteUpdateKey, RouteEntry> update(final DOMDataWriteTransaction tx, final Collection<DataTreeCandidate> changes) {
148         final Map<RouteUpdateKey, RouteEntry> ret = new HashMap<>();
149
150         for (final DataTreeCandidate tc : changes) {
151             final YangInstanceIdentifier rootPath = tc.getRootPath();
152             final DataTreeCandidateNode rootNode = tc.getRootNode();
153             final NodeIdentifierWithPredicates peerKey = IdentifierUtils.peerKey(rootPath);
154             final PeerId peerId = IdentifierUtils.peerId(peerKey);
155             filterOutPeerRole(peerId, rootNode, rootPath);
156             filterOutChangesToSupportedTables(peerId, rootNode);
157             filterOutAnyChangeOutsideEffRibsIn(peerId, rootNode, ret, rootPath, tx);
158         }
159
160         return ret;
161     }
162
163     private void filterOutAnyChangeOutsideEffRibsIn(final PeerId peerId, final DataTreeCandidateNode rootNode,
164         final Map<RouteUpdateKey, RouteEntry> ret, final YangInstanceIdentifier rootPath, final DOMDataWriteTransaction tx) {
165         final DataTreeCandidateNode ribIn = rootNode.getModifiedChild(EFFRIBIN_NID);
166         if (ribIn == null) {
167             LOG.trace("Skipping change {}", rootNode.getIdentifier());
168             return;
169         }
170         final DataTreeCandidateNode table = ribIn.getModifiedChild(TABLES_NID).getModifiedChild(this.tableKey);
171         if (table == null) {
172             LOG.trace("Skipping change {}", rootNode.getIdentifier());
173             return;
174         }
175         initializeTableWithExistentRoutes(table, peerId, rootPath, tx);
176         updateNodes(table, peerId, tx, ret);
177     }
178
179     private void filterOutChangesToSupportedTables(final PeerId peerIdOfNewPeer, final DataTreeCandidateNode rootNode) {
180         final DataTreeCandidateNode tablesChange = rootNode.getModifiedChild(AbstractPeerRoleTracker.PEER_TABLES);
181         if (tablesChange != null) {
182             this.peerPolicyTracker.onTablesChanged(peerIdOfNewPeer, tablesChange);
183         }
184     }
185
186     private void initializeTableWithExistentRoutes(final DataTreeCandidateNode table, final PeerId peerIdOfNewPeer, final YangInstanceIdentifier rootPath,
187         final DOMDataWriteTransaction tx) {
188         if (!table.getDataBefore().isPresent() && this.peerPolicyTracker.isTableSupported(peerIdOfNewPeer)) {
189             LOG.debug("Peer {} table has been created, inserting existent routes", peerIdOfNewPeer);
190             final PeerRole newPeerRole = this.peerPolicyTracker.getRole(IdentifierUtils.peerPath(rootPath));
191             final PeerExportGroup peerGroup = this.peerPolicyTracker.getPeerGroup(newPeerRole);
192             this.routeEntries.entrySet().forEach(entry -> entry.getValue().writeRoute(peerIdOfNewPeer, entry.getKey(), rootPath, peerGroup,
193                 this.localTablesKey, this.peerPolicyTracker, this.ribSupport, this.cacheDisconnectedPeers, tx));
194         }
195     }
196
197     private void filterOutPeerRole(final PeerId peerId, final DataTreeCandidateNode rootNode, final YangInstanceIdentifier rootPath) {
198         final DataTreeCandidateNode roleChange = rootNode.getModifiedChild(AbstractPeerRoleTracker.PEER_ROLE_NID);
199         if (roleChange != null) {
200             if (!rootNode.getModificationType().equals(ModificationType.DELETE)) {
201                 this.cacheDisconnectedPeers.reconnected(peerId);
202             }
203             this.peerPolicyTracker.onDataTreeChanged(roleChange, IdentifierUtils.peerPath(rootPath));
204         }
205     }
206
207     private void updateNodes(final DataTreeCandidateNode table, final PeerId peerId, final DOMDataWriteTransaction tx,
208         final Map<RouteUpdateKey, RouteEntry> routes) {
209         for (final DataTreeCandidateNode child : table.getChildNodes()) {
210             LOG.debug("Modification type {}", child.getModificationType());
211             if ((Attributes.QNAME).equals(child.getIdentifier().getNodeType())) {
212                 if (child.getDataAfter().isPresent()) {
213                     // putting uptodate attribute in
214                     LOG.trace("Uptodate found for {}", child.getDataAfter());
215                     tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(child.getIdentifier()), child.getDataAfter().get());
216                 }
217                 continue;
218             }
219             updateRoutesEntries(child, peerId, routes);
220         }
221     }
222
223     private void updateRoutesEntries(final DataTreeCandidateNode child, final PeerId peerId, final Map<RouteUpdateKey, RouteEntry> routes) {
224         final UnsignedInteger routerId = RouterIds.routerIdForPeerId(peerId);
225         final Collection<DataTreeCandidateNode> modifiedRoutes = this.ribSupport.changedRoutes(child);
226         for (final DataTreeCandidateNode route : modifiedRoutes) {
227             final PathArgument routeId = route.getIdentifier();
228             RouteEntry entry = this.routeEntries.get(routeId);
229             final Optional<NormalizedNode<?, ?>> maybeData = route.getDataAfter();
230             final Optional<NormalizedNode<?, ?>> maybeDataBefore = route.getDataBefore();
231             if (maybeData.isPresent()) {
232                 if (entry == null) {
233                     entry = createEntry(routeId);
234                 }
235                 entry.addRoute(routerId, this.ribSupport.extractPathId(maybeData.get()), this.attributesIdentifier, maybeData.get());
236             } else if (entry != null && entry.removeRoute(routerId, this.ribSupport.extractPathId(maybeDataBefore.get()))) {
237                 this.routeEntries.remove(routeId);
238                 LOG.trace("Removed route from {}", routerId);
239             }
240             final RouteUpdateKey routeUpdateKey = new RouteUpdateKey(peerId, routeId);
241             LOG.debug("Updated route {} entry {}", routeId, entry);
242             routes.put(routeUpdateKey, entry);
243         }
244     }
245
246     private void walkThrough(final DOMDataWriteTransaction tx, final Map<RouteUpdateKey, RouteEntry> toUpdate) {
247         for (final Map.Entry<RouteUpdateKey, RouteEntry> e : toUpdate.entrySet()) {
248             LOG.trace("Walking through {}", e);
249             final RouteEntry entry = e.getValue();
250
251             if (!entry.selectBest(this.ourAs)) {
252                 LOG.trace("Best path has not changed, continuing");
253                 continue;
254             }
255             entry.updateRoute(this.localTablesKey, this.peerPolicyTracker, this.locRibTarget, this.ribSupport, this.cacheDisconnectedPeers,
256                 tx, e.getKey().getRouteId());
257         }
258     }
259 }