Bug-5536: When using clustering with replication, linkstate topology of non-leaders...
[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.Optional;
17 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
18 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
19 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
20 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
21 import org.opendaylight.controller.md.sal.dom.api.ClusteredDOMDataTreeChangeListener;
22 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
23 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
24 import org.opendaylight.protocol.bgp.openconfig.spi.BGPConfigModuleTracker;
25 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
26 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
27 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
28 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.ApplicationRibId;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.SimpleRoutingPolicy;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibIn;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
40 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 /**
45  * Application Peer is a special case of BGP peer. It serves as an interface
46  * for user to advertise user routes to ODL and through ODL to other BGP peers.
47  *
48  * This peer has it's own RIB, where it stores all user routes. This RIB is
49  * located in configurational datastore. Routes are added through RESTCONF.
50  *
51  * They are then processed as routes from any other peer, through AdjRib,
52  * EffectiveRib,LocRib and if they are advertised further, through AdjRibOut.
53  *
54  * For purposed of import policies such as Best Path Selection, application
55  * peer needs to have a BGP-ID that is configurable.
56  */
57 public class ApplicationPeer implements AutoCloseable, org.opendaylight.protocol.bgp.rib.spi.Peer, ClusteredDOMDataTreeChangeListener, TransactionChainListener {
58
59     private static final Logger LOG = LoggerFactory.getLogger(ApplicationPeer.class);
60
61     private final byte[] rawIdentifier;
62     private final String name;
63     private final YangInstanceIdentifier adjRibsInId;
64     private final DOMTransactionChain chain;
65     private final BGPConfigModuleTracker moduleTracker;
66     private final EffectiveRibInWriter effectiveRibInWriter;
67     private AdjRibInWriter writer;
68
69     public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address ipAddress, final RIB rib,
70             final BGPConfigModuleTracker moduleTracker) {
71         this.name = applicationRibId.getValue().toString();
72         final RIB targetRib = Preconditions.checkNotNull(rib);
73         this.rawIdentifier = InetAddresses.forString(ipAddress.getValue()).getAddress();
74         final NodeIdentifierWithPredicates peerId = IdentifierUtils.domPeerId(RouterIds.createPeerId(ipAddress));
75         final YangInstanceIdentifier peerIId = targetRib.getYangRibId().node(Peer.QNAME).node(peerId);
76         this.adjRibsInId = peerIId.node(AdjRibIn.QNAME).node(Tables.QNAME);
77         this.chain = targetRib.createPeerChain(this);
78         this.writer = AdjRibInWriter.create(targetRib.getYangRibId(), PeerRole.Internal, Optional.of(SimpleRoutingPolicy.AnnounceNone), this.chain);
79         this.writer = this.writer.transform(RouterIds.createPeerId(ipAddress), targetRib.getRibSupportContext(), targetRib.getLocalTablesKeys(),
80                 Collections.emptyList());
81         //TODO need to create effective rib in writer with route counter here
82         this.effectiveRibInWriter = EffectiveRibInWriter.create(targetRib.getService(), this.chain, peerIId,
83             targetRib.getImportPolicyPeerTracker(), targetRib.getRibSupportContext(), PeerRole.Internal);
84         this.moduleTracker = moduleTracker;
85         if (moduleTracker != null) {
86             moduleTracker.onInstanceCreate();
87         }
88     }
89
90     public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address bgpPeerId, final RIB targetRibDependency) {
91         this(applicationRibId, bgpPeerId, targetRibDependency, null);
92     }
93
94     /**
95      * Routes come from application RIB that is identified by (configurable) name.
96      * Each route is pushed into AdjRibsInWriter with it's whole context. In this
97      * method, it doesn't matter if the routes are removed or added, this will
98      * be determined in LocRib.
99      */
100     @Override
101     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
102         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
103         LOG.debug("Received data change to ApplicationRib {}", changes);
104         for (final DataTreeCandidate tc : changes) {
105             LOG.debug("Modification Type {}", tc.getRootNode().getModificationType());
106             final YangInstanceIdentifier path = tc.getRootPath();
107             final PathArgument lastArg = path.getLastPathArgument();
108             Verify.verify(lastArg instanceof NodeIdentifierWithPredicates, "Unexpected type %s in path %s", lastArg.getClass(), path);
109             final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
110             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
111                 final PathArgument childIdentifier = child.getIdentifier();
112                 final YangInstanceIdentifier tableId = this.adjRibsInId.node(tableKey).node(childIdentifier);
113                 switch (child.getModificationType()) {
114                 case DELETE:
115                     LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
116                     tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
117                     break;
118                 case UNMODIFIED:
119                     // No-op
120                     break;
121                 case SUBTREE_MODIFIED:
122                     if (EffectiveRibInWriter.TABLE_ROUTES.equals(childIdentifier)) {
123                         processRoutesTable(child, tableId, tx, tableId);
124                         break;
125                     }
126                 case WRITE:
127                     if (child.getDataAfter().isPresent()) {
128                         final NormalizedNode<?,?> dataAfter = child.getDataAfter().get();
129                         LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
130                         LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
131                         tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
132                     }
133                     break;
134                 default:
135                     break;
136                 }
137             }
138         }
139         tx.submit();
140     }
141
142     /**
143      * Applies modification under table routes based on modification type instead of only put. BUG 4438
144      * @param node
145      * @param identifier
146      * @param tx
147      * @param routeTableIdentifier
148      */
149     private void processRoutesTable(final DataTreeCandidateNode node, final YangInstanceIdentifier identifier,
150             final DOMDataWriteTransaction tx, final YangInstanceIdentifier routeTableIdentifier) {
151         for (final DataTreeCandidateNode child : node.getChildNodes()) {
152             final YangInstanceIdentifier childIdentifier = identifier.node(child.getIdentifier());
153             switch (child.getModificationType()) {
154             case DELETE:
155                 LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
156                 tx.delete(LogicalDatastoreType.OPERATIONAL, childIdentifier);
157                 break;
158             case UNMODIFIED:
159                 // No-op
160                 break;
161             case SUBTREE_MODIFIED:
162                 //For be ables to use DELETE when we remove specific routes as we do when we remove the whole routes,
163                 // we need to go deeper three levels
164                 if (!routeTableIdentifier.equals(childIdentifier.getParent().getParent().getParent())) {
165                     processRoutesTable(child, childIdentifier, tx, routeTableIdentifier);
166                     break;
167                 }
168             case WRITE:
169                 if (child.getDataAfter().isPresent()) {
170                     final NormalizedNode<?,?> dataAfter = child.getDataAfter().get();
171                     LOG.trace("App peer -> AdjRibsIn path : {}", childIdentifier);
172                     LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
173                     tx.put(LogicalDatastoreType.OPERATIONAL, childIdentifier, dataAfter);
174                 }
175                 break;
176             default:
177                 break;
178             }
179         }
180     }
181
182     @Override
183     public String getName() {
184         return this.name;
185     }
186
187     @Override
188     public void close() {
189         this.effectiveRibInWriter.close();
190         this.writer.removePeer();
191         this.chain.close();
192         if (this.moduleTracker != null) {
193             this.moduleTracker.onInstanceClose();
194         }
195     }
196
197     @Override
198     public byte[] getRawIdentifier() {
199         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
200     }
201
202     @Override
203     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction,
204             final Throwable cause) {
205         LOG.error("Transaction chain failed.", cause);
206     }
207
208     @Override
209     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
210         LOG.debug("Transaction chain {} successfull.", chain);
211     }
212 }