Sonar issue fix
[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.Arrays;
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.RIBSupportContext;
27 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
28 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
29 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.LocRib;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibOut;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.EffectiveRibIn;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Attributes;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Routes;
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
62     private final Map<PathArgument, AbstractRouteEntry> routeEntries = new HashMap<>();
63     private final YangInstanceIdentifier locRibTarget;
64     private final DOMTransactionChain chain;
65     private final ExportPolicyPeerTracker peerPolicyTracker;
66     private final NodeIdentifier attributesIdentifier;
67     private final Long ourAs;
68     private final RIBSupport ribSupport;
69     private final NodeIdentifierWithPredicates tableKey;
70     private final RIBSupportContextRegistry registry;
71
72     LocRibWriter(final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier target, final Long ourAs,
73         final DOMDataTreeChangeService service, final PolicyDatabase pd, final TablesKey tablesKey) {
74         this.chain = Preconditions.checkNotNull(chain);
75         this.tableKey = RibSupportUtils.toYangTablesKey(tablesKey);
76         this.locRibTarget = YangInstanceIdentifier.create(target.node(LocRib.QNAME).node(Tables.QNAME).node(this.tableKey).getPathArguments());
77         this.ourAs = Preconditions.checkNotNull(ourAs);
78         this.registry = registry;
79         this.ribSupport = this.registry.getRIBSupportContext(tablesKey).getRibSupport();
80         this.attributesIdentifier = this.ribSupport.routeAttributesIdentifier();
81         this.peerPolicyTracker = new ExportPolicyPeerTracker(pd);
82
83         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
84         tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Routes.QNAME), this.ribSupport.emptyRoutes());
85         tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
86         tx.submit();
87
88         final YangInstanceIdentifier tableId = target.node(Peer.QNAME).node(Peer.QNAME).node(EffectiveRibIn.QNAME).node(Tables.QNAME).node(this.tableKey);
89         service.registerDataTreeChangeListener(new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, tableId), this);
90     }
91
92     public static LocRibWriter create(@Nonnull final RIBSupportContextRegistry registry, @Nonnull final TablesKey tablesKey, @Nonnull final DOMTransactionChain chain, @Nonnull final YangInstanceIdentifier target,
93         @Nonnull final AsNumber ourAs, @Nonnull final DOMDataTreeChangeService service, @Nonnull final PolicyDatabase pd) {
94         return new LocRibWriter(registry, chain, target, ourAs.getValue(), service, pd, tablesKey);
95     }
96
97     @Override
98     public void close() {
99         this.chain.close();
100     }
101
102     @Nonnull private AbstractRouteEntry createEntry(final PathArgument routeId) {
103         final AbstractRouteEntry ret = this.ribSupport.isComplexRoute() ? new ComplexRouteEntry() : new SimpleRouteEntry();
104
105         this.routeEntries.put(routeId, ret);
106         LOG.trace("Created new entry for {}", routeId);
107         return ret;
108     }
109
110     @Override
111     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
112         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
113         LOG.trace("Received data change to LocRib {}", Arrays.toString(changes.toArray()));
114         /*
115          * We use two-stage processing here in hopes that we avoid duplicate
116          * calculations when multiple peers have changed a particular entry.
117          */
118         final Map<RouteUpdateKey, AbstractRouteEntry> toUpdate = new HashMap<>();
119         update(tx, changes, toUpdate);
120
121         // Now walk all updated entries
122         walkThrough(tx, toUpdate);
123
124         tx.submit();
125     }
126
127     private void walkThrough(final DOMDataWriteTransaction tx, final Map<RouteUpdateKey, AbstractRouteEntry> toUpdate) {
128         for (final Entry<RouteUpdateKey, AbstractRouteEntry> e : toUpdate.entrySet()) {
129             LOG.trace("Walking through {}", e);
130             final AbstractRouteEntry entry = e.getValue();
131             final RouteUpdateKey key = e.getKey();
132             final NormalizedNode<?, ?> value;
133
134             if (entry != null) {
135                 if (!entry.selectBest(this.ourAs)) {
136                     // Best path has not changed, no need to do anything else. Proceed to next route.
137                     LOG.trace("Continuing");
138                     continue;
139                 }
140                 value = entry.createValue(key.getRouteId());
141                 LOG.trace("Selected best value {}", value);
142             } else {
143                 value = null;
144             }
145
146             final YangInstanceIdentifier writePath = this.ribSupport.routePath(this.locRibTarget.node(Routes.QNAME), key.getRouteId());
147             if (value != null) {
148                 LOG.debug("Write route to LocRib {}", value);
149                 tx.put(LogicalDatastoreType.OPERATIONAL, writePath, value);
150             } else {
151                 LOG.debug("Delete route from LocRib {}", entry);
152                 tx.delete(LogicalDatastoreType.OPERATIONAL, writePath);
153             }
154             fillAdjRibsOut(tx, entry, value, key);
155         }
156     }
157
158     private void update(final DOMDataWriteTransaction tx, final Collection<DataTreeCandidate> changes,
159         final Map<RouteUpdateKey, AbstractRouteEntry> toUpdate) {
160
161         for (final DataTreeCandidate tc : changes) {
162             final YangInstanceIdentifier path = tc.getRootPath();
163             final NodeIdentifierWithPredicates peerKey = IdentifierUtils.peerKey(path);
164             final PeerId peerId = IdentifierUtils.peerId(peerKey);
165             final UnsignedInteger routerId = RouterIds.routerIdForPeerId(peerId);
166             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
167                 if ((Attributes.QNAME).equals(child.getIdentifier().getNodeType())) {
168                     // putting uptodate attribute in
169                     LOG.trace("Uptodate found for {}", child.getDataAfter());
170                     tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(child.getIdentifier()), child.getDataAfter().get());
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                     toUpdate.put(new RouteUpdateKey(peerId, routeId), entry);
191                 }
192             }
193         }
194     }
195
196     private void fillAdjRibsOut(final DOMDataWriteTransaction tx, final AbstractRouteEntry entry, final NormalizedNode<?, ?> value, final RouteUpdateKey key) {
197         /*
198          * We need to keep track of routers and populate adj-ribs-out, too. If we do not, we need to
199          * expose from which client a particular route was learned from in the local RIB, and have
200          * the listener perform filtering.
201          *
202          * We walk the policy set in order to minimize the amount of work we do for multiple peers:
203          * if we have two eBGP peers, for example, there is no reason why we should perform the translation
204          * multiple times.
205          */
206         for (final PeerRole role : PeerRole.values()) {
207             final PeerExportGroup peerGroup = this.peerPolicyTracker.getPeerGroup(role);
208             if (peerGroup != null) {
209                 final ContainerNode attributes = entry == null ? null : entry.attributes();
210                 final PeerId peerId = key.getPeerId();
211                 final ContainerNode effectiveAttributes = peerGroup.effectiveAttributes(peerId, attributes);
212                 for (final Entry<PeerId, YangInstanceIdentifier> pid : peerGroup.getPeers()) {
213                     // This points to adj-rib-out for a particular peer/table combination
214                     final RIBSupportContext ribCtx = this.registry.getRIBSupportContext(this.tableKey);
215                     // FIXME: the table should be created for a peer only once
216                     ribCtx.clearTable(tx, pid.getValue().node(AdjRibOut.QNAME).node(Tables.QNAME).node(this.tableKey));
217                     final YangInstanceIdentifier routeTarget = this.ribSupport.routePath(pid.getValue().node(AdjRibOut.QNAME).node(Tables.QNAME).node(this.tableKey).node(Routes.QNAME), key.getRouteId());
218                     if (effectiveAttributes != null && value != null && !peerId.equals(pid.getKey())) {
219                         LOG.debug("Write route to AdjRibsOut {}", value);
220                         tx.put(LogicalDatastoreType.OPERATIONAL, routeTarget, value);
221                         tx.put(LogicalDatastoreType.OPERATIONAL, routeTarget.node(this.attributesIdentifier), effectiveAttributes);
222                     } else {
223                         LOG.trace("Removing {} from transaction", routeTarget);
224                         tx.delete(LogicalDatastoreType.OPERATIONAL, routeTarget);
225                     }
226                 }
227             }
228         }
229     }
230 }