BUG-7222: Make BGP DS clean up asynchronous
[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 com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.net.InetAddresses;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.ListenableFuture;
15 import java.util.Arrays;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.HashSet;
19 import java.util.Optional;
20 import java.util.Set;
21 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
22 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
23 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
24 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
25 import org.opendaylight.controller.md.sal.dom.api.ClusteredDOMDataTreeChangeListener;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
29 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
30 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
31 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
32 import org.opendaylight.protocol.bgp.rib.impl.state.BGPPeerStateImpl;
33 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl;
34 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStats;
35 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStatsImpl;
36 import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker;
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.BGPAfiSafiState;
41 import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState;
42 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
43 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
44 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.ApplicationRibId;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.SimpleRoutingPolicy;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibIn;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
55 import org.opendaylight.yangtools.concepts.ListenerRegistration;
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 BGPPeerStateImpl implements org.opendaylight.protocol.bgp.rib.spi.Peer,
79     ClusteredDOMDataTreeChangeListener, TransactionChainListener {
80
81     private static final Logger LOG = LoggerFactory.getLogger(ApplicationPeer.class);
82
83     private final byte[] rawIdentifier;
84     private final String name;
85     private final YangInstanceIdentifier adjRibsInId;
86     private final Ipv4Address ipAddress;
87     private final RIB rib;
88     private final YangInstanceIdentifier peerIId;
89     private DOMTransactionChain chain;
90     private DOMTransactionChain writerChain;
91     private EffectiveRibInWriter effectiveRibInWriter;
92     private AdjRibInWriter adjRibInWriter;
93     private ListenerRegistration<ApplicationPeer> registration;
94     private final Set<NodeIdentifierWithPredicates> supportedTables = new HashSet<>();
95     private final BGPSessionStateImpl bgpSessionState = new BGPSessionStateImpl();
96
97     @FunctionalInterface
98     interface RegisterAppPeerListener {
99         /**
100          * Register Application Peer Change Listener once AdjRibIn has been successfully initialized.
101          */
102         void register();
103     }
104
105     public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address ipAddress, final RIB rib) {
106         super(rib.getInstanceIdentifier(), "application-peers", new IpAddress(ipAddress), rib.getLocalTablesKeys(),
107             Collections.emptySet());
108         this.name = applicationRibId.getValue();
109         final RIB targetRib = Preconditions.checkNotNull(rib);
110         this.rawIdentifier = InetAddresses.forString(ipAddress.getValue()).getAddress();
111         final NodeIdentifierWithPredicates peerId = IdentifierUtils.domPeerId(RouterIds.createPeerId(ipAddress));
112         this.peerIId = targetRib.getYangRibId().node(Peer.QNAME).node(peerId);
113         this.adjRibsInId = this.peerIId.node(AdjRibIn.QNAME).node(Tables.QNAME);
114         this.rib = targetRib;
115         this.ipAddress = ipAddress;
116     }
117
118     public synchronized void instantiateServiceInstance(final DOMDataTreeChangeService dataTreeChangeService,
119         final DOMDataTreeIdentifier appPeerDOMId) {
120         this.chain = this.rib.createPeerChain(this);
121         this.writerChain = this.rib.createPeerChain(this);
122
123         final Optional<SimpleRoutingPolicy> simpleRoutingPolicy = Optional.of(SimpleRoutingPolicy.AnnounceNone);
124         final PeerId peerId = RouterIds.createPeerId(this.ipAddress);
125         final Set<TablesKey> localTables = this.rib.getLocalTablesKeys();
126         localTables.forEach(tablesKey -> {
127             final ExportPolicyPeerTracker exportTracker = this.rib.getExportPolicyPeerTracker(tablesKey);
128             if (exportTracker != null) {
129                 exportTracker.registerPeer(peerId, null, this.peerIId, PeerRole.Internal, simpleRoutingPolicy);
130             }
131             this.supportedTables.add(RibSupportUtils.toYangTablesKey(tablesKey));
132         });
133         setAdvertizedGracefulRestartTableTypes(Collections.emptyList());
134
135         this.adjRibInWriter = AdjRibInWriter.create(this.rib.getYangRibId(), PeerRole.Internal, simpleRoutingPolicy, this.writerChain);
136         final RIBSupportContextRegistry context = this.rib.getRibSupportContext();
137         final RegisterAppPeerListener registerAppPeerListener = () -> {
138             synchronized (this) {
139                 if(this.chain != null) {
140                     this.registration = dataTreeChangeService.registerDataTreeChangeListener(appPeerDOMId, this);
141                 }
142             }
143         };
144         this.adjRibInWriter = this.adjRibInWriter.transform(peerId, context, localTables, Collections.emptyMap(),
145             registerAppPeerListener);
146         final BGPPeerStats peerStats = new BGPPeerStatsImpl(this.name, localTables, this);
147         this.effectiveRibInWriter = EffectiveRibInWriter.create(this.rib.getService(), this.rib.createPeerChain(this), this.peerIId,
148             this.rib.getImportPolicyPeerTracker(), context, PeerRole.Internal,
149             peerStats.getAdjRibInRouteCounters(), localTables);
150         this.bgpSessionState.registerMessagesCounter(this);
151     }
152
153     /**
154      * Routes come from application RIB that is identified by (configurable) name.
155      * Each route is pushed into AdjRibsInWriter with it's whole context. In this
156      * method, it doesn't matter if the routes are removed or added, this will
157      * be determined in LocRib.
158      */
159     @Override
160     public synchronized void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
161         if(this.chain == null) {
162             LOG.trace("Skipping data changed called to Application Peer. Change : {}", changes);
163             return;
164         }
165         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
166         LOG.debug("Received data change to ApplicationRib {}", changes);
167         for (final DataTreeCandidate tc : changes) {
168             LOG.debug("Modification Type {}", tc.getRootNode().getModificationType());
169             final YangInstanceIdentifier path = tc.getRootPath();
170             final PathArgument lastArg = path.getLastPathArgument();
171             Verify.verify(lastArg instanceof NodeIdentifierWithPredicates, "Unexpected type %s in path %s", lastArg.getClass(), path);
172             final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
173             if (!this.supportedTables.contains(tableKey)) {
174                 LOG.trace("Skipping received data change for non supported family {}.", tableKey);
175                 continue;
176             }
177             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
178                 final PathArgument childIdentifier = child.getIdentifier();
179                 final YangInstanceIdentifier tableId = this.adjRibsInId.node(tableKey).node(childIdentifier);
180                 switch (child.getModificationType()) {
181                 case DELETE:
182                     LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
183                     tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
184                     break;
185                 case UNMODIFIED:
186                     // No-op
187                     break;
188                 case SUBTREE_MODIFIED:
189                     if (EffectiveRibInWriter.TABLE_ROUTES.equals(childIdentifier)) {
190                         processRoutesTable(child, tableId, tx, tableId);
191                         break;
192                     }
193                 case WRITE:
194                     if (child.getDataAfter().isPresent()) {
195                         final NormalizedNode<?,?> dataAfter = child.getDataAfter().get();
196                         LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
197                         LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
198                         tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
199                     }
200                     break;
201                 default:
202                     break;
203                 }
204             }
205         }
206         tx.submit();
207     }
208
209     /**
210      * Applies modification under table routes based on modification type instead of only put. BUG 4438
211      * @param node
212      * @param identifier
213      * @param tx
214      * @param routeTableIdentifier
215      */
216     private synchronized void processRoutesTable(final DataTreeCandidateNode node, final YangInstanceIdentifier identifier,
217             final DOMDataWriteTransaction tx, final YangInstanceIdentifier routeTableIdentifier) {
218         for (final DataTreeCandidateNode child : node.getChildNodes()) {
219             final YangInstanceIdentifier childIdentifier = identifier.node(child.getIdentifier());
220             switch (child.getModificationType()) {
221             case DELETE:
222                 LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
223                 tx.delete(LogicalDatastoreType.OPERATIONAL, childIdentifier);
224                 break;
225             case UNMODIFIED:
226                 // No-op
227                 break;
228             case SUBTREE_MODIFIED:
229                 //For be ables to use DELETE when we remove specific routes as we do when we remove the whole routes,
230                 // we need to go deeper three levels
231                 if (!routeTableIdentifier.equals(childIdentifier.getParent().getParent().getParent())) {
232                     processRoutesTable(child, childIdentifier, tx, routeTableIdentifier);
233                     break;
234                 }
235             case WRITE:
236                 if (child.getDataAfter().isPresent()) {
237                     final NormalizedNode<?,?> dataAfter = child.getDataAfter().get();
238                     LOG.trace("App peer -> AdjRibsIn path : {}", childIdentifier);
239                     LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
240                     tx.put(LogicalDatastoreType.OPERATIONAL, childIdentifier, dataAfter);
241                 }
242                 break;
243             default:
244                 break;
245             }
246         }
247     }
248
249     @Override
250     public String getName() {
251         return this.name;
252     }
253
254     // FIXME ListenableFuture<?> should be used once closeServiceInstance uses wildcard too
255     @Override
256     public synchronized ListenableFuture<Void> close() {
257         if (this.registration != null) {
258             this.registration.close();
259             this.registration = null;
260         }
261         if (this.effectiveRibInWriter != null) {
262             this.effectiveRibInWriter.close();
263         }
264         final ListenableFuture<Void> future;
265         if (this.adjRibInWriter != null) {
266             future = this.adjRibInWriter.removePeer();
267         }else {
268             future = Futures.immediateFuture(null);
269         }
270         if (this.chain != null) {
271             this.chain.close();
272             this.chain = null;
273         }
274         if (this.writerChain != null) {
275             this.writerChain.close();
276             this.writerChain = null;
277         }
278         return future;
279     }
280
281     @Override
282     public byte[] getRawIdentifier() {
283         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
284     }
285
286     @Override
287     public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
288         final AsyncTransaction<?, ?> transaction, final Throwable cause) {
289         LOG.error("Transaction chain {} failed.", transaction != null ? transaction.getIdentifier() : null, cause);
290     }
291
292     @Override
293     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
294         LOG.debug("Transaction chain {} successful.", chain);
295     }
296
297     @Override
298     public BGPErrorHandlingState getBGPErrorHandlingState() {
299         return this;
300     }
301
302     @Override
303     public BGPAfiSafiState getBGPAfiSafiState() {
304         return this;
305     }
306
307     @Override
308     public BGPSessionState getBGPSessionState() {
309         return this.bgpSessionState;
310     }
311
312     @Override
313     public BGPTimersState getBGPTimersState() {
314         return this.bgpSessionState;
315     }
316
317     @Override
318     public BGPTransportState getBGPTransportState() {
319         return this.bgpSessionState;
320     }
321 }