c1d10ca41c98e84c03b9925869505074f315919b
[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 java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashSet;
23 import java.util.Set;
24 import javax.annotation.Nonnull;
25 import javax.annotation.Nullable;
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.common.api.data.TransactionChainListener;
30 import org.opendaylight.controller.md.sal.dom.api.ClusteredDOMDataTreeChangeListener;
31 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
32 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
33 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
34 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
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.BGPPeerStateImpl;
38 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl;
39 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
40 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
41 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
42 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryImportParameters;
43 import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState;
44 import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState;
45 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
46 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
47 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
48 import org.opendaylight.protocol.concepts.AbstractRegistration;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.SendReceive;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.ApplicationRibId;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerId;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerRole;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.Peer;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.PeerKey;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.peer.AdjRibIn;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.peer.AdjRibOut;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.Tables;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.TablesKey;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.ClusterIdentifier;
62 import org.opendaylight.yangtools.concepts.ListenerRegistration;
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  * This peer has it's own RIB, where it stores all user routes. This RIB is
79  * located in configurational datastore. Routes are added through RESTCONF.
80  *
81  * They are then processed as routes from any other peer, through AdjRib,
82  * EffectiveRib,LocRib and if they are advertised further, through AdjRibOut.
83  *
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 BGPPeerStateImpl implements org.opendaylight.protocol.bgp.rib.spi.Peer,
88         BGPRouteEntryImportParameters, ClusteredDOMDataTreeChangeListener, TransactionChainListener {
89
90     private static final Logger LOG = LoggerFactory.getLogger(ApplicationPeer.class);
91
92     private final byte[] rawIdentifier;
93     private final String name;
94     private final YangInstanceIdentifier adjRibsInId;
95     private final RIB rib;
96     private final InstanceIdentifier<AdjRibOut> peerRibOutIId;
97     private final KeyedInstanceIdentifier<Peer, PeerKey> peerIId;
98     private DOMTransactionChain chain;
99     private DOMTransactionChain writerChain;
100     private EffectiveRibInWriter effectiveRibInWriter;
101     private AdjRibInWriter adjRibInWriter;
102     private ListenerRegistration<ApplicationPeer> registration;
103     private final Set<NodeIdentifierWithPredicates> supportedTables = new HashSet<>();
104     private final BGPSessionStateImpl bgpSessionState = new BGPSessionStateImpl();
105     private final LoadingCache<TablesKey, KeyedInstanceIdentifier<Tables, TablesKey>> tablesIId
106             = CacheBuilder.newBuilder()
107             .build(new CacheLoader<TablesKey, KeyedInstanceIdentifier<Tables, TablesKey>>() {
108                 @Override
109                 public KeyedInstanceIdentifier<Tables, TablesKey> load(final TablesKey tablesKey) {
110                     return ApplicationPeer.this.peerRibOutIId.child(Tables.class, tablesKey);
111                 }
112             });
113     private final PeerId peerId;
114     private AbstractRegistration trackerRegistration;
115
116     @FunctionalInterface
117     interface RegisterAppPeerListener {
118         /**
119          * Register Application Peer Change Listener once AdjRibIn has been successfully initialized.
120          */
121         void register();
122     }
123
124     public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address ipAddress, final RIB rib) {
125         super(rib.getInstanceIdentifier(), "application-peers", new IpAddress(ipAddress),
126                 rib.getLocalTablesKeys(), Collections.emptySet());
127         this.name = applicationRibId.getValue();
128         final RIB targetRib = requireNonNull(rib);
129         this.rawIdentifier = InetAddresses.forString(ipAddress.getValue()).getAddress();
130         final NodeIdentifierWithPredicates peerIId = IdentifierUtils.domPeerId(RouterIds.createPeerId(ipAddress));
131         this.adjRibsInId = targetRib.getYangRibId().node(Peer.QNAME).node(peerIId)
132                 .node(AdjRibIn.QNAME).node(Tables.QNAME);
133         this.rib = targetRib;
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.rev171207.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         this.chain = this.rib.createPeerDOMChain(this);
144         this.writerChain = this.rib.createPeerDOMChain(this);
145
146         final Set<TablesKey> localTables = this.rib.getLocalTablesKeys();
147         localTables.forEach(tablesKey -> {
148             this.supportedTables.add(RibSupportUtils.toYangTablesKey(tablesKey));
149         });
150         setAdvertizedGracefulRestartTableTypes(Collections.emptyList());
151
152         this.adjRibInWriter = AdjRibInWriter.create(this.rib.getYangRibId(), PeerRole.Internal, this.writerChain);
153         final RIBSupportContextRegistry context = this.rib.getRibSupportContext();
154         final RegisterAppPeerListener registerAppPeerListener = () -> {
155             synchronized (this) {
156                 if (this.chain != null) {
157                     this.registration = dataTreeChangeService.registerDataTreeChangeListener(appPeerDOMId, this);
158                 }
159             }
160         };
161         this.adjRibInWriter = this.adjRibInWriter.transform(this.peerId, context, localTables, Collections.emptyMap(),
162                 registerAppPeerListener);
163         this.effectiveRibInWriter = EffectiveRibInWriter
164                 .create(this, this.rib, this.rib.createPeerChain(this), this.peerIId, localTables);
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 (this.chain == null) {
178             LOG.trace("Skipping data changed called to Application Peer. Change : {}", changes);
179             return;
180         }
181         final DOMDataWriteTransaction tx = this.chain.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                         LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
200                         tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
201                         break;
202                     case UNMODIFIED:
203                         // No-op
204                         break;
205                     case SUBTREE_MODIFIED:
206                         if (EffectiveRibInWriter.TABLE_ROUTES.equals(childIdentifier)) {
207                             processRoutesTable(child, tableId, tx, tableId);
208                             break;
209                         }
210                     case WRITE:
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.submit();
224     }
225
226     private synchronized void processRoutesTable(final DataTreeCandidateNode node,
227             final YangInstanceIdentifier identifier, final DOMDataWriteTransaction tx,
228             final YangInstanceIdentifier routeTableIdentifier) {
229         for (final DataTreeCandidateNode child : node.getChildNodes()) {
230             final YangInstanceIdentifier childIdentifier = identifier.node(child.getIdentifier());
231             switch (child.getModificationType()) {
232                 case DELETE:
233                     LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
234                     tx.delete(LogicalDatastoreType.OPERATIONAL, childIdentifier);
235                     break;
236                 case UNMODIFIED:
237                     // No-op
238                     break;
239                 case SUBTREE_MODIFIED:
240                     //For be ables to use DELETE when we remove specific routes as we do when we remove the whole routes,
241                     // we need to go deeper three levels
242                     if (!routeTableIdentifier.equals(childIdentifier.getParent().getParent().getParent())) {
243                         processRoutesTable(child, childIdentifier, tx, routeTableIdentifier);
244                         break;
245                     }
246                 case WRITE:
247                     if (child.getDataAfter().isPresent()) {
248                         final NormalizedNode<?, ?> dataAfter = child.getDataAfter().get();
249                         LOG.trace("App peer -> AdjRibsIn path : {}", childIdentifier);
250                         LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
251                         tx.put(LogicalDatastoreType.OPERATIONAL, childIdentifier, dataAfter);
252                     }
253                     break;
254                 default:
255                     break;
256             }
257         }
258     }
259
260     @Override
261     public String getName() {
262         return this.name;
263     }
264
265     // FIXME ListenableFuture<?> should be used once closeServiceInstance uses wildcard too
266     @Override
267     public synchronized ListenableFuture<Void> close() {
268         setActive(false);
269         if (this.registration != null) {
270             this.registration.close();
271             this.registration = null;
272         }
273         if (this.effectiveRibInWriter != null) {
274             this.effectiveRibInWriter.close();
275         }
276         final ListenableFuture<Void> future;
277         if (this.adjRibInWriter != null) {
278             future = this.adjRibInWriter.removePeer();
279         } else {
280             future = Futures.immediateFuture(null);
281         }
282         if (this.chain != null) {
283             this.chain.close();
284             this.chain = null;
285         }
286         if (this.writerChain != null) {
287             this.writerChain.close();
288             this.writerChain = null;
289         }
290         if (this.trackerRegistration != null) {
291             this.trackerRegistration.close();
292             this.trackerRegistration = null;
293         }
294         return future;
295     }
296
297     @Override
298     public byte[] getRawIdentifier() {
299         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
300     }
301
302     @Override
303     public PeerId getPeerId() {
304         return this.peerId;
305     }
306
307     @Override
308     public boolean supportsAddPathSupported(final TablesKey tableKey) {
309         return false;
310     }
311
312     @Override
313     public SendReceive getSupportedAddPathTables(final TablesKey tableKey) {
314         return null;
315     }
316
317     @Override
318     public boolean supportsTable(final TablesKey tableKey) {
319         return this.rib.supportsTable(tableKey);
320     }
321
322     @Override
323     public PeerRole getRole() {
324         return PeerRole.Internal;
325     }
326
327     @Override
328     public ClusterIdentifier getClusterId() {
329         return null;
330     }
331
332     @Override
333     public KeyedInstanceIdentifier<Tables, TablesKey> getRibOutIId(final TablesKey tablesKey) {
334         return this.tablesIId.getUnchecked(tablesKey);
335     }
336
337     @Override
338     public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
339         final AsyncTransaction<?, ?> transaction, final Throwable cause) {
340         LOG.error("Transaction chain {} failed.", transaction != null ? transaction.getIdentifier() : null, cause);
341     }
342
343     @Override
344     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
345         LOG.debug("Transaction chain {} successful.", chain);
346     }
347
348     @Override
349     public BGPErrorHandlingState getBGPErrorHandlingState() {
350         return this;
351     }
352
353     @Override
354     public BGPAfiSafiState getBGPAfiSafiState() {
355         return this;
356     }
357
358     @Override
359     public BGPSessionState getBGPSessionState() {
360         return this.bgpSessionState;
361     }
362
363     @Override
364     public BGPTimersState getBGPTimersState() {
365         return this.bgpSessionState;
366     }
367
368     @Override
369     public BGPTransportState getBGPTransportState() {
370         return this.bgpSessionState;
371     }
372
373
374     @Override
375     public PeerRole getFromPeerRole() {
376         return getRole();
377     }
378
379     @Override
380     public PeerId getFromPeerId() {
381         return getPeerId();
382     }
383
384     @Override
385     public ClusterIdentifier getFromClusterId() {
386         return getClusterId();
387     }
388 }