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