MVPN RFC6514 Extendend communities
[bgpcep.git] / bgp / rib-spi / src / main / java / org / opendaylight / protocol / bgp / rib / spi / AbstractRIBSupport.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.spi;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import java.util.Collection;
14 import java.util.Collections;
15 import java.util.Optional;
16 import javax.annotation.Nonnull;
17 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
18 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Update;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.UpdateBuilder;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.Attributes;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.AttributesBuilder;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.Attributes1;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.Attributes1Builder;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.Attributes2;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.Attributes2Builder;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.destination.DestinationType;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpReachNlri;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpReachNlriBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpUnreachNlri;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpUnreachNlriBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.reach.nlri.AdvertizedRoutes;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.unreach.nlri.WithdrawnRoutes;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.Route;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.Routes;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.AddressFamily;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.SubsequentAddressFamily;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev180329.next.hop.CNextHop;
43 import org.opendaylight.yangtools.yang.binding.DataObject;
44 import org.opendaylight.yangtools.yang.binding.Identifier;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
46 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
53 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
56 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
59 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
60 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
61 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
62 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 @Beta
67 public abstract class AbstractRIBSupport<R extends Route, N extends Identifier>
68         implements RIBSupport<R, N> {
69     public static final String ROUTE_KEY = "route-key";
70     private static final Logger LOG = LoggerFactory.getLogger(AbstractRIBSupport.class);
71     private static final NodeIdentifier ADVERTISED_ROUTES = new NodeIdentifier(AdvertizedRoutes.QNAME);
72     private static final NodeIdentifier WITHDRAWN_ROUTES = new NodeIdentifier(WithdrawnRoutes.QNAME);
73     private static final NodeIdentifier DESTINATION_TYPE = new NodeIdentifier(DestinationType.QNAME);
74     private static final NodeIdentifier ROUTES = new NodeIdentifier(Routes.QNAME);
75     private static final ApplyRoute DELETE_ROUTE = new DeleteRoute();
76     private final NodeIdentifier routesContainerIdentifier;
77     private final NodeIdentifier routesListIdentifier;
78     private final NodeIdentifier routeAttributesIdentifier;
79     private final Class<? extends Routes> cazeClass;
80     private final Class<? extends DataObject> containerClass;
81     private final Class<? extends Route> listClass;
82     private final ApplyRoute putRoute = new PutRoute();
83     private final ChoiceNode emptyRoutes;
84     private final QName routeQname;
85     private final Class<? extends AddressFamily> afiClass;
86     private final Class<? extends SubsequentAddressFamily> safiClass;
87     private final NodeIdentifier destinationNid;
88     private final QName pathIdQname;
89     private final NodeIdentifier pathIdNid;
90     private final QName routeKeyQname;
91     private final NodeIdentifier routeKeyNodeId;
92
93     /**
94      * Default constructor. Requires the QName of the container augmented under the routes choice
95      * node in instantiations of the rib grouping. It is assumed that this container is defined by
96      * the same model which populates it with route grouping instantiation, and by extension with
97      * the route attributes container.
98      *  @param cazeClass        Binding class of the AFI/SAFI-specific case statement, must not be null
99      * @param containerClass   Binding class of the container in routes choice, must not be null.
100      * @param listClass        Binding class of the route list, nust not be null;
101      * @param afiClass         address Family Class
102      * @param safiClass        SubsequentAddressFamily
103      * @param destinationQname destination Qname
104      */
105     protected AbstractRIBSupport(
106             final Class<? extends Routes> cazeClass,
107             final Class<? extends DataObject> containerClass,
108             final Class<? extends Route> listClass,
109             final Class<? extends AddressFamily> afiClass,
110             final Class<? extends SubsequentAddressFamily> safiClass,
111             final QName destinationQname) {
112         final QName qname = BindingReflections.findQName(containerClass).intern();
113         this.routesContainerIdentifier = new NodeIdentifier(qname);
114         this.routeAttributesIdentifier = new NodeIdentifier(QName.create(qname,
115                 Attributes.QNAME.getLocalName().intern()));
116         this.cazeClass = requireNonNull(cazeClass);
117         this.containerClass = requireNonNull(containerClass);
118         this.listClass = requireNonNull(listClass);
119         this.routeQname = QName.create(qname, BindingReflections.findQName(listClass).intern().getLocalName());
120         this.routesListIdentifier = new NodeIdentifier(this.routeQname);
121         this.emptyRoutes = Builders.choiceBuilder().withNodeIdentifier(ROUTES)
122                 .addChild(Builders.containerBuilder()
123                 .withNodeIdentifier(routesContainerIdentifier())
124                 .withChild(ImmutableNodes.mapNodeBuilder(this.routeQname).build()).build()).build();
125         this.afiClass = afiClass;
126         this.safiClass = safiClass;
127         this.destinationNid = new NodeIdentifier(destinationQname);
128         this.pathIdQname = QName.create(routeQName(), "path-id").intern();
129         this.pathIdNid = new NodeIdentifier(this.pathIdQname);
130         this.routeKeyQname = QName.create(routeQName(), ROUTE_KEY).intern();
131         this.routeKeyNodeId = new NodeIdentifier(this.routeKeyQname);
132     }
133
134     @Override
135     public final Class<? extends Routes> routesCaseClass() {
136         return this.cazeClass;
137     }
138
139     @Override
140     public final Class<? extends DataObject> routesContainerClass() {
141         return this.containerClass;
142     }
143
144     @Override
145     public final Class<? extends Route> routesListClass() {
146         return this.listClass;
147     }
148
149     @Override
150     public final ChoiceNode emptyRoutes() {
151         return this.emptyRoutes;
152     }
153
154     public final QName routeQName() {
155         return this.routeQname;
156     }
157
158     protected final NodeIdentifier routeNid() {
159         return this.routesListIdentifier;
160     }
161
162     @Nonnull
163     @Override
164     public final Class<? extends AddressFamily> getAfi() {
165         return this.afiClass;
166     }
167
168     @Nonnull
169     @Override
170     public final Class<? extends SubsequentAddressFamily> getSafi() {
171         return this.safiClass;
172     }
173
174     /**
175      * Build MpReachNlri object from DOM representation.
176      *
177      * @param routes Collection of MapEntryNode DOM representation of routes
178      * @param hop    CNextHop as it was parsed from Attributes, to be included in MpReach object
179      * @return MpReachNlri
180      */
181     private MpReachNlri buildReach(final Collection<MapEntryNode> routes, final CNextHop hop) {
182         final MpReachNlriBuilder mb = new MpReachNlriBuilder();
183         mb.setAfi(this.getAfi());
184         mb.setSafi(this.getSafi());
185         mb.setCNextHop(hop);
186         mb.setAdvertizedRoutes(new AdvertizedRoutesBuilder().setDestinationType(buildDestination(routes)).build());
187         return mb.build();
188     }
189
190     /**
191      * Build MpUnReachNlri object from DOM representation.
192      *
193      * @param routes Collection of MapEntryNode DOM representation of routes
194      * @return MpUnreachNlri
195      */
196     private MpUnreachNlri buildUnreach(final Collection<MapEntryNode> routes) {
197         final MpUnreachNlriBuilder mb = new MpUnreachNlriBuilder();
198         mb.setAfi(this.getAfi());
199         mb.setSafi(this.getSafi());
200         mb.setWithdrawnRoutes(new WithdrawnRoutesBuilder()
201                 .setDestinationType(buildWithdrawnDestination(routes)).build());
202         return mb.build();
203     }
204
205     @Nonnull
206     protected abstract DestinationType buildDestination(@Nonnull Collection<MapEntryNode> routes);
207
208     @Nonnull
209     protected abstract DestinationType buildWithdrawnDestination(@Nonnull Collection<MapEntryNode> routes);
210
211     /**
212      * Return the {@link NodeIdentifier} of the AFI/SAFI-specific container under
213      * the RIB routes.
214      *
215      * @return Container identifier, may not be null.
216      */
217     protected final NodeIdentifier routesContainerIdentifier() {
218         return this.routesContainerIdentifier;
219     }
220
221     /**
222      * Return the {@link NodeIdentifier} of the AFI/SAFI-specific container under
223      * the NLRI destination.
224      *
225      * @return Container identifier, may not be null.
226      */
227     private NodeIdentifier destinationContainerIdentifier() {
228         return this.destinationNid;
229     }
230
231     /**
232      * Given the destination as ContainerNode, implementation needs to parse the DOM model
233      * from this point onward:
234      *
235      * {@code /bgp-mp:mp-unreach-nlri/bgp-mp:withdrawn-routes/bgp-mp:destination-type}
236      * and delete the routes from its RIBs.
237      *
238      * @param tx           DOMDataWriteTransaction to be passed into implementation
239      * @param tablePath    YangInstanceIdentifier to be passed into implementation
240      * @param destination  ContainerNode DOM representation of NLRI in Update message
241      * @param routesNodeId NodeIdentifier
242      */
243     private void deleteDestinationRoutes(final DOMDataWriteTransaction tx, final YangInstanceIdentifier tablePath,
244             final ContainerNode destination, final NodeIdentifier routesNodeId) {
245         processDestination(tx, tablePath.node(routesNodeId), destination, null, DELETE_ROUTE);
246     }
247
248     /**
249      * Given the destination as ContainerNode, implementation needs to parse the DOM model
250      * from this point onward:
251      *
252      * {@code /bgp-mp:mp-reach-nlri/bgp-mp:advertized-routes/bgp-mp:destination-type}
253      * and put the routes to its RIBs.
254      *
255      * @param tx           DOMDataWriteTransaction to be passed into implementation
256      * @param tablePath    YangInstanceIdentifier to be passed into implementation
257      * @param destination  ContainerNode DOM representation of NLRI in Update message
258      * @param attributes   ContainerNode to be passed into implementation
259      * @param routesNodeId NodeIdentifier
260      */
261     private void putDestinationRoutes(final DOMDataWriteTransaction tx, final YangInstanceIdentifier tablePath,
262             final ContainerNode destination, final ContainerNode attributes, final NodeIdentifier routesNodeId) {
263         processDestination(tx, tablePath.node(routesNodeId), destination, attributes, this.putRoute);
264     }
265
266     protected abstract void processDestination(DOMDataWriteTransaction tx, YangInstanceIdentifier routesPath,
267             ContainerNode destination, ContainerNode attributes, ApplyRoute applyFunction);
268
269     private static ContainerNode getDestination(final DataContainerChild<? extends PathArgument, ?> routes,
270             final NodeIdentifier destinationId) {
271         if (routes instanceof ContainerNode) {
272             final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> maybeDestination =
273                     ((ContainerNode) routes).getChild(DESTINATION_TYPE);
274             if (maybeDestination.isPresent()) {
275                 final DataContainerChild<? extends PathArgument, ?> destination = maybeDestination.get();
276                 if (destination instanceof ChoiceNode) {
277                     final Optional<DataContainerChild<? extends PathArgument, ?>> maybeRet =
278                             ((ChoiceNode) destination).getChild(destinationId);
279                     if (maybeRet.isPresent()) {
280                         final DataContainerChild<? extends PathArgument, ?> ret = maybeRet.get();
281                         if (ret instanceof ContainerNode) {
282                             return (ContainerNode) ret;
283                         }
284
285                         LOG.debug("Specified node {} is not a container, ignoring it", ret);
286                     } else {
287                         LOG.debug("Specified container {} is not present in destination {}",
288                                 destinationId, destination);
289                     }
290                 } else {
291                     LOG.warn("Destination {} is not a choice, ignoring it", destination);
292                 }
293             } else {
294                 LOG.debug("Destination is not present in routes {}", routes);
295             }
296         } else {
297             LOG.warn("Advertized routes {} are not a container, ignoring it", routes);
298         }
299
300         return null;
301     }
302
303     @Override
304     public final NodeIdentifier routeAttributesIdentifier() {
305         return this.routeAttributesIdentifier;
306     }
307
308     @Override
309     public final Collection<DataTreeCandidateNode> changedRoutes(final DataTreeCandidateNode routes) {
310         final DataTreeCandidateNode myRoutes = routes.getModifiedChild(this.routesContainerIdentifier);
311         if (myRoutes == null) {
312             return Collections.emptySet();
313         }
314         final DataTreeCandidateNode routesMap = myRoutes.getModifiedChild(routeNid());
315         if (routesMap == null) {
316             return Collections.emptySet();
317         }
318         // Well, given the remote possibility of augmentation, we should perform a filter here,
319         // to make sure the type matches what routeType() reports.
320         return routesMap.getChildNodes();
321     }
322
323     @Override
324     public final YangInstanceIdentifier routePath(final YangInstanceIdentifier routesPath, final PathArgument routeId) {
325         return routesPath.node(this.routesContainerIdentifier).node(routeNid()).node(routeId);
326     }
327
328     @Override
329     public final InstanceIdentifier<R> createRouteIdentifier(
330             final KeyedInstanceIdentifier<Tables, TablesKey> tableIId, final N key) {
331         return tableIId.child((Class) routesContainerClass()).child(routesListClass(), key);
332     }
333
334     @Override
335     public final void deleteRoutes(final DOMDataWriteTransaction tx, final YangInstanceIdentifier tablePath,
336             final ContainerNode nlri) {
337         deleteRoutes(tx, tablePath, nlri, ROUTES);
338     }
339
340     @Override
341     public final void putRoutes(final DOMDataWriteTransaction tx, final YangInstanceIdentifier tablePath,
342             final ContainerNode nlri, final ContainerNode attributes) {
343         putRoutes(tx, tablePath, nlri, attributes, ROUTES);
344     }
345
346     @Nonnull
347     @Override
348     public final Update buildUpdate(final Collection<MapEntryNode> advertised, final Collection<MapEntryNode> withdrawn,
349             final Attributes attr) {
350         final UpdateBuilder ub = new UpdateBuilder();
351         final AttributesBuilder ab = new AttributesBuilder(attr);
352         final CNextHop hop = ab.getCNextHop();
353
354         LOG.debug("cnextHop before={}", hop);
355         // do not preserve next hop in attributes if we are using MpReach
356         ab.setCNextHop(null);
357
358         if (!advertised.isEmpty()) {
359             final MpReachNlri mb = buildReach(advertised, hop);
360             ab.addAugmentation(Attributes1.class, new Attributes1Builder().setMpReachNlri(mb).build());
361             LOG.debug("mpreach nexthop={}", mb);
362         }
363         if (!withdrawn.isEmpty()) {
364             final MpUnreachNlri mb = buildUnreach(withdrawn);
365             ab.addAugmentation(Attributes2.class, new Attributes2Builder().setMpUnreachNlri(mb).build());
366             LOG.debug("mpunrach mb={}", mb);
367         }
368
369         ub.setAttributes(ab.build());
370         LOG.debug("update {}", ub.build());
371         return ub.build();
372     }
373
374     @Override
375     @SuppressWarnings("checkstyle:OverloadMethodsDeclarationOrder")
376     public final void deleteRoutes(final DOMDataWriteTransaction tx, final YangInstanceIdentifier tablePath,
377             final ContainerNode nlri, final NodeIdentifier routesNodeId) {
378         final Optional<DataContainerChild<? extends PathArgument, ?>> maybeRoutes = nlri.getChild(WITHDRAWN_ROUTES);
379         if (maybeRoutes.isPresent()) {
380             final ContainerNode destination = getDestination(maybeRoutes.get(), destinationContainerIdentifier());
381             if (destination != null) {
382                 deleteDestinationRoutes(tx, tablePath, destination, routesNodeId);
383             }
384         } else {
385             LOG.debug("Withdrawn routes are not present in NLRI {}", nlri);
386         }
387     }
388
389     @Override
390     public final void putRoutes(final DOMDataWriteTransaction tx, final YangInstanceIdentifier tablePath,
391             final ContainerNode nlri, final ContainerNode attributes, final NodeIdentifier routesNodeId) {
392         final Optional<DataContainerChild<? extends PathArgument, ?>> maybeRoutes = nlri.getChild(ADVERTISED_ROUTES);
393         if (maybeRoutes.isPresent()) {
394             final ContainerNode destination = getDestination(maybeRoutes.get(), destinationContainerIdentifier());
395             if (destination != null) {
396                 putDestinationRoutes(tx, tablePath, destination, attributes, routesNodeId);
397             }
398         } else {
399             LOG.debug("Advertized routes are not present in NLRI {}", nlri);
400         }
401     }
402
403     private static final class DeleteRoute implements ApplyRoute {
404         @Override
405         public void apply(final DOMDataWriteTransaction tx, final YangInstanceIdentifier base,
406                 final NodeIdentifierWithPredicates routeKey, final DataContainerNode<?> route,
407                 final ContainerNode attributes) {
408             tx.delete(LogicalDatastoreType.OPERATIONAL, base.node(routeKey));
409         }
410     }
411
412     private final class PutRoute implements ApplyRoute {
413         @Override
414         public void apply(final DOMDataWriteTransaction tx, final YangInstanceIdentifier base,
415                 final NodeIdentifierWithPredicates routeKey, final DataContainerNode<?> route,
416                 final ContainerNode attributes) {
417             // Build the DataContainer data
418             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> b =
419                     ImmutableNodes.mapEntryBuilder();
420             b.withNodeIdentifier(routeKey);
421
422             route.getValue().forEach(b::withChild);
423             // Add attributes
424             final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> cb =
425                     Builders.containerBuilder(attributes);
426             cb.withNodeIdentifier(routeAttributesIdentifier());
427             b.withChild(cb.build());
428             tx.put(LogicalDatastoreType.OPERATIONAL, base.node(routeKey), b.build());
429         }
430     }
431
432     protected final NodeIdentifier routePathIdNid() {
433         return this.pathIdNid;
434     }
435
436     protected final QName pathIdQName() {
437         return this.pathIdQname;
438     }
439
440     protected final QName routeKeyQName() {
441         return this.routeKeyQname;
442     }
443
444     protected final NodeIdentifier routeKeyNodeIdentifier() {
445         return this.routeKeyNodeId;
446     }
447 }