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