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