BGP Logs improvement
[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.annotations.VisibleForTesting;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.primitives.UnsignedInteger;
14 import java.util.Collection;
15 import java.util.HashMap;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import javax.annotation.Nonnull;
19 import javax.annotation.concurrent.NotThreadSafe;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
22 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
23 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
24 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
25 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
26 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
27 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
28 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.LocRib;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibOut;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.EffectiveRibIn;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Attributes;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Routes;
40 import org.opendaylight.yangtools.concepts.ListenerRegistration;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
46 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
50 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
51 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 @NotThreadSafe
56 final class LocRibWriter implements AutoCloseable, DOMDataTreeChangeListener {
57
58     private static final Logger LOG = LoggerFactory.getLogger(LocRibWriter.class);
59
60     private static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_TRUE = ImmutableNodes.leafNode(QName.create(Attributes.QNAME, "uptodate"), Boolean.TRUE);
61     private static final NodeIdentifier ROUTES_IDENTIFIER = new NodeIdentifier(Routes.QNAME);
62     private static final NodeIdentifier EFFRIBIN_NID = new NodeIdentifier(EffectiveRibIn.QNAME);
63     private static final NodeIdentifier TABLES_NID = new NodeIdentifier(Tables.QNAME);
64
65     private final Map<PathArgument, AbstractRouteEntry> routeEntries = new HashMap<>();
66     private final YangInstanceIdentifier locRibTarget;
67     private final DOMTransactionChain chain;
68     private final ExportPolicyPeerTracker peerPolicyTracker;
69     private final NodeIdentifier attributesIdentifier;
70     private final Long ourAs;
71     private final RIBSupport ribSupport;
72     private final NodeIdentifierWithPredicates tableKey;
73     private final TablesKey localTablesKey;
74     private final RIBSupportContextRegistry registry;
75     private final ListenerRegistration<LocRibWriter> reg;
76
77     LocRibWriter(final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier target, final Long ourAs,
78         final DOMDataTreeChangeService service, final PolicyDatabase pd, final TablesKey tablesKey) {
79         this.chain = Preconditions.checkNotNull(chain);
80         this.tableKey = RibSupportUtils.toYangTablesKey(tablesKey);
81         this.localTablesKey = tablesKey;
82         this.locRibTarget = YangInstanceIdentifier.create(target.node(LocRib.QNAME).node(Tables.QNAME).node(this.tableKey).getPathArguments());
83         this.ourAs = Preconditions.checkNotNull(ourAs);
84         this.registry = registry;
85         this.ribSupport = this.registry.getRIBSupportContext(tablesKey).getRibSupport();
86         this.attributesIdentifier = this.ribSupport.routeAttributesIdentifier();
87         this.peerPolicyTracker = new ExportPolicyPeerTracker(pd);
88
89         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
90         tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Routes.QNAME), this.ribSupport.emptyRoutes());
91         tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
92         tx.submit();
93
94         final YangInstanceIdentifier tableId = target.node(Peer.QNAME).node(Peer.QNAME);
95
96         this.reg = service.registerDataTreeChangeListener(new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, tableId), this);
97     }
98
99     public static LocRibWriter create(@Nonnull final RIBSupportContextRegistry registry, @Nonnull final TablesKey tablesKey, @Nonnull final DOMTransactionChain chain, @Nonnull final YangInstanceIdentifier target,
100         @Nonnull final AsNumber ourAs, @Nonnull final DOMDataTreeChangeService service, @Nonnull final PolicyDatabase pd) {
101         return new LocRibWriter(registry, chain, target, ourAs.getValue(), service, pd, tablesKey);
102     }
103
104     @Override
105     public void close() {
106         this.reg.close();
107         // FIXME: wipe the local rib
108         // FIXME: wait for the chain to close? unfortunately RIBImpl is the listener, so that may require some work
109         this.chain.close();
110     }
111
112     @Nonnull
113     private AbstractRouteEntry createEntry(final PathArgument routeId) {
114         final AbstractRouteEntry ret = this.ribSupport.isComplexRoute() ? new ComplexRouteEntry() : new SimpleRouteEntry();
115         this.routeEntries.put(routeId, ret);
116         LOG.trace("Created new entry for {}", routeId);
117         return ret;
118     }
119
120     @Override
121     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
122         LOG.trace("Received data change {} to LocRib {}", changes, this);
123
124         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
125         try {
126             /*
127              * We use two-stage processing here in hopes that we avoid duplicate
128              * calculations when multiple peers have changed a particular entry.
129              */
130             final Map<RouteUpdateKey, AbstractRouteEntry> toUpdate = update(tx, changes);
131
132             // Now walk all updated entries
133             walkThrough(tx, toUpdate);
134         } catch (final Exception e) {
135             LOG.error("Failed to completely propagate updates {}, state is undefined", changes, e);
136         } finally {
137             tx.submit();
138         }
139     }
140
141     private Map<RouteUpdateKey, AbstractRouteEntry> update(final DOMDataWriteTransaction tx,
142         final Collection<DataTreeCandidate> changes) {
143         final Map<RouteUpdateKey, AbstractRouteEntry> ret = new HashMap<>();
144
145         for (final DataTreeCandidate tc : changes) {
146             final YangInstanceIdentifier rootPath = tc.getRootPath();
147             final DataTreeCandidateNode rootNode = tc.getRootNode();
148             // filter out changes to supported tables
149             final DataTreeCandidateNode tablesChange = rootNode.getModifiedChild(AbstractPeerRoleTracker.PEER_TABLES);
150             if (tablesChange != null) {
151                 this.peerPolicyTracker.onTablesChanged(tablesChange, IdentifierUtils.peerPath(rootPath));
152             }
153             // filter out peer role
154             final DataTreeCandidateNode roleChange =  rootNode.getModifiedChild(AbstractPeerRoleTracker.PEER_ROLE_NID);
155             if (roleChange != null) {
156                 this.peerPolicyTracker.onDataTreeChanged(roleChange, IdentifierUtils.peerPath(rootPath));
157             }
158             // filter out any change outside EffRibsIn
159             final DataTreeCandidateNode ribIn = rootNode.getModifiedChild(EFFRIBIN_NID);
160             if (ribIn == null) {
161                 LOG.debug("Skipping change {}", rootNode.getIdentifier());
162                 continue;
163             }
164             final DataTreeCandidateNode table = ribIn.getModifiedChild(TABLES_NID).getModifiedChild(this.tableKey);
165             if (table == null) {
166                 LOG.debug("Skipping change {}", rootNode.getIdentifier());
167                 continue;
168             }
169             final NodeIdentifierWithPredicates peerKey = IdentifierUtils.peerKey(rootPath);
170             final PeerId peerId = IdentifierUtils.peerId(peerKey);
171             updateNodes(table, peerId, tx, ret);
172         }
173
174         return ret;
175     }
176
177     private void updateNodes(final DataTreeCandidateNode table, final PeerId peerId, final DOMDataWriteTransaction tx, final Map<RouteUpdateKey, AbstractRouteEntry> routes) {
178         for (final DataTreeCandidateNode child : table.getChildNodes()) {
179             LOG.debug("Modification type {}", child.getModificationType());
180             if ((Attributes.QNAME).equals(child.getIdentifier().getNodeType())) {
181                 if (child.getDataAfter().isPresent()) {
182                     // putting uptodate attribute in
183                     LOG.trace("Uptodate found for {}", child.getDataAfter());
184                     tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(child.getIdentifier()), child.getDataAfter().get());
185                 }
186                 continue;
187             }
188             updateRoutesEntries(child, peerId, routes);
189         }
190     }
191
192     private void updateRoutesEntries(final DataTreeCandidateNode child, final PeerId peerId, final Map<RouteUpdateKey, AbstractRouteEntry> routes) {
193         final UnsignedInteger routerId = RouterIds.routerIdForPeerId(peerId);
194         for (final DataTreeCandidateNode route : this.ribSupport.changedRoutes(child)) {
195             final PathArgument routeId = route.getIdentifier();
196             AbstractRouteEntry entry = this.routeEntries.get(routeId);
197
198             final Optional<NormalizedNode<?, ?>> maybeData = route.getDataAfter();
199             if (maybeData.isPresent()) {
200                 if (entry == null) {
201                     entry = createEntry(routeId);
202                 }
203                 entry.addRoute(routerId, this.attributesIdentifier, maybeData.get());
204             } else if (entry != null && entry.removeRoute(routerId)) {
205                 this.routeEntries.remove(routeId);
206                 entry = null;
207                 LOG.trace("Removed route from {}", routerId);
208             }
209             LOG.debug("Updated route {} entry {}", routeId, entry);
210             routes.put(new RouteUpdateKey(peerId, routeId), entry);
211         }
212     }
213
214     private void walkThrough(final DOMDataWriteTransaction tx, final Map<RouteUpdateKey, AbstractRouteEntry> toUpdate) {
215         for (final Entry<RouteUpdateKey, AbstractRouteEntry> e : toUpdate.entrySet()) {
216             LOG.trace("Walking through {}", e);
217             final AbstractRouteEntry entry = e.getValue();
218             final RouteUpdateKey key = e.getKey();
219             final NormalizedNode<?, ?> value;
220
221             if (entry != null) {
222                 if (!entry.selectBest(this.ourAs)) {
223                     // Best path has not changed, no need to do anything else. Proceed to next route.
224                     LOG.trace("Continuing");
225                     continue;
226                 }
227                 value = entry.createValue(key.getRouteId());
228                 LOG.trace("Selected best value {}", value);
229             } else {
230                 value = null;
231             }
232
233             final YangInstanceIdentifier writePath = this.ribSupport.routePath(this.locRibTarget.node(ROUTES_IDENTIFIER), key.getRouteId());
234             if (value != null) {
235                 LOG.debug("Write route to LocRib {}", value);
236                 tx.put(LogicalDatastoreType.OPERATIONAL, writePath, value);
237             } else {
238                 LOG.debug("Delete route from LocRib {}", entry);
239                 tx.delete(LogicalDatastoreType.OPERATIONAL, writePath);
240             }
241             fillAdjRibsOut(tx, entry, value, key);
242         }
243     }
244
245     @VisibleForTesting
246     void fillAdjRibsOut(final DOMDataWriteTransaction tx, final AbstractRouteEntry entry, final NormalizedNode<?, ?> value, final RouteUpdateKey key) {
247         /*
248          * We need to keep track of routers and populate adj-ribs-out, too. If we do not, we need to
249          * expose from which client a particular route was learned from in the local RIB, and have
250          * the listener perform filtering.
251          *
252          * We walk the policy set in order to minimize the amount of work we do for multiple peers:
253          * if we have two eBGP peers, for example, there is no reason why we should perform the translation
254          * multiple times.
255          */
256         for (final PeerRole role : PeerRole.values()) {
257             final PeerExportGroup peerGroup = this.peerPolicyTracker.getPeerGroup(role);
258             if (peerGroup != null) {
259                 final ContainerNode attributes = entry == null ? null : entry.attributes();
260                 final PeerId peerId = key.getPeerId();
261                 final ContainerNode effectiveAttributes = peerGroup.effectiveAttributes(peerId, attributes);
262                 for (final Entry<PeerId, YangInstanceIdentifier> pid : peerGroup.getPeers()) {
263                     if (!this.peerPolicyTracker.isTableSupported(pid.getKey(), this.localTablesKey)) {
264                         LOG.trace("Route rejected, peer {} does not support this table type {}", pid.getKey(), this.localTablesKey);
265                         continue;
266                     }
267                     final YangInstanceIdentifier routeTarget = this.ribSupport.routePath(pid.getValue().node(AdjRibOut.QNAME).node(Tables.QNAME).node(this.tableKey).node(ROUTES_IDENTIFIER), key.getRouteId());
268                     if (effectiveAttributes != null && value != null && !peerId.equals(pid.getKey())) {
269                         LOG.debug("Write route {} to peers AdjRibsOut {}", value, pid.getKey());
270                         tx.put(LogicalDatastoreType.OPERATIONAL, routeTarget, value);
271                         tx.put(LogicalDatastoreType.OPERATIONAL, routeTarget.node(this.attributesIdentifier), effectiveAttributes);
272                     } else {
273                         LOG.trace("Removing {} from transaction for peer {}", routeTarget, pid.getKey());
274                         tx.delete(LogicalDatastoreType.OPERATIONAL, routeTarget);
275                     }
276                 }
277             }
278         }
279     }
280 }