Bump upstreams
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / ApplicationPeer.java
1 /*
2  * Copyright (c) 2014 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 com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ADJRIBIN_NID;
13 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ADJRIBOUT_NID;
14 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.PEER_NID;
15 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ROUTES_NID;
16 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.TABLES_NID;
17
18 import com.google.common.cache.CacheBuilder;
19 import com.google.common.cache.CacheLoader;
20 import com.google.common.cache.LoadingCache;
21 import com.google.common.util.concurrent.FluentFuture;
22 import com.google.common.util.concurrent.FutureCallback;
23 import com.google.common.util.concurrent.MoreExecutors;
24 import java.util.ArrayList;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Set;
29 import org.opendaylight.mdsal.common.api.CommitInfo;
30 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
31 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
32 import org.opendaylight.mdsal.dom.api.DOMDataBroker.DataTreeChangeExtension;
33 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
34 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
35 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
36 import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
37 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
38 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
39 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl;
40 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
41 import org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers;
42 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
43 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
44 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
45 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressNoZone;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4AddressNoZone;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.SendReceive;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.ApplicationRibId;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerRole;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.RouteTarget;
53 import org.opendaylight.yangtools.concepts.Registration;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
57 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
58 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateNode;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 /**
63  * Application Peer is a special case of BGP peer. It serves as an interface
64  * for user to advertise user routes to ODL and through ODL to other BGP peers.
65  *
66  * <p>
67  * This peer has it's own RIB, where it stores all user routes. This RIB is
68  * located in configurational datastore. Routes are added through RESTCONF.
69  *
70  * <p>
71  * They are then processed as routes from any other peer, through AdjRib,
72  * EffectiveRib,LocRib and if they are advertised further, through AdjRibOut.
73  *
74  * <p>
75  * For purposed of import policies such as Best Path Selection, application
76  * peer needs to have a BGP-ID that is configurable.
77  */
78 public class ApplicationPeer extends AbstractPeer implements ClusteredDOMDataTreeChangeListener {
79     private static final Logger LOG = LoggerFactory.getLogger(ApplicationPeer.class);
80     private static final String APP_PEER_GROUP = "application-peers";
81
82     private final LoadingCache<NodeIdentifierWithPredicates, YangInstanceIdentifier> tablesIId =
83         CacheBuilder.newBuilder().build(new CacheLoader<NodeIdentifierWithPredicates, YangInstanceIdentifier>() {
84             @Override
85             public YangInstanceIdentifier load(final NodeIdentifierWithPredicates key) {
86                 return peerRibOutIId.node(RIBNodeIdentifiers.TABLES_NID).node(key);
87             }
88         });
89
90     private final YangInstanceIdentifier adjRibsInId;
91     private final YangInstanceIdentifier peerRibOutIId;
92     private final BGPTableTypeRegistryConsumer tableTypeRegistry;
93     private EffectiveRibInWriter effectiveRibInWriter;
94     private AdjRibInWriter adjRibInWriter;
95     private Registration registration;
96     private final Set<NodeIdentifierWithPredicates> supportedTables = new HashSet<>();
97     private final BGPSessionStateImpl bgpSessionState = new BGPSessionStateImpl();
98     private Registration trackerRegistration;
99     private YangInstanceIdentifier peerPath;
100
101     @Override
102     public List<RouteTarget> getMemberships() {
103         return List.of();
104     }
105
106     @FunctionalInterface
107     interface RegisterAppPeerListener {
108         /**
109          * Register Application Peer Change Listener once AdjRibIn has been successfully initialized.
110          */
111         void register();
112     }
113
114     public ApplicationPeer(
115             final BGPTableTypeRegistryConsumer tableTypeRegistry,
116             final ApplicationRibId applicationRibId, final Ipv4AddressNoZone ipAddress, final RIB rib) {
117         super(rib, applicationRibId.getValue(), APP_PEER_GROUP, PeerRole.Internal,
118                 new IpAddressNoZone(ipAddress), Set.of());
119         this.tableTypeRegistry = requireNonNull(tableTypeRegistry);
120         final RIB targetRib = requireNonNull(rib);
121         peerId = RouterIds.createPeerId(ipAddress);
122
123         final YangInstanceIdentifier peerRib = targetRib.getYangRibId().node(PEER_NID)
124             .node(IdentifierUtils.domPeerId(peerId));
125         adjRibsInId = peerRib.node(ADJRIBIN_NID).node(TABLES_NID).toOptimized();
126         peerRibOutIId = peerRib.node(ADJRIBOUT_NID).node(TABLES_NID).toOptimized();
127     }
128
129     public synchronized void instantiateServiceInstance(final DataTreeChangeExtension dataTreeChangeService,
130             final DOMDataTreeIdentifier appPeerDOMId) {
131         setActive(true);
132         final var localTables = rib.getLocalTablesKeys();
133         for (var localTable : localTables) {
134             final var tableSupport = rib.getRibSupportContext().getRIBSupport(localTable);
135             if (tableSupport != null) {
136                 supportedTables.add(tableSupport.tablesKey());
137             } else {
138                 LOG.warn("Ignoring unsupported table {}", localTable);
139             }
140         }
141         setAdvertizedGracefulRestartTableTypes(List.of());
142
143         createDomChain();
144         adjRibInWriter = AdjRibInWriter.create(rib.getYangRibId(), PeerRole.Internal, this);
145         final RIBSupportContextRegistry context = rib.getRibSupportContext();
146         final RegisterAppPeerListener registerAppPeerListener = () -> {
147             synchronized (this) {
148                 if (getDomChain() != null) {
149                     registration = dataTreeChangeService.registerTreeChangeListener(appPeerDOMId, this);
150                 }
151             }
152         };
153         peerPath = createPeerPath(peerId);
154         adjRibInWriter = adjRibInWriter.transform(peerId, peerPath, context, localTables,
155                 Map.of(), registerAppPeerListener);
156
157         final var chain = rib.createPeerDOMChain();
158         chain.addCallback(this);
159
160         effectiveRibInWriter = new EffectiveRibInWriter(this, rib, chain, peerPath, localTables, tableTypeRegistry,
161             new ArrayList<>(), rtCache);
162         effectiveRibInWriter.init();
163         bgpSessionState.registerMessagesCounter(this);
164         trackerRegistration = rib.getPeerTracker().registerPeer(this);
165     }
166
167     @Override
168     public void onInitialData() {
169         // FIXME: we really want to (under a synchronized block) to ensure adj-rib-in is completely empty here.
170         //        Unfortunately that bit is already being done somewhere else. The entire the tables are being created
171         //        elsewhere and therefore we need to reign in lifecycle first
172     }
173
174     /**
175      * Routes come from application RIB that is identified by (configurable) name.
176      * Each route is pushed into AdjRibsInWriter with it's whole context. In this
177      * method, it doesn't matter if the routes are removed or added, this will
178      * be determined in LocRib.
179      */
180     @Override
181     public synchronized void onDataTreeChanged(final List<DataTreeCandidate> changes) {
182         final DOMTransactionChain chain = getDomChain();
183         if (chain == null) {
184             LOG.trace("Skipping data changed called to Application Peer. Change : {}", changes);
185             return;
186         }
187         final DOMDataTreeWriteTransaction tx = chain.newWriteOnlyTransaction();
188         LOG.debug("Received data change to ApplicationRib {}", changes);
189         for (final DataTreeCandidate tc : changes) {
190             LOG.debug("Modification Type {}", tc.getRootNode().modificationType());
191             final YangInstanceIdentifier path = tc.getRootPath();
192             final PathArgument lastArg = path.getLastPathArgument();
193             verify(lastArg instanceof NodeIdentifierWithPredicates,
194                     "Unexpected type %s in path %s", lastArg.getClass(), path);
195             final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
196             if (!supportedTables.contains(tableKey)) {
197                 LOG.trace("Skipping received data change for non supported family {}.", tableKey);
198                 continue;
199             }
200             for (final DataTreeCandidateNode child : tc.getRootNode().childNodes()) {
201                 final PathArgument childIdentifier = child.name();
202                 final YangInstanceIdentifier tableId = adjRibsInId.node(tableKey).node(childIdentifier);
203                 switch (child.modificationType()) {
204                     case DELETE:
205                     case DISAPPEARED:
206                         LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
207                         tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
208                         break;
209                     case UNMODIFIED:
210                         // No-op
211                         break;
212                     case SUBTREE_MODIFIED:
213                         if (ROUTES_NID.equals(childIdentifier)) {
214                             processRoutesTable(child, tableId, tx, tableId);
215                         } else {
216                             processWrite(child, tableId, tx);
217                         }
218                         break;
219                     case WRITE:
220                     case APPEARED:
221                         processWrite(child, tableId, tx);
222                         break;
223                     default:
224                         break;
225                 }
226             }
227         }
228         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
229             @Override
230             public void onSuccess(final CommitInfo result) {
231                 LOG.trace("Successful commit");
232             }
233
234             @Override
235             public void onFailure(final Throwable trw) {
236                 LOG.error("Failed commit", trw);
237             }
238         }, MoreExecutors.directExecutor());
239     }
240
241     private static void processWrite(final DataTreeCandidateNode child, final YangInstanceIdentifier tableId,
242             final DOMDataTreeWriteTransaction tx) {
243         final var dataAfter = child.dataAfter();
244         if (dataAfter != null) {
245             LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
246             LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
247             tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
248         }
249     }
250
251     private synchronized void processRoutesTable(final DataTreeCandidateNode node,
252             final YangInstanceIdentifier identifier, final DOMDataTreeWriteTransaction tx,
253             final YangInstanceIdentifier routeTableIdentifier) {
254         for (var child : node.childNodes()) {
255             final YangInstanceIdentifier childIdentifier = identifier.node(child.name());
256             switch (child.modificationType()) {
257                 case DELETE:
258                     LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
259                     tx.delete(LogicalDatastoreType.OPERATIONAL, childIdentifier);
260                     break;
261                 case UNMODIFIED:
262                     // No-op
263                     break;
264                 case SUBTREE_MODIFIED:
265                     // For be ables to use DELETE when we remove specific routes as we do when we remove the whole
266                     // routes, we need to go deeper three levels
267                     if (!routeTableIdentifier.equals(childIdentifier.getParent().getParent().getParent())) {
268                         processRoutesTable(child, childIdentifier, tx, routeTableIdentifier);
269                     } else {
270                         processRouteWrite(child, childIdentifier, tx);
271                     }
272                     break;
273                 case WRITE:
274                     processRouteWrite(child, childIdentifier, tx);
275                     break;
276                 default:
277                     break;
278             }
279         }
280     }
281
282     private static void processRouteWrite(final DataTreeCandidateNode child,
283             final YangInstanceIdentifier childIdentifier, final DOMDataTreeWriteTransaction tx) {
284         final var dataAfter = child.dataAfter();
285         if (dataAfter != null) {
286             LOG.trace("App peer -> AdjRibsIn path : {}", childIdentifier);
287             LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
288             tx.put(LogicalDatastoreType.OPERATIONAL, childIdentifier, dataAfter);
289         }
290     }
291
292     @Override
293     public synchronized FluentFuture<? extends CommitInfo> close() {
294         setActive(false);
295         if (registration != null) {
296             registration.close();
297             registration = null;
298         }
299         if (adjRibInWriter != null) {
300             adjRibInWriter.releaseChain();
301         }
302         if (effectiveRibInWriter != null) {
303             effectiveRibInWriter.close();
304         }
305         final FluentFuture<? extends CommitInfo> future = removePeer(peerPath);
306         closeDomChain();
307         if (trackerRegistration != null) {
308             trackerRegistration.close();
309             trackerRegistration = null;
310         }
311         return future;
312     }
313
314     @Override
315     public boolean supportsAddPathSupported(final TablesKey tableKey) {
316         return false;
317     }
318
319     @Override
320     public SendReceive getSupportedAddPathTables(final TablesKey tableKey) {
321         return null;
322     }
323
324     @Override
325     public boolean supportsTable(final TablesKey tableKey) {
326         return rib.supportsTable(tableKey);
327     }
328
329     @Override
330     public YangInstanceIdentifier getRibOutIId(final NodeIdentifierWithPredicates tablekey) {
331         return tablesIId.getUnchecked(tablekey);
332     }
333
334     @Override
335     public void onFailure(final Throwable cause) {
336         LOG.error("Transaction chain failed.", cause);
337     }
338
339     @Override
340     public BGPSessionState getBGPSessionState() {
341         return bgpSessionState;
342     }
343
344     @Override
345     public BGPTimersState getBGPTimersState() {
346         return bgpSessionState;
347     }
348
349     @Override
350     public BGPTransportState getBGPTransportState() {
351         return bgpSessionState;
352     }
353 }