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