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