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