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