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