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