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