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