Fix LeafNode conversions
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / AdjRibOutListener.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.bgp.rib.impl;
9
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ADJRIBOUT_NID;
12 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.PEER_NID;
13 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.TABLES_NID;
14
15 import java.util.Collection;
16 import java.util.Collections;
17 import java.util.List;
18 import java.util.Optional;
19 import java.util.concurrent.atomic.LongAdder;
20 import java.util.stream.Collectors;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
23 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
24 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
25 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
26 import org.opendaylight.protocol.bgp.rib.impl.spi.Codecs;
27 import org.opendaylight.protocol.bgp.rib.impl.spi.CodecsRegistry;
28 import org.opendaylight.protocol.bgp.rib.impl.state.peer.PrefixesSentCounters;
29 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
30 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
31 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Prefix;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.inet.rev180329.ipv4.routes.ipv4.routes.Ipv4Route;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.PathId;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Update;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.UpdateBuilder;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.path.attributes.Attributes;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.update.message.Nlri;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.update.message.NlriBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.update.message.WithdrawnRoutes;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.update.message.WithdrawnRoutesBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerId;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
44 import org.opendaylight.yangtools.concepts.ListenerRegistration;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.common.Uint32;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
49 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
51 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
53 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
54 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * Instantiated for each peer and table, listens on a particular peer's adj-rib-out, performs transcoding to BA form
60  * (message) and sends it down the channel. This class is NOT thread-safe.
61  */
62 final class AdjRibOutListener implements ClusteredDOMDataTreeChangeListener, PrefixesSentCounters {
63
64     private static final Logger LOG = LoggerFactory.getLogger(AdjRibOutListener.class);
65
66     private static final QName PREFIX_QNAME = QName.create(Ipv4Route.QNAME, "prefix").intern();
67     private static final QName PATHID_QNAME = QName.create(Ipv4Route.QNAME, "path-id").intern();
68     private final YangInstanceIdentifier.NodeIdentifier routeKeyPrefixLeaf = new YangInstanceIdentifier
69             .NodeIdentifier(PREFIX_QNAME);
70     private final YangInstanceIdentifier.NodeIdentifier routeKeyPathIdLeaf = new YangInstanceIdentifier
71             .NodeIdentifier(PATHID_QNAME);
72
73     private final ChannelOutputLimiter session;
74     private final Codecs codecs;
75     private final RIBSupport<?, ?, ?, ?> support;
76     private final boolean mpSupport;
77     private final ListenerRegistration<AdjRibOutListener> registerDataTreeChangeListener;
78     private final LongAdder prefixesSentCounter = new LongAdder();
79     private final TablesKey tablesKey;
80     private boolean initalState;
81
82     private AdjRibOutListener(final PeerId peerId, final TablesKey tablesKey, final YangInstanceIdentifier ribId,
83             final CodecsRegistry registry, final RIBSupport<?, ?, ?, ?> support, final DOMDataTreeChangeService service,
84             final ChannelOutputLimiter session, final boolean mpSupport) {
85         this.session = requireNonNull(session);
86         this.support = requireNonNull(support);
87         this.codecs = registry.getCodecs(this.support);
88         this.mpSupport = mpSupport;
89         this.tablesKey = requireNonNull(tablesKey);
90         final YangInstanceIdentifier adjRibOutId = ribId.node(PEER_NID).node(IdentifierUtils.domPeerId(peerId))
91                 .node(ADJRIBOUT_NID).node(TABLES_NID).node(RibSupportUtils.toYangTablesKey(tablesKey));
92         /*
93          *  After listener registration should always be executed ODTC. Even when empty table is present
94          *  in data store. Within this first ODTC execution we should advertise present routes and than
95          *  send EOR marker. initialState flag is distinguishing between first ODTC execution and the rest.
96          */
97         this.initalState = true;
98         this.registerDataTreeChangeListener = service.registerDataTreeChangeListener(
99                 new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, adjRibOutId), this);
100     }
101
102     static AdjRibOutListener create(
103             final @NonNull PeerId peerId,
104             final @NonNull TablesKey tablesKey,
105             final @NonNull YangInstanceIdentifier ribId,
106             final @NonNull CodecsRegistry registry,
107             final @NonNull RIBSupport<?, ?, ?, ?> support,
108             final @NonNull DOMDataTreeChangeService service,
109             final @NonNull ChannelOutputLimiter session,
110             final boolean mpSupport) {
111         return new AdjRibOutListener(peerId, tablesKey, ribId, registry, support, service, session, mpSupport);
112     }
113
114     @Override
115     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
116         LOG.debug("Data change received for AdjRibOut {}", changes);
117         for (final DataTreeCandidate tc : changes) {
118             LOG.trace("Change {} type {}", tc.getRootNode(), tc.getRootNode().getModificationType());
119             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
120                 processSupportedFamilyRoutes(child);
121             }
122         }
123         if (initalState) {
124             final Update endOfRib = BgpPeerUtil.createEndOfRib(this.tablesKey);
125             this.session.write(endOfRib);
126             this.initalState = false;
127         }
128         this.session.flush();
129     }
130
131     private void processSupportedFamilyRoutes(final DataTreeCandidateNode child) {
132         final Collection<DataTreeCandidateNode> changedRoutes = this.support.changedRoutes(child);
133         for (final DataTreeCandidateNode route : changedRoutes) {
134             processRouteChange(route);
135         }
136     }
137
138     private void processRouteChange(final DataTreeCandidateNode route) {
139         final Update update;
140         switch (route.getModificationType()) {
141             case UNMODIFIED:
142                 LOG.debug("Skipping unmodified route {}", route.getIdentifier());
143                 return;
144             case DELETE:
145             case DISAPPEARED:
146                 // FIXME: we can batch deletions into a single batch
147                 update = withdraw((MapEntryNode) route.getDataBefore().get());
148                 LOG.debug("Withdrawing routes {}", update);
149                 break;
150             case APPEARED:
151             case SUBTREE_MODIFIED:
152             case WRITE:
153                 update = advertise((MapEntryNode) route.getDataAfter().get());
154                 LOG.debug("Advertising routes {}", update);
155                 break;
156             default:
157                 LOG.warn("Ignoring unhandled modification type {}", route.getModificationType());
158                 return;
159         }
160         this.session.write(update);
161     }
162
163     private Attributes routeAttributes(final MapEntryNode route) {
164         if (LOG.isDebugEnabled()) {
165             LOG.debug("AdjRibOut parsing route {}", NormalizedNodes.toStringTree(route));
166         }
167         final ContainerNode advertisedAttrs = (ContainerNode) NormalizedNodes.findNode(route,
168                 this.support.routeAttributesIdentifier()).orElse(null);
169         return this.codecs.deserializeAttributes(advertisedAttrs);
170     }
171
172     private Update withdraw(final MapEntryNode route) {
173         if (!this.mpSupport) {
174             return buildUpdate(Collections.emptyList(), Collections.singleton(route), routeAttributes(route));
175         }
176         return this.support.buildUpdate(Collections.emptyList(), Collections.singleton(route), routeAttributes(route));
177     }
178
179     private Update advertise(final MapEntryNode route) {
180         this.prefixesSentCounter.increment();
181         if (!this.mpSupport) {
182             return buildUpdate(Collections.singleton(route), Collections.emptyList(), routeAttributes(route));
183         }
184         return this.support.buildUpdate(Collections.singleton(route), Collections.emptyList(), routeAttributes(route));
185     }
186
187     private Update buildUpdate(
188             final @NonNull Collection<MapEntryNode> advertised,
189             final @NonNull Collection<MapEntryNode> withdrawn,
190             final @NonNull Attributes attr) {
191         final UpdateBuilder ub = new UpdateBuilder().setWithdrawnRoutes(extractWithdrawnRoutes(withdrawn))
192                 .setNlri(extractNlris(advertised));
193         ub.setAttributes(attr);
194         return ub.build();
195     }
196
197     private List<Nlri> extractNlris(final Collection<MapEntryNode> routes) {
198         return routes.stream().map(ipv4Route -> new NlriBuilder().setPrefix(new Ipv4Prefix(extractPrefix(ipv4Route)))
199                 .setPathId(extractPathId(ipv4Route)).build()).collect(Collectors.toList());
200     }
201
202     private List<WithdrawnRoutes> extractWithdrawnRoutes(final Collection<MapEntryNode> routes) {
203         return routes.stream().map(ipv4Route -> new WithdrawnRoutesBuilder()
204                 .setPrefix(new Ipv4Prefix(extractPrefix(ipv4Route))).setPathId(extractPathId(ipv4Route)).build())
205                 .collect(Collectors.toList());
206     }
207
208     private String extractPrefix(final MapEntryNode ipv4Route) {
209         return (String) ipv4Route.getChild(this.routeKeyPrefixLeaf).get().getValue();
210     }
211
212     private PathId extractPathId(final MapEntryNode ipv4Route) {
213         final Optional<DataContainerChild<? extends PathArgument, ?>> pathId = ipv4Route
214                 .getChild(this.routeKeyPathIdLeaf);
215         return pathId.map(dataContainerChild -> new PathId((Uint32) dataContainerChild.getValue())).orElse(null);
216     }
217
218     public void close() {
219         this.registerDataTreeChangeListener.close();
220     }
221
222     boolean isMpSupported() {
223         return this.mpSupport;
224     }
225
226     @Override
227     public long getPrefixesSentCount() {
228         return this.prefixesSentCounter.longValue();
229     }
230 }