126bd553dcedec4f8750708003cf2daa1d9c9c72
[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.Optional;
21 import java.util.Set;
22 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
25 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
26 import org.opendaylight.controller.md.sal.dom.api.ClusteredDOMDataTreeChangeListener;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
29 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
30 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
31 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
32 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
33 import org.opendaylight.protocol.bgp.rib.impl.state.BGPPeerStateImpl;
34 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl;
35 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStats;
36 import org.opendaylight.protocol.bgp.rib.impl.stats.peer.BGPPeerStatsImpl;
37 import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker;
38 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
39 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
40 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
41 import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState;
42 import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState;
43 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
44 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
45 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
46 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.ApplicationRibId;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.SimpleRoutingPolicy;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibIn;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
56 import org.opendaylight.yangtools.concepts.ListenerRegistration;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 /**
67  * Application Peer is a special case of BGP peer. It serves as an interface
68  * for user to advertise user routes to ODL and through ODL to other BGP peers.
69  *
70  * This peer has it's own RIB, where it stores all user routes. This RIB is
71  * located in configurational datastore. Routes are added through RESTCONF.
72  *
73  * They are then processed as routes from any other peer, through AdjRib,
74  * EffectiveRib,LocRib and if they are advertised further, through AdjRibOut.
75  *
76  * For purposed of import policies such as Best Path Selection, application
77  * peer needs to have a BGP-ID that is configurable.
78  */
79 public class ApplicationPeer extends BGPPeerStateImpl implements org.opendaylight.protocol.bgp.rib.spi.Peer,
80     ClusteredDOMDataTreeChangeListener, TransactionChainListener {
81
82     private static final Logger LOG = LoggerFactory.getLogger(ApplicationPeer.class);
83
84     private final byte[] rawIdentifier;
85     private final String name;
86     private final YangInstanceIdentifier adjRibsInId;
87     private final Ipv4Address ipAddress;
88     private final RIB rib;
89     private final YangInstanceIdentifier peerIId;
90     private DOMTransactionChain chain;
91     private DOMTransactionChain writerChain;
92     private EffectiveRibInWriter effectiveRibInWriter;
93     private AdjRibInWriter adjRibInWriter;
94     private ListenerRegistration<ApplicationPeer> registration;
95     private final Set<NodeIdentifierWithPredicates> supportedTables = new HashSet<>();
96     private final BGPSessionStateImpl bgpSessionState = new BGPSessionStateImpl();
97
98     @FunctionalInterface
99     interface RegisterAppPeerListener {
100         /**
101          * Register Application Peer Change Listener once AdjRibIn has been successfully initialized.
102          */
103         void register();
104     }
105
106     public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address ipAddress, final RIB rib) {
107         super(rib.getInstanceIdentifier(), "application-peers", new IpAddress(ipAddress), rib.getLocalTablesKeys(),
108             Collections.emptySet());
109         this.name = applicationRibId.getValue();
110         final RIB targetRib = requireNonNull(rib);
111         this.rawIdentifier = InetAddresses.forString(ipAddress.getValue()).getAddress();
112         final NodeIdentifierWithPredicates peerId = IdentifierUtils.domPeerId(RouterIds.createPeerId(ipAddress));
113         this.peerIId = targetRib.getYangRibId().node(Peer.QNAME).node(peerId);
114         this.adjRibsInId = this.peerIId.node(AdjRibIn.QNAME).node(Tables.QNAME);
115         this.rib = targetRib;
116         this.ipAddress = ipAddress;
117     }
118
119     public synchronized void instantiateServiceInstance(final DOMDataTreeChangeService dataTreeChangeService,
120         final DOMDataTreeIdentifier appPeerDOMId) {
121         this.chain = this.rib.createPeerChain(this);
122         this.writerChain = this.rib.createPeerChain(this);
123
124         final Optional<SimpleRoutingPolicy> simpleRoutingPolicy = Optional.of(SimpleRoutingPolicy.AnnounceNone);
125         final PeerId peerId = RouterIds.createPeerId(this.ipAddress);
126         final Set<TablesKey> localTables = this.rib.getLocalTablesKeys();
127         localTables.forEach(tablesKey -> {
128             final ExportPolicyPeerTracker exportTracker = this.rib.getExportPolicyPeerTracker(tablesKey);
129             if (exportTracker != null) {
130                 exportTracker.registerPeer(peerId, null, this.peerIId, PeerRole.Internal, simpleRoutingPolicy);
131             }
132             this.supportedTables.add(RibSupportUtils.toYangTablesKey(tablesKey));
133         });
134         setAdvertizedGracefulRestartTableTypes(Collections.emptyList());
135
136         this.adjRibInWriter = AdjRibInWriter.create(this.rib.getYangRibId(), PeerRole.Internal, simpleRoutingPolicy, this.writerChain);
137         final RIBSupportContextRegistry context = this.rib.getRibSupportContext();
138         final RegisterAppPeerListener registerAppPeerListener = () -> {
139             synchronized (this) {
140                 if(this.chain != null) {
141                     this.registration = dataTreeChangeService.registerDataTreeChangeListener(appPeerDOMId, this);
142                 }
143             }
144         };
145         this.adjRibInWriter = this.adjRibInWriter.transform(peerId, context, localTables, Collections.emptyMap(),
146             registerAppPeerListener);
147         final BGPPeerStats peerStats = new BGPPeerStatsImpl(this.name, localTables, this);
148         this.effectiveRibInWriter = EffectiveRibInWriter.create(this.rib.getService(), this.rib.createPeerChain(this), this.peerIId,
149             this.rib.getImportPolicyPeerTracker(), context, PeerRole.Internal,
150             peerStats.getAdjRibInRouteCounters(), localTables);
151         this.bgpSessionState.registerMessagesCounter(this);
152     }
153
154     /**
155      * Routes come from application RIB that is identified by (configurable) name.
156      * Each route is pushed into AdjRibsInWriter with it's whole context. In this
157      * method, it doesn't matter if the routes are removed or added, this will
158      * be determined in LocRib.
159      */
160     @Override
161     public synchronized void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
162         if(this.chain == null) {
163             LOG.trace("Skipping data changed called to Application Peer. Change : {}", changes);
164             return;
165         }
166         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
167         LOG.debug("Received data change to ApplicationRib {}", changes);
168         for (final DataTreeCandidate tc : changes) {
169             LOG.debug("Modification Type {}", tc.getRootNode().getModificationType());
170             final YangInstanceIdentifier path = tc.getRootPath();
171             final PathArgument lastArg = path.getLastPathArgument();
172             Verify.verify(lastArg instanceof NodeIdentifierWithPredicates, "Unexpected type %s in path %s", lastArg.getClass(), path);
173             final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
174             if (!this.supportedTables.contains(tableKey)) {
175                 LOG.trace("Skipping received data change for non supported family {}.", tableKey);
176                 continue;
177             }
178             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
179                 final PathArgument childIdentifier = child.getIdentifier();
180                 final YangInstanceIdentifier tableId = this.adjRibsInId.node(tableKey).node(childIdentifier);
181                 switch (child.getModificationType()) {
182                 case DELETE:
183                     LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
184                     tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
185                     break;
186                 case UNMODIFIED:
187                     // No-op
188                     break;
189                 case SUBTREE_MODIFIED:
190                     if (EffectiveRibInWriter.TABLE_ROUTES.equals(childIdentifier)) {
191                         processRoutesTable(child, tableId, tx, tableId);
192                         break;
193                     }
194                 case WRITE:
195                     if (child.getDataAfter().isPresent()) {
196                         final NormalizedNode<?,?> dataAfter = child.getDataAfter().get();
197                         LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
198                         LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
199                         tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
200                     }
201                     break;
202                 default:
203                     break;
204                 }
205             }
206         }
207         tx.submit();
208     }
209
210     /**
211      * Applies modification under table routes based on modification type instead of only put. BUG 4438
212      * @param node
213      * @param identifier
214      * @param tx
215      * @param routeTableIdentifier
216      */
217     private synchronized void processRoutesTable(final DataTreeCandidateNode node, final YangInstanceIdentifier identifier,
218             final DOMDataWriteTransaction tx, 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         if (this.registration != null) {
259             this.registration.close();
260             this.registration = null;
261         }
262         if (this.effectiveRibInWriter != null) {
263             this.effectiveRibInWriter.close();
264         }
265         final ListenableFuture<Void> future;
266         if (this.adjRibInWriter != null) {
267             future = this.adjRibInWriter.removePeer();
268         }else {
269             future = Futures.immediateFuture(null);
270         }
271         if (this.chain != null) {
272             this.chain.close();
273             this.chain = null;
274         }
275         if (this.writerChain != null) {
276             this.writerChain.close();
277             this.writerChain = null;
278         }
279         return future;
280     }
281
282     @Override
283     public byte[] getRawIdentifier() {
284         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
285     }
286
287     @Override
288     public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
289         final AsyncTransaction<?, ?> transaction, final Throwable cause) {
290         LOG.error("Transaction chain {} failed.", transaction != null ? transaction.getIdentifier() : null, cause);
291     }
292
293     @Override
294     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
295         LOG.debug("Transaction chain {} successful.", chain);
296     }
297
298     @Override
299     public BGPErrorHandlingState getBGPErrorHandlingState() {
300         return this;
301     }
302
303     @Override
304     public BGPAfiSafiState getBGPAfiSafiState() {
305         return this;
306     }
307
308     @Override
309     public BGPSessionState getBGPSessionState() {
310         return this.bgpSessionState;
311     }
312
313     @Override
314     public BGPTimersState getBGPTimersState() {
315         return this.bgpSessionState;
316     }
317
318     @Override
319     public BGPTransportState getBGPTransportState() {
320         return this.bgpSessionState;
321     }
322 }