a3e4dcf6830980ad462bf35424286f179cd01c05
[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.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
48 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
50 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
52 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
53 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 /**
58  * Instantiated for each peer and table, listens on a particular peer's adj-rib-out, performs transcoding to BA form
59  * (message) and sends it down the channel. This class is NOT thread-safe.
60  */
61 final class AdjRibOutListener implements ClusteredDOMDataTreeChangeListener, PrefixesSentCounters {
62
63     private static final Logger LOG = LoggerFactory.getLogger(AdjRibOutListener.class);
64
65     private static final QName PREFIX_QNAME = QName.create(Ipv4Route.QNAME, "prefix").intern();
66     private static final QName PATHID_QNAME = QName.create(Ipv4Route.QNAME, "path-id").intern();
67     private final YangInstanceIdentifier.NodeIdentifier routeKeyPrefixLeaf = new YangInstanceIdentifier
68             .NodeIdentifier(PREFIX_QNAME);
69     private final YangInstanceIdentifier.NodeIdentifier routeKeyPathIdLeaf = new YangInstanceIdentifier
70             .NodeIdentifier(PATHID_QNAME);
71
72     private final ChannelOutputLimiter session;
73     private final Codecs codecs;
74     private final RIBSupport<?, ?, ?, ?> support;
75     private final boolean mpSupport;
76     private final ListenerRegistration<AdjRibOutListener> registerDataTreeChangeListener;
77     private final LongAdder prefixesSentCounter = new LongAdder();
78     private final TablesKey tablesKey;
79     private boolean initalState;
80
81     private AdjRibOutListener(final PeerId peerId, final TablesKey tablesKey, final YangInstanceIdentifier ribId,
82             final CodecsRegistry registry, final RIBSupport<?, ?, ?, ?> support, final DOMDataTreeChangeService service,
83             final ChannelOutputLimiter session, final boolean mpSupport) {
84         this.session = requireNonNull(session);
85         this.support = requireNonNull(support);
86         this.codecs = registry.getCodecs(this.support);
87         this.mpSupport = mpSupport;
88         this.tablesKey = requireNonNull(tablesKey);
89         final YangInstanceIdentifier adjRibOutId = ribId.node(PEER_NID).node(IdentifierUtils.domPeerId(peerId))
90                 .node(ADJRIBOUT_NID).node(TABLES_NID).node(RibSupportUtils.toYangTablesKey(tablesKey));
91         /*
92          *  After listener registration should always be executed ODTC. Even when empty table is present
93          *  in data store. Within this first ODTC execution we should advertise present routes and than
94          *  send EOR marker. initialState flag is distinguishing between first ODTC execution and the rest.
95          */
96         this.initalState = true;
97         this.registerDataTreeChangeListener = service.registerDataTreeChangeListener(
98                 new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, adjRibOutId), this);
99     }
100
101     static AdjRibOutListener create(
102             final @NonNull PeerId peerId,
103             final @NonNull TablesKey tablesKey,
104             final @NonNull YangInstanceIdentifier ribId,
105             final @NonNull CodecsRegistry registry,
106             final @NonNull RIBSupport<?, ?, ?, ?> support,
107             final @NonNull DOMDataTreeChangeService service,
108             final @NonNull ChannelOutputLimiter session,
109             final boolean mpSupport) {
110         return new AdjRibOutListener(peerId, tablesKey, ribId, registry, support, service, session, mpSupport);
111     }
112
113     @Override
114     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
115         LOG.debug("Data change received for AdjRibOut {}", changes);
116         for (final DataTreeCandidate tc : changes) {
117             LOG.trace("Change {} type {}", tc.getRootNode(), tc.getRootNode().getModificationType());
118             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
119                 processSupportedFamilyRoutes(child);
120             }
121         }
122         if (initalState) {
123             final Update endOfRib = BgpPeerUtil.createEndOfRib(this.tablesKey);
124             this.session.write(endOfRib);
125             this.initalState = false;
126         }
127         this.session.flush();
128     }
129
130     private void processSupportedFamilyRoutes(final DataTreeCandidateNode child) {
131         final Collection<DataTreeCandidateNode> changedRoutes = this.support.changedRoutes(child);
132         for (final DataTreeCandidateNode route : changedRoutes) {
133             processRouteChange(route);
134         }
135     }
136
137     private void processRouteChange(final DataTreeCandidateNode route) {
138         final Update update;
139         switch (route.getModificationType()) {
140             case UNMODIFIED:
141                 LOG.debug("Skipping unmodified route {}", route.getIdentifier());
142                 return;
143             case DELETE:
144             case DISAPPEARED:
145                 // FIXME: we can batch deletions into a single batch
146                 update = withdraw((MapEntryNode) route.getDataBefore().get());
147                 LOG.debug("Withdrawing routes {}", update);
148                 break;
149             case APPEARED:
150             case SUBTREE_MODIFIED:
151             case WRITE:
152                 update = advertise((MapEntryNode) route.getDataAfter().get());
153                 LOG.debug("Advertising routes {}", update);
154                 break;
155             default:
156                 LOG.warn("Ignoring unhandled modification type {}", route.getModificationType());
157                 return;
158         }
159         this.session.write(update);
160     }
161
162     private Attributes routeAttributes(final MapEntryNode route) {
163         if (LOG.isDebugEnabled()) {
164             LOG.debug("AdjRibOut parsing route {}", NormalizedNodes.toStringTree(route));
165         }
166         final ContainerNode advertisedAttrs = (ContainerNode) NormalizedNodes.findNode(route,
167                 this.support.routeAttributesIdentifier()).orElse(null);
168         return this.codecs.deserializeAttributes(advertisedAttrs);
169     }
170
171     private Update withdraw(final MapEntryNode route) {
172         if (!this.mpSupport) {
173             return buildUpdate(Collections.emptyList(), Collections.singleton(route), routeAttributes(route));
174         }
175         return this.support.buildUpdate(Collections.emptyList(), Collections.singleton(route), routeAttributes(route));
176     }
177
178     private Update advertise(final MapEntryNode route) {
179         this.prefixesSentCounter.increment();
180         if (!this.mpSupport) {
181             return buildUpdate(Collections.singleton(route), Collections.emptyList(), routeAttributes(route));
182         }
183         return this.support.buildUpdate(Collections.singleton(route), Collections.emptyList(), routeAttributes(route));
184     }
185
186     private Update buildUpdate(
187             final @NonNull Collection<MapEntryNode> advertised,
188             final @NonNull Collection<MapEntryNode> withdrawn,
189             final @NonNull Attributes attr) {
190         final UpdateBuilder ub = new UpdateBuilder().setWithdrawnRoutes(extractWithdrawnRoutes(withdrawn))
191                 .setNlri(extractNlris(advertised));
192         ub.setAttributes(attr);
193         return ub.build();
194     }
195
196     private List<Nlri> extractNlris(final Collection<MapEntryNode> routes) {
197         return routes.stream().map(ipv4Route -> new NlriBuilder().setPrefix(new Ipv4Prefix(extractPrefix(ipv4Route)))
198                 .setPathId(extractPathId(ipv4Route)).build()).collect(Collectors.toList());
199     }
200
201     private List<WithdrawnRoutes> extractWithdrawnRoutes(final Collection<MapEntryNode> routes) {
202         return routes.stream().map(ipv4Route -> new WithdrawnRoutesBuilder()
203                 .setPrefix(new Ipv4Prefix(extractPrefix(ipv4Route))).setPathId(extractPathId(ipv4Route)).build())
204                 .collect(Collectors.toList());
205     }
206
207     private String extractPrefix(final MapEntryNode ipv4Route) {
208         return (String) ipv4Route.getChild(this.routeKeyPrefixLeaf).get().getValue();
209     }
210
211     private PathId extractPathId(final MapEntryNode ipv4Route) {
212         final Optional<DataContainerChild<? extends PathArgument, ?>> pathId = ipv4Route
213                 .getChild(this.routeKeyPathIdLeaf);
214         return pathId.map(dataContainerChild -> new PathId((Long) dataContainerChild.getValue())).orElse(null);
215     }
216
217     public void close() {
218         this.registerDataTreeChangeListener.close();
219     }
220
221     boolean isMpSupported() {
222         return this.mpSupport;
223     }
224
225     @Override
226     public long getPrefixesSentCount() {
227         return this.prefixesSentCounter.longValue();
228     }
229 }