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