BUG-6647 Increase code coverage and clean up IV
[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 Ipv4Address ipAddress;
65     private final BGPConfigModuleTracker moduleTracker;
66     private final RIB rib;
67     private final YangInstanceIdentifier peerIId;
68     private DOMTransactionChain chain;
69     private DOMTransactionChain writerChain;
70     private EffectiveRibInWriter effectiveRibInWriter;
71     private AdjRibInWriter writer;
72
73     public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address ipAddress, final RIB rib,
74         final BGPConfigModuleTracker moduleTracker) {
75         this.name = applicationRibId.getValue();
76         final RIB targetRib = Preconditions.checkNotNull(rib);
77         this.rawIdentifier = InetAddresses.forString(ipAddress.getValue()).getAddress();
78         final NodeIdentifierWithPredicates peerId = IdentifierUtils.domPeerId(RouterIds.createPeerId(ipAddress));
79         this.peerIId = targetRib.getYangRibId().node(Peer.QNAME).node(peerId);
80         this.adjRibsInId = this.peerIId.node(AdjRibIn.QNAME).node(Tables.QNAME);
81         this.rib = targetRib;
82         this.ipAddress = ipAddress;
83         this.moduleTracker = moduleTracker;
84     }
85
86     public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address bgpPeerId, final RIB targetRibDependency) {
87         this(applicationRibId, bgpPeerId, targetRibDependency, null);
88     }
89
90     public void instantiateServiceInstance() {
91         this.chain = this.rib.createPeerChain(this);
92         this.writerChain = this.rib.createPeerChain(this);
93         this.writer = AdjRibInWriter.create(this.rib.getYangRibId(), PeerRole.Internal, Optional.of(SimpleRoutingPolicy.AnnounceNone), this.writerChain);
94         this.writer = this.writer.transform(RouterIds.createPeerId(this.ipAddress), this.rib.getRibSupportContext(), this.rib.getLocalTablesKeys(),
95             Collections.emptyList());
96         //TODO need to create effective rib in writer with route counter here
97         this.effectiveRibInWriter = EffectiveRibInWriter.create(this.rib.getService(), this.rib.createPeerChain(this), this.peerIId,
98             this.rib.getImportPolicyPeerTracker(), this.rib.getRibSupportContext(), PeerRole.Internal);
99         if (moduleTracker != null) {
100             moduleTracker.onInstanceCreate();
101         }
102     }
103
104     /**
105      * Routes come from application RIB that is identified by (configurable) name.
106      * Each route is pushed into AdjRibsInWriter with it's whole context. In this
107      * method, it doesn't matter if the routes are removed or added, this will
108      * be determined in LocRib.
109      */
110     @Override
111     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
112         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
113         LOG.debug("Received data change to ApplicationRib {}", changes);
114         for (final DataTreeCandidate tc : changes) {
115             LOG.debug("Modification Type {}", tc.getRootNode().getModificationType());
116             final YangInstanceIdentifier path = tc.getRootPath();
117             final PathArgument lastArg = path.getLastPathArgument();
118             Verify.verify(lastArg instanceof NodeIdentifierWithPredicates, "Unexpected type %s in path %s", lastArg.getClass(), path);
119             final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
120             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
121                 final PathArgument childIdentifier = child.getIdentifier();
122                 final YangInstanceIdentifier tableId = this.adjRibsInId.node(tableKey).node(childIdentifier);
123                 switch (child.getModificationType()) {
124                 case DELETE:
125                     LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
126                     tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
127                     break;
128                 case UNMODIFIED:
129                     // No-op
130                     break;
131                 case SUBTREE_MODIFIED:
132                     if (EffectiveRibInWriter.TABLE_ROUTES.equals(childIdentifier)) {
133                         processRoutesTable(child, tableId, tx, tableId);
134                         break;
135                     }
136                 case WRITE:
137                     if (child.getDataAfter().isPresent()) {
138                         final NormalizedNode<?,?> dataAfter = child.getDataAfter().get();
139                         LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
140                         LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
141                         tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
142                     }
143                     break;
144                 default:
145                     break;
146                 }
147             }
148         }
149         tx.submit();
150     }
151
152     /**
153      * Applies modification under table routes based on modification type instead of only put. BUG 4438
154      * @param node
155      * @param identifier
156      * @param tx
157      * @param routeTableIdentifier
158      */
159     private void processRoutesTable(final DataTreeCandidateNode node, final YangInstanceIdentifier identifier,
160             final DOMDataWriteTransaction tx, final YangInstanceIdentifier routeTableIdentifier) {
161         for (final DataTreeCandidateNode child : node.getChildNodes()) {
162             final YangInstanceIdentifier childIdentifier = identifier.node(child.getIdentifier());
163             switch (child.getModificationType()) {
164             case DELETE:
165                 LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
166                 tx.delete(LogicalDatastoreType.OPERATIONAL, childIdentifier);
167                 break;
168             case UNMODIFIED:
169                 // No-op
170                 break;
171             case SUBTREE_MODIFIED:
172                 //For be ables to use DELETE when we remove specific routes as we do when we remove the whole routes,
173                 // we need to go deeper three levels
174                 if (!routeTableIdentifier.equals(childIdentifier.getParent().getParent().getParent())) {
175                     processRoutesTable(child, childIdentifier, tx, routeTableIdentifier);
176                     break;
177                 }
178             case WRITE:
179                 if (child.getDataAfter().isPresent()) {
180                     final NormalizedNode<?,?> dataAfter = child.getDataAfter().get();
181                     LOG.trace("App peer -> AdjRibsIn path : {}", childIdentifier);
182                     LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
183                     tx.put(LogicalDatastoreType.OPERATIONAL, childIdentifier, dataAfter);
184                 }
185                 break;
186             default:
187                 break;
188             }
189         }
190     }
191
192     @Override
193     public String getName() {
194         return this.name;
195     }
196
197     @Override
198     public void close() {
199         if(this.effectiveRibInWriter != null) {
200             this.effectiveRibInWriter.close();
201         }
202         if(this.writer != null) {
203             this.writer.removePeer();
204         }
205         if(this.chain != null) {
206             this.chain.close();
207         }
208         if(this.writerChain != null) {
209             this.writerChain.close();
210         }
211         if (this.moduleTracker != null) {
212             this.moduleTracker.onInstanceClose();
213         }
214     }
215
216     @Override
217     public byte[] getRawIdentifier() {
218         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
219     }
220
221     @Override
222     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction,
223             final Throwable cause) {
224         LOG.error("Transaction chain failed.", cause);
225     }
226
227     @Override
228     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
229         LOG.debug("Transaction chain {} successfull.", chain);
230     }
231 }