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