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