Fix PingPong transaction race in EffectiveRibWriter.
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / EffectiveRibInWriter.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.Preconditions;
11 import com.google.common.base.Verify;
12 import java.util.Collection;
13 import javax.annotation.Nonnull;
14 import javax.annotation.concurrent.NotThreadSafe;
15 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
16 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
17 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
18 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
19 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
20 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
21 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContext;
22 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
23 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibIn;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.EffectiveRibIn;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Routes;
29 import org.opendaylight.yangtools.concepts.ListenerRegistration;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
36 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
37 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * Implementation of the BGP import policy. Listens on all Adj-RIB-In, inspects all inbound
43  * routes in the context of the advertising peer's role and applies the inbound policy.
44  *
45  * Inbound policy is applied as follows:
46  *
47  * 1) if the peer is an eBGP peer, perform attribute replacement and filtering
48  * 2) check if a route is admissible based on attributes attached to it, as well as the
49  *    advertising peer's role
50  * 3) output admitting routes with edited attributes into /bgp-rib/rib/peer/effective-rib-in/tables/routes
51  *
52  * Note that we maintain the peer roles using a DCL, even if we could look up our internal
53  * structures. This is done so we maintain causality and loose coupling.
54  */
55 @NotThreadSafe
56 final class EffectiveRibInWriter implements AutoCloseable {
57     private static final Logger LOG = LoggerFactory.getLogger(EffectiveRibInWriter.class);
58     private static final NodeIdentifier TABLE_ROUTES = new NodeIdentifier(Routes.QNAME);
59     private static final NodeIdentifier ADJRIBIN_NID = new NodeIdentifier(AdjRibIn.QNAME);
60     private static final NodeIdentifier TABLES_NID = new NodeIdentifier(Tables.QNAME);
61
62     /**
63      * Maintains {@link TableRouteListener} instances.
64      */
65     private final class AdjInTracker implements AutoCloseable, DOMDataTreeChangeListener {
66         private final RIBSupportContextRegistry registry;
67         private final YangInstanceIdentifier ribId;
68         private final ListenerRegistration<?> reg;
69         private final DOMTransactionChain chain;
70
71         AdjInTracker(final DOMDataTreeChangeService service, final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier ribId) {
72             this.registry = Preconditions.checkNotNull(registry);
73             this.chain = Preconditions.checkNotNull(chain);
74             this.ribId = Preconditions.checkNotNull(ribId);
75
76             final YangInstanceIdentifier tableId = ribId.node(Peer.QNAME).node(Peer.QNAME);
77             final DOMDataTreeIdentifier treeId = new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, tableId);
78             LOG.debug("Registered Effective RIB on {}", tableId);
79             this.reg = service.registerDataTreeChangeListener(treeId, this);
80         }
81
82         private void processRoute(final DOMDataWriteTransaction tx, final RIBSupport ribSupport, final AbstractImportPolicy policy, final YangInstanceIdentifier routesPath, final DataTreeCandidateNode route) {
83             LOG.debug("Process route {}", route);
84             final YangInstanceIdentifier routeId = ribSupport.routePath(routesPath, route.getIdentifier());
85             switch (route.getModificationType()) {
86             case DELETE:
87                 tx.delete(LogicalDatastoreType.OPERATIONAL, routeId);
88                 break;
89             case UNMODIFIED:
90                 // No-op
91                 break;
92             case SUBTREE_MODIFIED:
93             case WRITE:
94                 tx.put(LogicalDatastoreType.OPERATIONAL, routeId, route.getDataAfter().get());
95                 // Lookup per-table attributes from RIBSupport
96                 final ContainerNode advertisedAttrs = (ContainerNode) NormalizedNodes.findNode(route.getDataAfter(), ribSupport.routeAttributesIdentifier()).orNull();
97                 final ContainerNode effectiveAttrs;
98
99                 if (advertisedAttrs != null) {
100                     effectiveAttrs = policy.effectiveAttributes(advertisedAttrs);
101                 } else {
102                     effectiveAttrs = null;
103                 }
104
105                 LOG.debug("Route {} effective attributes {} towards {}", route.getIdentifier(), effectiveAttrs, routeId);
106
107                 if (effectiveAttrs != null) {
108                     tx.put(LogicalDatastoreType.OPERATIONAL, routeId.node(ribSupport.routeAttributesIdentifier()), effectiveAttrs);
109                 } else {
110                     LOG.warn("Route {} advertised empty attributes", routeId);
111                     tx.delete(LogicalDatastoreType.OPERATIONAL,  routeId);
112                 }
113                 break;
114             default:
115                 LOG.warn("Ignoring unhandled route {}", route);
116                 break;
117             }
118         }
119
120         private void processTableChildren(final DOMDataWriteTransaction tx, final RIBSupport ribSupport, final NodeIdentifierWithPredicates peerKey, final YangInstanceIdentifier tablePath, final Collection<DataTreeCandidateNode> children) {
121             final AbstractImportPolicy policy = EffectiveRibInWriter.this.peerPolicyTracker.policyFor(IdentifierUtils.peerId(peerKey));
122
123             for (final DataTreeCandidateNode child : children) {
124                 LOG.debug("Process table {} type {}", child, child.getModificationType());
125                 final YangInstanceIdentifier childPath = tablePath.node(child.getIdentifier());
126                 switch (child.getModificationType()) {
127                 case DELETE:
128                     tx.delete(LogicalDatastoreType.OPERATIONAL, tablePath.node(child.getIdentifier()));
129                     break;
130                 case UNMODIFIED:
131                     // No-op
132                     break;
133                 case SUBTREE_MODIFIED:
134                     if (TABLE_ROUTES.equals(child.getIdentifier())) {
135                         for (final DataTreeCandidateNode route : ribSupport.changedRoutes(child)) {
136                             processRoute(tx, ribSupport, policy, childPath, route);
137                         }
138                     } else {
139                         tx.put(LogicalDatastoreType.OPERATIONAL, childPath, child.getDataAfter().get());
140                     }
141                     break;
142                 case WRITE:
143                     tx.put(LogicalDatastoreType.OPERATIONAL, childPath, child.getDataAfter().get());
144                     // Routes are special, as they may end up being filtered. The previous put conveniently
145                     // ensured that we have them in at target, so a subsequent delete will not fail :)
146                     if (TABLE_ROUTES.equals(child.getIdentifier())) {
147                         for (final DataTreeCandidateNode route : ribSupport.changedRoutes(child)) {
148                             processRoute(tx, ribSupport, policy, childPath, route);
149                         }
150                     }
151                     break;
152                 default:
153                     LOG.warn("Ignoring unhandled child {}", child);
154                     break;
155                 }
156             }
157         }
158
159         private RIBSupportContext getRibSupport(final NodeIdentifierWithPredicates tableKey) {
160             return this.registry.getRIBSupportContext(tableKey);
161         }
162
163         private YangInstanceIdentifier effectiveTablePath(final NodeIdentifierWithPredicates peerKey, final NodeIdentifierWithPredicates tableKey) {
164             return this.ribId.node(Peer.QNAME).node(peerKey).node(EffectiveRibIn.QNAME).node(Tables.QNAME).node(tableKey);
165         }
166
167         private void modifyTable(final DOMDataWriteTransaction tx, final NodeIdentifierWithPredicates peerKey, final NodeIdentifierWithPredicates tableKey, final DataTreeCandidateNode table) {
168             final RIBSupportContext ribSupport = getRibSupport(tableKey);
169             final YangInstanceIdentifier tablePath = effectiveTablePath(peerKey, tableKey);
170
171             processTableChildren(tx, ribSupport.getRibSupport(), peerKey, tablePath, table.getChildNodes());
172         }
173
174         private void writeTable(final DOMDataWriteTransaction tx, final NodeIdentifierWithPredicates peerKey, final NodeIdentifierWithPredicates tableKey, final DataTreeCandidateNode table) {
175             final RIBSupportContext ribSupport = getRibSupport(tableKey);
176             final YangInstanceIdentifier tablePath = effectiveTablePath(peerKey, tableKey);
177
178             // Create an empty table
179             ribSupport.clearTable(tx,tablePath);
180
181             processTableChildren(tx, ribSupport.getRibSupport(), peerKey, tablePath, table.getChildNodes());
182         }
183
184         @Override
185         public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
186             LOG.trace("Data changed called to effective RIB. Change : {}", changes);
187
188             // we have a lot of transactions created for 'nothing' because a lot of changes
189             // are skipped, so ensure we only create one transaction when we really need it
190             DOMDataWriteTransaction tx = null;
191             for (final DataTreeCandidate tc : changes) {
192                 final YangInstanceIdentifier rootPath = tc.getRootPath();
193
194                 // Obtain the peer's key
195                 final NodeIdentifierWithPredicates peerKey = IdentifierUtils.peerKey(rootPath);
196                 final DataTreeCandidateNode root = tc.getRootNode();
197
198                 // call out peer-role has changed
199                 final DataTreeCandidateNode roleChange =  root.getModifiedChild(AbstractPeerRoleTracker.PEER_ROLE_NID);
200                 if (roleChange != null) {
201                     EffectiveRibInWriter.this.peerPolicyTracker.onDataTreeChanged(roleChange, IdentifierUtils.peerPath(rootPath));
202                 }
203
204                 // filter out any change outside AdjRibsIn
205                 final DataTreeCandidateNode ribIn =  root.getModifiedChild(ADJRIBIN_NID);
206                 if (ribIn == null) {
207                     LOG.debug("Skipping change {}", tc.getRootNode());
208                     continue;
209                 }
210                 final DataTreeCandidateNode tables = ribIn.getModifiedChild(TABLES_NID);
211                 if (tables == null) {
212                     LOG.debug("Skipping change {}", tc.getRootNode());
213                     continue;
214                 }
215                 for (final DataTreeCandidateNode table : tables.getChildNodes()) {
216                     if (tx == null) {
217                         tx = this.chain.newWriteOnlyTransaction();
218                     }
219                     changeDataTree(tx, rootPath, root, peerKey, table);
220                 }
221             }
222             if (tx != null) {
223                 tx.submit();
224             }
225         }
226
227         private void changeDataTree(final DOMDataWriteTransaction tx, final YangInstanceIdentifier rootPath,
228             final DataTreeCandidateNode root, final NodeIdentifierWithPredicates peerKey, final DataTreeCandidateNode table) {
229             final PathArgument lastArg = table.getIdentifier();
230             Verify.verify(lastArg instanceof NodeIdentifierWithPredicates, "Unexpected type %s in path %s", lastArg.getClass(), rootPath);
231             final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
232
233             switch (root.getModificationType()) {
234             case DELETE:
235                 // delete the corresponding effective table
236                 tx.delete(LogicalDatastoreType.OPERATIONAL, effectiveTablePath(peerKey, tableKey));
237                 break;
238             case SUBTREE_MODIFIED:
239                 modifyTable(tx, peerKey, tableKey, table);
240                 break;
241             case UNMODIFIED:
242                 LOG.info("Ignoring spurious notification on {} data {}", rootPath, table);
243                 break;
244             case WRITE:
245                 writeTable(tx, peerKey, tableKey, table);
246                 break;
247             default:
248                 LOG.warn("Ignoring unhandled root {}", root);
249                 break;
250             }
251         }
252
253         @Override
254         public void close() {
255             // FIXME: wipe all effective routes?
256             this.reg.close();
257         }
258     }
259
260     private final ImportPolicyPeerTracker peerPolicyTracker;
261     private final AdjInTracker adjInTracker;
262
263     static EffectiveRibInWriter create(@Nonnull final DOMDataTreeChangeService service, @Nonnull final DOMTransactionChain chain,
264         @Nonnull final YangInstanceIdentifier ribId, @Nonnull final PolicyDatabase pd, @Nonnull final RIBSupportContextRegistry registry) {
265         return new EffectiveRibInWriter(service, chain, ribId, pd, registry);
266     }
267
268     private EffectiveRibInWriter(final DOMDataTreeChangeService service, final DOMTransactionChain chain, final YangInstanceIdentifier ribId,
269         final PolicyDatabase pd, final RIBSupportContextRegistry registry) {
270         this.peerPolicyTracker = new ImportPolicyPeerTracker(pd);
271         this.adjInTracker = new AdjInTracker(service, registry, chain, ribId);
272     }
273
274     @Override
275     public void close() {
276         this.adjInTracker.close();
277     }
278 }