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