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