0b57184df312b27f86141d8fc8d90861ecf6c550
[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.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.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
48 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 @NotThreadSafe
53 final class LocRibWriter implements AutoCloseable, DOMDataTreeChangeListener {
54
55     private static final Logger LOG = LoggerFactory.getLogger(LocRibWriter.class);
56
57     private final Map<PathArgument, AbstractRouteEntry> routeEntries = new HashMap<>();
58     private final YangInstanceIdentifier locRibTarget;
59     private final DOMTransactionChain chain;
60     private final ExportPolicyPeerTracker peerPolicyTracker;
61     private final NodeIdentifier attributesIdentifier;
62     private final Long ourAs;
63     private final RIBSupport ribSupport;
64     private final NodeIdentifierWithPredicates tableKey;
65     private final RIBSupportContextRegistry registry;
66
67     LocRibWriter(final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier target, final Long ourAs,
68         final DOMDataTreeChangeService service, final PolicyDatabase pd, final TablesKey tablesKey) {
69         this.chain = Preconditions.checkNotNull(chain);
70         this.tableKey = RibSupportUtils.toYangTablesKey(tablesKey);
71         this.locRibTarget = YangInstanceIdentifier.create(target.node(LocRib.QNAME).node(Tables.QNAME).node(this.tableKey).getPathArguments());
72         this.ourAs = Preconditions.checkNotNull(ourAs);
73         this.registry = registry;
74         this.ribSupport = this.registry.getRIBSupportContext(tablesKey).getRibSupport();
75         this.attributesIdentifier = this.ribSupport.routeAttributesIdentifier();
76         this.peerPolicyTracker = new ExportPolicyPeerTracker(service, target, pd);
77
78         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
79         tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Routes.QNAME), this.ribSupport.emptyRoutes());
80         tx.submit();
81
82         final YangInstanceIdentifier tableId = target.node(Peer.QNAME).node(Peer.QNAME).node(EffectiveRibIn.QNAME).node(Tables.QNAME).node(this.tableKey);
83         service.registerDataTreeChangeListener(new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, tableId), this);
84     }
85
86     public static LocRibWriter create(@Nonnull final RIBSupportContextRegistry registry, @Nonnull final TablesKey tablesKey, @Nonnull final DOMTransactionChain chain, @Nonnull final YangInstanceIdentifier target,
87         @Nonnull final AsNumber ourAs, @Nonnull final DOMDataTreeChangeService service, @Nonnull final PolicyDatabase pd) {
88         return new LocRibWriter(registry, chain, target, ourAs.getValue(), service, pd, tablesKey);
89     }
90
91     @Override
92     public void close() {
93         this.peerPolicyTracker.close();
94     }
95
96     private AbstractRouteEntry createEntry(final PathArgument routeId) {
97         final AbstractRouteEntry ret = this.ribSupport.isComplexRoute() ? new ComplexRouteEntry() : new SimpleRouteEntry();
98
99         this.routeEntries.put(routeId, ret);
100         LOG.trace("Created new entry for {}", routeId);
101         return ret;
102     }
103
104     @Override
105     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
106         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
107         LOG.trace("Received data change to LocRib {}", Arrays.toString(changes.toArray()));
108         /*
109          * We use two-stage processing here in hopes that we avoid duplicate
110          * calculations when multiple peers have changed a particular entry.
111          */
112         final Map<RouteUpdateKey, AbstractRouteEntry> toUpdate = new HashMap<>();
113         for (final DataTreeCandidate tc : changes) {
114             final YangInstanceIdentifier path = tc.getRootPath();
115             final NodeIdentifierWithPredicates peerKey = IdentifierUtils.peerKey(path);
116             final PeerId peerId = IdentifierUtils.peerId(peerKey);
117             final UnsignedInteger routerId = RouterIds.routerIdForPeerId(peerId);
118             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
119                 if ((Attributes.QNAME).equals(child.getIdentifier().getNodeType())) {
120                     // putting uptodate attribute in
121                     LOG.trace("Uptodate found for {}", child.getDataAfter());
122                     tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(child.getIdentifier()), child.getDataAfter().get());
123                     continue;
124                 }
125                 for (final DataTreeCandidateNode route : this.ribSupport.changedRoutes(child)) {
126                     final PathArgument routeId = route.getIdentifier();
127                     AbstractRouteEntry entry = this.routeEntries.get(routeId);
128
129                     final Optional<NormalizedNode<?, ?>> maybeData = route.getDataAfter();
130                     if (maybeData.isPresent()) {
131                         if (entry == null) {
132                             entry = createEntry(routeId);
133                         }
134
135                         entry.addRoute(routerId, this.attributesIdentifier, maybeData.get());
136                     } else if (entry != null && entry.removeRoute(routerId)) {
137                         this.routeEntries.remove(routeId);
138                         entry = null;
139                         LOG.trace("Removed route from {}", routerId);
140                     }
141                     LOG.debug("Updated route {} entry {}", routeId, entry);
142                     toUpdate.put(new RouteUpdateKey(peerId, routeId), entry);
143                 }
144             }
145         }
146
147         // Now walk all updated entries
148         for (final Entry<RouteUpdateKey, AbstractRouteEntry> e : toUpdate.entrySet()) {
149             LOG.trace("Walking through {}", e);
150             final AbstractRouteEntry entry = e.getValue();
151             final NormalizedNode<?, ?> value;
152
153             if (entry != null) {
154                 if (!entry.selectBest(this.ourAs)) {
155                     // Best path has not changed, no need to do anything else. Proceed to next route.
156                     LOG.trace("Continuing");
157                     continue;
158                 }
159                 value = entry.createValue(e.getKey().getRouteId());
160                 LOG.trace("Selected best value {}", value);
161             } else {
162                 value = null;
163             }
164
165             final YangInstanceIdentifier writePath = this.ribSupport.routePath(this.locRibTarget.node(Routes.QNAME), e.getKey().getRouteId());
166             if (value != null) {
167                 LOG.debug("Write route to LocRib {}", value);
168                 tx.put(LogicalDatastoreType.OPERATIONAL, writePath, value);
169             } else {
170                 LOG.debug("Delete route from LocRib {}", entry);
171                 tx.delete(LogicalDatastoreType.OPERATIONAL, writePath);
172             }
173
174             /*
175              * We need to keep track of routers and populate adj-ribs-out, too. If we do not, we need to
176              * expose from which client a particular route was learned from in the local RIB, and have
177              * the listener perform filtering.
178              *
179              * We walk the policy set in order to minimize the amount of work we do for multiple peers:
180              * if we have two eBGP peers, for example, there is no reason why we should perform the translation
181              * multiple times.
182              */
183             for (final PeerRole role : PeerRole.values()) {
184                 final PeerExportGroup peerGroup = this.peerPolicyTracker.getPeerGroup(role);
185                 if (peerGroup != null) {
186                     final ContainerNode attributes = entry == null ? null : entry.attributes();
187                     final PeerId peerId = e.getKey().getPeerId();
188                     final ContainerNode effectiveAttributes = peerGroup.effectiveAttributes(peerId, attributes);
189                     for (final Entry<PeerId, YangInstanceIdentifier> pid : peerGroup.getPeers()) {
190                         // This points to adj-rib-out for a particular peer/table combination
191                         final RIBSupportContext ribCtx = this.registry.getRIBSupportContext(this.tableKey);
192                         // FIXME: the table should be created for a peer only once
193                         ribCtx.clearTable(tx, pid.getValue().node(AdjRibOut.QNAME).node(Tables.QNAME).node(this.tableKey));
194                         final YangInstanceIdentifier routeTarget = this.ribSupport.routePath(pid.getValue().node(AdjRibOut.QNAME).node(Tables.QNAME).node(this.tableKey).node(Routes.QNAME), e.getKey().getRouteId());
195                         if (effectiveAttributes != null && value != null && !peerId.equals(pid.getKey())) {
196                             LOG.debug("Write route to AdjRibsOut {}", value);
197                             tx.put(LogicalDatastoreType.OPERATIONAL, routeTarget, value);
198                             tx.put(LogicalDatastoreType.OPERATIONAL, routeTarget.node(this.attributesIdentifier), effectiveAttributes);
199                         } else {
200                             LOG.trace("Removing {} from transaction", routeTarget);
201                             tx.delete(LogicalDatastoreType.OPERATIONAL, routeTarget);
202                         }
203                     }
204                 }
205             }
206         }
207         tx.submit();
208     }
209 }