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