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