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