Update MRI projects for Aluminium
[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 com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.BGPRIB_NID;
13 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.LOCRIB_NID;
14 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.RIB_NID;
15 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ROUTES_NID;
16 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.TABLES_NID;
17
18 import com.google.common.annotations.Beta;
19 import com.google.common.cache.CacheBuilder;
20 import com.google.common.cache.CacheLoader;
21 import com.google.common.cache.LoadingCache;
22 import com.google.common.collect.ImmutableList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.Optional;
27 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
28 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
29 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
30 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.Update;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.UpdateBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.Attributes;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev200120.path.attributes.AttributesBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.Attributes1Builder;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.Attributes2Builder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.destination.DestinationType;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpReachNlri;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpReachNlriBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpUnreachNlri;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.MpUnreachNlriBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.reach.nlri.AdvertizedRoutes;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.reach.nlri.AdvertizedRoutesBuilder;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.unreach.nlri.WithdrawnRoutes;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.update.attributes.mp.unreach.nlri.WithdrawnRoutesBuilder;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.BgpRib;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.Route;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.Rib;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.LocRib;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesBuilder;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.tables.Routes;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.AddressFamily;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.RouteDistinguisher;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.RouteDistinguisherBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.SubsequentAddressFamily;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.next.hop.CNextHop;
59 import org.opendaylight.yangtools.util.ImmutableOffsetMapTemplate;
60 import org.opendaylight.yangtools.yang.binding.ChildOf;
61 import org.opendaylight.yangtools.yang.binding.ChoiceIn;
62 import org.opendaylight.yangtools.yang.binding.DataObject;
63 import org.opendaylight.yangtools.yang.binding.Identifiable;
64 import org.opendaylight.yangtools.yang.binding.Identifier;
65 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
66 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
67 import org.opendaylight.yangtools.yang.common.QName;
68 import org.opendaylight.yangtools.yang.common.QNameModule;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
71 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
72 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
73 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
76 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
80 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
81 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
82 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85
86 @Beta
87 public abstract class AbstractRIBSupport<
88         C extends Routes & DataObject & ChoiceIn<Tables>,
89         S extends ChildOf<? super C>,
90         R extends Route & ChildOf<? super S> & Identifiable<I>,
91         I extends Identifier<R>>
92         implements RIBSupport<C, S, R, I> {
93     public static final String ROUTE_KEY = "route-key";
94     private static final Logger LOG = LoggerFactory.getLogger(AbstractRIBSupport.class);
95     private static final NodeIdentifier ADVERTISED_ROUTES = NodeIdentifier.create(AdvertizedRoutes.QNAME);
96     private static final NodeIdentifier WITHDRAWN_ROUTES = NodeIdentifier.create(WithdrawnRoutes.QNAME);
97     private static final NodeIdentifier DESTINATION_TYPE = NodeIdentifier.create(DestinationType.QNAME);
98     private static final InstanceIdentifier<Tables> TABLES_II = InstanceIdentifier.builder(BgpRib.class)
99             .child(Rib.class).child(LocRib.class).child(Tables.class).build();
100     private static final ApplyRoute DELETE_ROUTE = new DeleteRoute();
101     // Instance identifier to table/(choice routes)/(map of route)
102     private final LoadingCache<YangInstanceIdentifier, YangInstanceIdentifier> routesPath = CacheBuilder.newBuilder()
103             .weakValues().build(new CacheLoader<YangInstanceIdentifier, YangInstanceIdentifier>() {
104                 @Override
105                 public YangInstanceIdentifier load(final YangInstanceIdentifier routesTablePaths) {
106                     return routesTablePaths.node(routesContainerIdentifier()).node(routeQName());
107                 }
108             });
109     private final NodeIdentifier routesContainerIdentifier;
110     private final NodeIdentifier routesListIdentifier;
111     private final NodeIdentifier routeAttributesIdentifier;
112     private final Class<C> cazeClass;
113     private final Class<S> containerClass;
114     private final Class<R> listClass;
115     private final ApplyRoute putRoute = new PutRoute();
116     private final MapEntryNode emptyTable;
117     private final QName routeQname;
118     private final Class<? extends AddressFamily> afiClass;
119     private final Class<? extends SubsequentAddressFamily> safiClass;
120     private final NodeIdentifier destinationNid;
121     private final NodeIdentifier pathIdNid;
122     private final NodeIdentifier prefixTypeNid;
123     private final NodeIdentifier rdNid;
124     protected final BindingNormalizedNodeSerializer mappingService;
125     protected final YangInstanceIdentifier routeDefaultYii;
126     private final TablesKey tk;
127     private final ImmutableList<PathArgument> relativeRoutesPath;
128     private final ImmutableOffsetMapTemplate<QName> routeKeyTemplate;
129
130     /**
131      * Default constructor. Requires the QName of the container augmented under the routes choice
132      * node in instantiations of the rib grouping. It is assumed that this container is defined by
133      * the same model which populates it with route grouping instantiation, and by extension with
134      * the route attributes container.
135      *
136      * @param mappingService   Serialization service
137      * @param cazeClass        Binding class of the AFI/SAFI-specific case statement, must not be null
138      * @param containerClass   Binding class of the container in routes choice, must not be null.
139      * @param listClass        Binding class of the route list, nust not be null;
140      * @param afiClass         address Family Class
141      * @param safiClass        SubsequentAddressFamily
142      * @param destContainerQname destination Container Qname
143      */
144     protected AbstractRIBSupport(
145             final BindingNormalizedNodeSerializer mappingService,
146             final Class<C> cazeClass,
147             final Class<S> containerClass,
148             final Class<R> listClass,
149             final Class<? extends AddressFamily> afiClass,
150             final Class<? extends SubsequentAddressFamily> safiClass,
151             final QName destContainerQname) {
152         final QNameModule module = BindingReflections.getQNameModule(cazeClass);
153         this.routesContainerIdentifier = NodeIdentifier.create(
154             BindingReflections.findQName(containerClass).bindTo(module));
155         this.routeAttributesIdentifier = NodeIdentifier.create(Attributes.QNAME.bindTo(module));
156         this.cazeClass = requireNonNull(cazeClass);
157         this.mappingService = requireNonNull(mappingService);
158         this.containerClass = requireNonNull(containerClass);
159         this.listClass = requireNonNull(listClass);
160         this.routeQname = BindingReflections.findQName(listClass).bindTo(module);
161         this.routesListIdentifier = NodeIdentifier.create(this.routeQname);
162         this.tk = new TablesKey(afiClass, safiClass);
163         this.emptyTable = (MapEntryNode) this.mappingService
164                 .toNormalizedNode(TABLES_II, new TablesBuilder().withKey(tk)
165                         .setAttributes(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib
166                                 .rev180329.rib.tables.AttributesBuilder().build()).build()).getValue();
167         this.afiClass = afiClass;
168         this.safiClass = safiClass;
169         this.destinationNid = NodeIdentifier.create(destContainerQname);
170         this.pathIdNid = NodeIdentifier.create(QName.create(routeQName(), "path-id").intern());
171         this.prefixTypeNid = NodeIdentifier.create(QName.create(destContainerQname, "prefix").intern());
172         this.rdNid = NodeIdentifier.create(QName.create(destContainerQname, "route-distinguisher").intern());
173         this.routeDefaultYii =
174                 YangInstanceIdentifier.builder()
175                         .node(BGPRIB_NID)
176                         .node(RIB_NID)
177                         .node(RIB_NID)
178                         .node(LOCRIB_NID)
179                         .node(TABLES_NID)
180                         .node(TABLES_NID)
181                         .node(ROUTES_NID)
182                         .node(this.routesContainerIdentifier)
183                         .node(this.routesListIdentifier)
184                         .node(this.routesListIdentifier).build();
185         this.relativeRoutesPath = ImmutableList.of(routesContainerIdentifier, routesListIdentifier);
186         this.routeKeyTemplate = ImmutableOffsetMapTemplate.ordered(
187             ImmutableList.of(this.pathIdNid.getNodeType(), QName.create(routeQName(), ROUTE_KEY).intern()));
188     }
189
190     @Override
191     public final TablesKey getTablesKey() {
192         return this.tk;
193     }
194
195     @Override
196     public final Class<C> routesCaseClass() {
197         return this.cazeClass;
198     }
199
200     @Override
201     public final Class<S> routesContainerClass() {
202         return this.containerClass;
203     }
204
205     @Override
206     public final Class<R> routesListClass() {
207         return this.listClass;
208     }
209
210     @Override
211     public final MapEntryNode emptyTable() {
212         return this.emptyTable;
213     }
214
215     public final QName routeQName() {
216         return this.routeQname;
217     }
218
219     protected final NodeIdentifier prefixNid() {
220         return this.prefixTypeNid;
221     }
222
223     protected final NodeIdentifier routeNid() {
224         return this.routesListIdentifier;
225     }
226
227     @Override
228     public final Class<? extends AddressFamily> getAfi() {
229         return this.afiClass;
230     }
231
232     @Override
233     public final Class<? extends SubsequentAddressFamily> getSafi() {
234         return this.safiClass;
235     }
236
237     /**
238      * Build MpReachNlri object from DOM representation.
239      *
240      * @param routes Collection of MapEntryNode DOM representation of routes
241      * @param hop    CNextHop as it was parsed from Attributes, to be included in MpReach object
242      * @return MpReachNlri
243      */
244     private MpReachNlri buildReach(final Collection<MapEntryNode> routes, final CNextHop hop) {
245         final MpReachNlriBuilder mb = new MpReachNlriBuilder();
246         mb.setAfi(this.getAfi());
247         mb.setSafi(this.getSafi());
248         mb.setCNextHop(hop);
249         mb.setAdvertizedRoutes(new AdvertizedRoutesBuilder().setDestinationType(buildDestination(routes)).build());
250         return mb.build();
251     }
252
253     /**
254      * Build MpUnReachNlri object from DOM representation.
255      *
256      * @param routes Collection of MapEntryNode DOM representation of routes
257      * @return MpUnreachNlri
258      */
259     private MpUnreachNlri buildUnreach(final Collection<MapEntryNode> routes) {
260         final MpUnreachNlriBuilder mb = new MpUnreachNlriBuilder();
261         mb.setAfi(this.getAfi());
262         mb.setSafi(this.getSafi());
263         mb.setWithdrawnRoutes(new WithdrawnRoutesBuilder()
264                 .setDestinationType(buildWithdrawnDestination(routes)).build());
265         return mb.build();
266     }
267
268     protected abstract DestinationType buildDestination(Collection<MapEntryNode> routes);
269
270     protected abstract DestinationType buildWithdrawnDestination(Collection<MapEntryNode> routes);
271
272     /**
273      * Return the {@link NodeIdentifier} of the AFI/SAFI-specific container under
274      * the RIB routes.
275      *
276      * @return Container identifier, may not be null.
277      */
278     public final NodeIdentifier routesContainerIdentifier() {
279         return this.routesContainerIdentifier;
280     }
281
282     /**
283      * Return the {@link NodeIdentifier} of the AFI/SAFI-specific container under
284      * the NLRI destination.
285      *
286      * @return Container identifier, may not be null.
287      */
288     private NodeIdentifier destinationContainerIdentifier() {
289         return this.destinationNid;
290     }
291
292     /**
293      * Given the destination as ContainerNode, implementation needs to parse the DOM model
294      * from this point onward:
295      *
296      * {@code /bgp-mp:mp-unreach-nlri/bgp-mp:withdrawn-routes/bgp-mp:destination-type}
297      * and delete the routes from its RIBs.
298      *
299      * @param tx           DOMDataWriteTransaction to be passed into implementation
300      * @param tablePath    YangInstanceIdentifier to be passed into implementation
301      * @param destination  ContainerNode DOM representation of NLRI in Update message
302      * @param routesNodeId NodeIdentifier
303      */
304     private void deleteDestinationRoutes(final DOMDataTreeWriteTransaction tx, final YangInstanceIdentifier tablePath,
305             final ContainerNode destination, final NodeIdentifier routesNodeId) {
306         processDestination(tx, tablePath.node(routesNodeId), destination, null, DELETE_ROUTE);
307     }
308
309     /**
310      * Given the destination as ContainerNode, implementation needs to parse the DOM model
311      * from this point onward:
312      *
313      * {@code /bgp-mp:mp-reach-nlri/bgp-mp:advertized-routes/bgp-mp:destination-type}
314      * and put the routes to its RIBs.
315      *
316      * @param tx           DOMDataWriteTransaction to be passed into implementation
317      * @param tablePath    YangInstanceIdentifier to be passed into implementation
318      * @param destination  ContainerNode DOM representation of NLRI in Update message
319      * @param attributes   ContainerNode to be passed into implementation
320      * @param routesNodeId NodeIdentifier
321      * @return List of processed route identifiers
322      */
323     private Collection<NodeIdentifierWithPredicates> putDestinationRoutes(final DOMDataTreeWriteTransaction tx,
324             final YangInstanceIdentifier tablePath, final ContainerNode destination, final ContainerNode attributes,
325             final NodeIdentifier routesNodeId) {
326         return processDestination(tx, tablePath.node(routesNodeId), destination, attributes, this.putRoute);
327     }
328
329     protected abstract Collection<NodeIdentifierWithPredicates> processDestination(DOMDataTreeWriteTransaction tx,
330             YangInstanceIdentifier routesPath, ContainerNode destination, ContainerNode attributes,
331             ApplyRoute applyFunction);
332
333     private static ContainerNode getDestination(final DataContainerChild<? extends PathArgument, ?> routes,
334             final NodeIdentifier destinationId) {
335         if (routes instanceof ContainerNode) {
336             final java.util.Optional<DataContainerChild<? extends PathArgument, ?>> maybeDestination =
337                     ((ContainerNode) routes).getChild(DESTINATION_TYPE);
338             if (maybeDestination.isPresent()) {
339                 final DataContainerChild<? extends PathArgument, ?> destination = maybeDestination.get();
340                 if (destination instanceof ChoiceNode) {
341                     final Optional<DataContainerChild<? extends PathArgument, ?>> maybeRet =
342                             ((ChoiceNode) destination).getChild(destinationId);
343                     if (maybeRet.isPresent()) {
344                         final DataContainerChild<? extends PathArgument, ?> ret = maybeRet.get();
345                         if (ret instanceof ContainerNode) {
346                             return (ContainerNode) ret;
347                         }
348
349                         LOG.debug("Specified node {} is not a container, ignoring it", ret);
350                     } else {
351                         LOG.debug("Specified container {} is not present in destination {}",
352                                 destinationId, destination);
353                     }
354                 } else {
355                     LOG.warn("Destination {} is not a choice, ignoring it", destination);
356                 }
357             } else {
358                 LOG.debug("Destination is not present in routes {}", routes);
359             }
360         } else {
361             LOG.warn("Advertized routes {} are not a container, ignoring it", routes);
362         }
363
364         return null;
365     }
366
367     @Override
368     public final NodeIdentifier routeAttributesIdentifier() {
369         return this.routeAttributesIdentifier;
370     }
371
372     @Override
373     public final Collection<DataTreeCandidateNode> changedRoutes(final DataTreeCandidateNode routes) {
374         return routes.getModifiedChild(this.routesContainerIdentifier)
375             .flatMap(myRoutes -> myRoutes.getModifiedChild(routeNid()))
376             // Well, given the remote possibility of augmentation, we should perform a filter here,
377             // to make sure the type matches what routeType() reports.
378             .map(DataTreeCandidateNode::getChildNodes)
379             .orElse(Collections.emptySet());
380     }
381
382     @Override
383     public final YangInstanceIdentifier routesPath(final YangInstanceIdentifier routesTablePaths) {
384         return routesYangInstanceIdentifier(routesTablePaths.node(ROUTES_NID));
385     }
386
387     @Override
388     public final List<PathArgument> relativeRoutesPath() {
389         return relativeRoutesPath;
390     }
391
392     @Override
393     public final InstanceIdentifier<R> createRouteIdentifier(
394             final KeyedInstanceIdentifier<Tables, TablesKey> tableIId, final I key) {
395         //FIXME Cache
396         return tableIId.child(routesCaseClass(), routesContainerClass()).child(routesListClass(), key);
397     }
398
399     @Override
400     public final void deleteRoutes(final DOMDataTreeWriteTransaction tx, final YangInstanceIdentifier tablePath,
401             final ContainerNode nlri) {
402         deleteRoutes(tx, tablePath, nlri, ROUTES_NID);
403     }
404
405     @Override
406     public final Collection<NodeIdentifierWithPredicates> putRoutes(final DOMDataTreeWriteTransaction tx,
407                                                                     final YangInstanceIdentifier tablePath,
408                                                                     final ContainerNode nlri,
409                                                                     final ContainerNode attributes) {
410         return putRoutes(tx, tablePath, nlri, attributes, ROUTES_NID);
411     }
412
413     @Override
414     public final Update buildUpdate(final Collection<MapEntryNode> advertised, final Collection<MapEntryNode> withdrawn,
415             final Attributes attr) {
416         final UpdateBuilder ub = new UpdateBuilder();
417         final AttributesBuilder ab = new AttributesBuilder(attr);
418         final CNextHop hop = ab.getCNextHop();
419
420         LOG.debug("cnextHop before={}", hop);
421         // do not preserve next hop in attributes if we are using MpReach
422         ab.setCNextHop(null);
423
424         if (!advertised.isEmpty()) {
425             final MpReachNlri mb = buildReach(advertised, hop);
426             ab.addAugmentation(new Attributes1Builder().setMpReachNlri(mb).build());
427             LOG.debug("mpreach nexthop={}", mb);
428         }
429         if (!withdrawn.isEmpty()) {
430             final MpUnreachNlri mb = buildUnreach(withdrawn);
431             ab.addAugmentation(new Attributes2Builder().setMpUnreachNlri(mb).build());
432             LOG.debug("mpunrach mb={}", mb);
433         }
434
435         ub.setAttributes(ab.build());
436         LOG.debug("update {}", ub.build());
437         return ub.build();
438     }
439
440     @Override
441     @SuppressWarnings("checkstyle:OverloadMethodsDeclarationOrder")
442     public final void deleteRoutes(final DOMDataTreeWriteTransaction tx, final YangInstanceIdentifier tablePath,
443             final ContainerNode nlri, final NodeIdentifier routesNodeId) {
444         final Optional<DataContainerChild<? extends PathArgument, ?>> maybeRoutes = nlri.getChild(WITHDRAWN_ROUTES);
445         if (maybeRoutes.isPresent()) {
446             final ContainerNode destination = getDestination(maybeRoutes.get(), destinationContainerIdentifier());
447             if (destination != null) {
448                 deleteDestinationRoutes(tx, tablePath, destination, routesNodeId);
449             }
450         } else {
451             LOG.debug("Withdrawn routes are not present in NLRI {}", nlri);
452         }
453     }
454
455     @Override
456     public final Collection<NodeIdentifierWithPredicates> putRoutes(final DOMDataTreeWriteTransaction tx,
457                                                              final YangInstanceIdentifier tablePath,
458                                                              final ContainerNode nlri,
459                                                              final ContainerNode attributes,
460                                                              final NodeIdentifier routesNodeId) {
461         final Optional<DataContainerChild<? extends PathArgument, ?>> maybeRoutes = nlri.getChild(ADVERTISED_ROUTES);
462         if (maybeRoutes.isPresent()) {
463             final ContainerNode destination = getDestination(maybeRoutes.get(), destinationContainerIdentifier());
464             if (destination != null) {
465                 return putDestinationRoutes(tx, tablePath, destination, attributes, routesNodeId);
466             }
467         } else {
468             LOG.debug("Advertized routes are not present in NLRI {}", nlri);
469         }
470         return Collections.emptyList();
471     }
472
473     private static final class DeleteRoute implements ApplyRoute {
474         @Override
475         public void apply(final DOMDataTreeWriteTransaction tx, final YangInstanceIdentifier base,
476                 final NodeIdentifierWithPredicates routeKey, final DataContainerNode<?> route,
477                 final ContainerNode attributes) {
478             tx.delete(LogicalDatastoreType.OPERATIONAL, base.node(routeKey));
479         }
480     }
481
482     private final class PutRoute implements ApplyRoute {
483         @Override
484         public void apply(final DOMDataTreeWriteTransaction tx, final YangInstanceIdentifier base,
485                 final NodeIdentifierWithPredicates routeKey, final DataContainerNode<?> route,
486                 final ContainerNode attributes) {
487             // Build the DataContainer data
488             final DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> b =
489                     ImmutableNodes.mapEntryBuilder();
490             b.withNodeIdentifier(routeKey);
491
492             route.getValue().forEach(b::withChild);
493             // Add attributes
494             final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> cb =
495                     Builders.containerBuilder(attributes);
496             cb.withNodeIdentifier(routeAttributesIdentifier());
497             b.withChild(cb.build());
498             tx.put(LogicalDatastoreType.OPERATIONAL, base.node(routeKey), b.build());
499         }
500     }
501
502     protected final NodeIdentifier routePathIdNid() {
503         return this.pathIdNid;
504     }
505
506     protected final ImmutableOffsetMapTemplate<QName> routeKeyTemplate() {
507         return this.routeKeyTemplate;
508     }
509
510     protected final String extractPrefix(final DataContainerNode<? extends PathArgument> route) {
511         return (String) route.getChild(prefixTypeNid).get().getValue();
512     }
513
514     protected final RouteDistinguisher extractRouteDistinguisher(
515             final DataContainerNode<? extends PathArgument> route) {
516         if (route.getChild(this.rdNid).isPresent()) {
517             return RouteDistinguisherBuilder.getDefaultInstance((String) route.getChild(this.rdNid).get().getValue());
518         }
519         return null;
520     }
521
522     protected final YangInstanceIdentifier routesYangInstanceIdentifier(final YangInstanceIdentifier routesTablePaths) {
523         return this.routesPath.getUnchecked(routesTablePaths);
524     }
525
526     @Override
527     public R fromNormalizedNode(final YangInstanceIdentifier routePath, final NormalizedNode<?, ?> normalizedNode) {
528         final DataObject node = this.mappingService.fromNormalizedNode(routePath, normalizedNode).getValue();
529         verify(node instanceof Route, "node %s is not a Route", node);
530         return (R) node;
531     }
532
533     @Override
534     public Attributes attributeFromContainerNode(final ContainerNode advertisedAttrs) {
535         final YangInstanceIdentifier path = this.routeDefaultYii.node(routeAttributesIdentifier());
536         return (Attributes) this.mappingService.fromNormalizedNode(path, advertisedAttrs).getValue();
537     }
538
539     @Override
540     public ContainerNode attributeToContainerNode(final YangInstanceIdentifier attPath, final Attributes attributes) {
541         final InstanceIdentifier<DataObject> iid = this.mappingService.fromYangInstanceIdentifier(attPath);
542         return (ContainerNode) this.mappingService.toNormalizedNode(iid, attributes).getValue();
543     }
544 }