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