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