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