BGPCEP-754: Rework EffectiveRibInWriter
[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.net.InetAddresses;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.HashSet;
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.spi.ExportPolicyPeerTracker;
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.policy.BGPRouteEntryImportParameters;
39 import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState;
40 import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState;
41 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
42 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
43 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
44 import org.opendaylight.protocol.concepts.AbstractRegistration;
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.multiprotocol.rev171207.SendReceive;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.ApplicationRibId;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerId;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerRole;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.Peer;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.PeerKey;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.peer.AdjRibIn;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.Tables;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.TablesKey;
56 import org.opendaylight.yangtools.concepts.ListenerRegistration;
57 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
63 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 /**
68  * Application Peer is a special case of BGP peer. It serves as an interface
69  * for user to advertise user routes to ODL and through ODL to other BGP peers.
70  *
71  * This peer has it's own RIB, where it stores all user routes. This RIB is
72  * located in configurational datastore. Routes are added through RESTCONF.
73  *
74  * They are then processed as routes from any other peer, through AdjRib,
75  * EffectiveRib,LocRib and if they are advertised further, through AdjRibOut.
76  *
77  * For purposed of import policies such as Best Path Selection, application
78  * peer needs to have a BGP-ID that is configurable.
79  */
80 public class ApplicationPeer extends BGPPeerStateImpl implements org.opendaylight.protocol.bgp.rib.spi.Peer,
81         BGPRouteEntryImportParameters, ClusteredDOMDataTreeChangeListener, TransactionChainListener {
82
83     private static final Logger LOG = LoggerFactory.getLogger(ApplicationPeer.class);
84
85     private final byte[] rawIdentifier;
86     private final String name;
87     private final YangInstanceIdentifier adjRibsInId;
88     private final Ipv4Address ipAddress;
89     private final RIB rib;
90     private final KeyedInstanceIdentifier<Peer, PeerKey> peerIId;
91     private final YangInstanceIdentifier peerYIId;
92     private DOMTransactionChain chain;
93     private DOMTransactionChain writerChain;
94     private EffectiveRibInWriter effectiveRibInWriter;
95     private AdjRibInWriter adjRibInWriter;
96     private ListenerRegistration<ApplicationPeer> registration;
97     private final Set<NodeIdentifierWithPredicates> supportedTables = new HashSet<>();
98     private final BGPSessionStateImpl bgpSessionState = new BGPSessionStateImpl();
99     private final PeerId peerId;
100     private AbstractRegistration trackerRegistration;
101
102     @FunctionalInterface
103     interface RegisterAppPeerListener {
104         /**
105          * Register Application Peer Change Listener once AdjRibIn has been successfully initialized.
106          */
107         void register();
108     }
109
110     public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address ipAddress, final RIB rib) {
111         super(rib.getInstanceIdentifier(), "application-peers", new IpAddress(ipAddress),
112                 rib.getLocalTablesKeys(), Collections.emptySet());
113         this.name = applicationRibId.getValue();
114         final RIB targetRib = requireNonNull(rib);
115         this.rawIdentifier = InetAddresses.forString(ipAddress.getValue()).getAddress();
116         final NodeIdentifierWithPredicates peerIId = IdentifierUtils.domPeerId(RouterIds.createPeerId(ipAddress));
117         this.peerYIId = targetRib.getYangRibId().node(Peer.QNAME).node(peerIId);
118         this.adjRibsInId = this.peerYIId.node(AdjRibIn.QNAME).node(Tables.QNAME);
119         this.rib = targetRib;
120         this.ipAddress = ipAddress;
121         this.peerId = RouterIds.createPeerId(ipAddress);
122         this.peerIId = getInstanceIdentifier().child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns
123                 .yang.bgp.rib.rev171207.bgp.rib.rib.Peer.class, new PeerKey(this.peerId));
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             final ExportPolicyPeerTracker exportTracker = this.rib.getExportPolicyPeerTracker(tablesKey);
135             if (exportTracker != null) {
136                 exportTracker.registerPeer(this.peerId, null, this.peerYIId, PeerRole.Internal);
137             }
138             this.supportedTables.add(RibSupportUtils.toYangTablesKey(tablesKey));
139         });
140         setAdvertizedGracefulRestartTableTypes(Collections.emptyList());
141
142         this.adjRibInWriter = AdjRibInWriter.create(this.rib.getYangRibId(), PeerRole.Internal, this.writerChain);
143         final RIBSupportContextRegistry context = this.rib.getRibSupportContext();
144         final RegisterAppPeerListener registerAppPeerListener = () -> {
145             synchronized (this) {
146                 if (this.chain != null) {
147                     this.registration = dataTreeChangeService.registerDataTreeChangeListener(appPeerDOMId, this);
148                 }
149             }
150         };
151         this.adjRibInWriter = this.adjRibInWriter.transform(this.peerId, context, localTables, Collections.emptyMap(),
152                 registerAppPeerListener);
153         this.effectiveRibInWriter = EffectiveRibInWriter
154                 .create(this, this.rib, this.rib.createPeerChain(this), this.peerIId, localTables);
155         this.bgpSessionState.registerMessagesCounter(this);
156         this.trackerRegistration = this.rib.getPeerTracker().registerPeer(this);
157     }
158
159     /**
160      * Routes come from application RIB that is identified by (configurable) name.
161      * Each route is pushed into AdjRibsInWriter with it's whole context. In this
162      * method, it doesn't matter if the routes are removed or added, this will
163      * be determined in LocRib.
164      */
165     @Override
166     public synchronized void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
167         if (this.chain == null) {
168             LOG.trace("Skipping data changed called to Application Peer. Change : {}", changes);
169             return;
170         }
171         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
172         LOG.debug("Received data change to ApplicationRib {}", changes);
173         for (final DataTreeCandidate tc : changes) {
174             LOG.debug("Modification Type {}", tc.getRootNode().getModificationType());
175             final YangInstanceIdentifier path = tc.getRootPath();
176             final PathArgument lastArg = path.getLastPathArgument();
177             Verify.verify(lastArg instanceof NodeIdentifierWithPredicates,
178                     "Unexpected type %s in path %s", lastArg.getClass(), path);
179             final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
180             if (!this.supportedTables.contains(tableKey)) {
181                 LOG.trace("Skipping received data change for non supported family {}.", tableKey);
182                 continue;
183             }
184             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
185                 final PathArgument childIdentifier = child.getIdentifier();
186                 final YangInstanceIdentifier tableId = this.adjRibsInId.node(tableKey).node(childIdentifier);
187                 switch (child.getModificationType()) {
188                     case DELETE:
189                         LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
190                         tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
191                         break;
192                     case UNMODIFIED:
193                         // No-op
194                         break;
195                     case SUBTREE_MODIFIED:
196                         if (EffectiveRibInWriter.TABLE_ROUTES.equals(childIdentifier)) {
197                             processRoutesTable(child, tableId, tx, tableId);
198                             break;
199                         }
200                     case WRITE:
201                         if (child.getDataAfter().isPresent()) {
202                             final NormalizedNode<?, ?> dataAfter = child.getDataAfter().get();
203                             LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
204                             LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
205                             tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
206                         }
207                         break;
208                     default:
209                         break;
210                 }
211             }
212         }
213         tx.submit();
214     }
215
216     private synchronized void processRoutesTable(final DataTreeCandidateNode node,
217             final YangInstanceIdentifier identifier, final DOMDataWriteTransaction tx,
218             final YangInstanceIdentifier routeTableIdentifier) {
219         for (final DataTreeCandidateNode child : node.getChildNodes()) {
220             final YangInstanceIdentifier childIdentifier = identifier.node(child.getIdentifier());
221             switch (child.getModificationType()) {
222                 case DELETE:
223                     LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
224                     tx.delete(LogicalDatastoreType.OPERATIONAL, childIdentifier);
225                     break;
226                 case UNMODIFIED:
227                     // No-op
228                     break;
229                 case SUBTREE_MODIFIED:
230                     //For be ables to use DELETE when we remove specific routes as we do when we remove the whole routes,
231                     // we need to go deeper three levels
232                     if (!routeTableIdentifier.equals(childIdentifier.getParent().getParent().getParent())) {
233                         processRoutesTable(child, childIdentifier, tx, routeTableIdentifier);
234                         break;
235                     }
236                 case WRITE:
237                     if (child.getDataAfter().isPresent()) {
238                         final NormalizedNode<?, ?> dataAfter = child.getDataAfter().get();
239                         LOG.trace("App peer -> AdjRibsIn path : {}", childIdentifier);
240                         LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
241                         tx.put(LogicalDatastoreType.OPERATIONAL, childIdentifier, dataAfter);
242                     }
243                     break;
244                 default:
245                     break;
246             }
247         }
248     }
249
250     @Override
251     public String getName() {
252         return this.name;
253     }
254
255     // FIXME ListenableFuture<?> should be used once closeServiceInstance uses wildcard too
256     @Override
257     public synchronized ListenableFuture<Void> close() {
258         setActive(false);
259         if (this.registration != null) {
260             this.registration.close();
261             this.registration = null;
262         }
263         if (this.effectiveRibInWriter != null) {
264             this.effectiveRibInWriter.close();
265         }
266         final ListenableFuture<Void> future;
267         if (this.adjRibInWriter != null) {
268             future = this.adjRibInWriter.removePeer();
269         } else {
270             future = Futures.immediateFuture(null);
271         }
272         if (this.chain != null) {
273             this.chain.close();
274             this.chain = null;
275         }
276         if (this.writerChain != null) {
277             this.writerChain.close();
278             this.writerChain = null;
279         }
280         if (this.trackerRegistration != null) {
281             this.trackerRegistration.close();
282             this.trackerRegistration = null;
283         }
284         return future;
285     }
286
287     @Override
288     public byte[] getRawIdentifier() {
289         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
290     }
291
292     @Override
293     public PeerId getPeerId() {
294         return this.peerId;
295     }
296
297     @Override
298     public boolean supportsAddPathSupported(final TablesKey tableKey) {
299         return false;
300     }
301
302     @Override
303     public SendReceive getSupportedAddPathTables(final TablesKey tableKey) {
304         return null;
305     }
306
307     @Override
308     public boolean supportsTable(final TablesKey tableKey) {
309         return this.rib.supportsTable(tableKey);
310     }
311
312     @Override
313     public YangInstanceIdentifier getPeerRibInstanceIdentifier() {
314         return this.peerYIId;
315     }
316
317     @Override
318     public PeerRole getRole() {
319         return PeerRole.Internal;
320     }
321
322     @Override
323     public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
324         final AsyncTransaction<?, ?> transaction, final Throwable cause) {
325         LOG.error("Transaction chain {} failed.", transaction != null ? transaction.getIdentifier() : null, cause);
326     }
327
328     @Override
329     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
330         LOG.debug("Transaction chain {} successful.", chain);
331     }
332
333     @Override
334     public BGPErrorHandlingState getBGPErrorHandlingState() {
335         return this;
336     }
337
338     @Override
339     public BGPAfiSafiState getBGPAfiSafiState() {
340         return this;
341     }
342
343     @Override
344     public BGPSessionState getBGPSessionState() {
345         return this.bgpSessionState;
346     }
347
348     @Override
349     public BGPTimersState getBGPTimersState() {
350         return this.bgpSessionState;
351     }
352
353     @Override
354     public BGPTransportState getBGPTransportState() {
355         return this.bgpSessionState;
356     }
357
358
359     @Override
360     public PeerRole getFromPeerRole() {
361         return getRole();
362     }
363
364     @Override
365     public PeerId getFromPeerId() {
366         return getPeerId();
367     }
368 }