BUG-4197: BGP OpenConfig SPI
[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         // FIXME: set to true, once it's fixed how to skip advertising routes back to AppPeer
75         this.writer = this.writer.transform(RouterIds.createPeerId(ipAddress), this.targetRib.getRibSupportContext(), this.targetRib.getLocalTablesKeys(), false);
76         this.moduleTracker = moduleTracker;
77         if (moduleTracker != null) {
78             moduleTracker.onInstanceCreate();
79         }
80     }
81
82     public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address bgpPeerId, final RIBImpl targetRibDependency) {
83         this(applicationRibId, bgpPeerId, targetRibDependency, null);
84     }
85
86     /**
87      * Routes come from application RIB that is identified by (configurable) name.
88      * Each route is pushed into AdjRibsInWriter with it's whole context. In this
89      * method, it doesn't matter if the routes are removed or added, this will
90      * be determined in LocRib.
91      */
92     @Override
93     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
94         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
95         LOG.debug("Received data change to ApplicationRib {}", changes);
96         for (final DataTreeCandidate tc : changes) {
97             LOG.debug("Modification Type {}", tc.getRootNode().getModificationType());
98             final YangInstanceIdentifier path = tc.getRootPath();
99             final PathArgument lastArg = path.getLastPathArgument();
100             Verify.verify(lastArg instanceof NodeIdentifierWithPredicates, "Unexpected type %s in path %s", lastArg.getClass(), path);
101             final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
102             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
103                 final PathArgument childIdentifier = child.getIdentifier();
104                 final YangInstanceIdentifier tableId = this.adjRibsInId.node(tableKey).node(childIdentifier);
105                 switch (child.getModificationType()) {
106                 case DELETE:
107                     LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
108                     tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
109                     break;
110                 case UNMODIFIED:
111                     // No-op
112                     break;
113                 case SUBTREE_MODIFIED:
114                     if (EffectiveRibInWriter.TABLE_ROUTES.equals(childIdentifier)) {
115                         processRoutesTable(child, tableId, tx, tableId);
116                         break;
117                     }
118                 case WRITE:
119                     if (child.getDataAfter().isPresent()) {
120                         final NormalizedNode<?,?> dataAfter = child.getDataAfter().get();
121                         LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
122                         LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
123                         tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
124                     }
125                     break;
126                 default:
127                     break;
128                 }
129             }
130         }
131         tx.submit();
132     }
133
134     /**
135      * Applies modification under table routes based on modification type instead of only put. BUG 4438
136      * @param node
137      * @param identifier
138      * @param tx
139      * @param routeTableIdentifier
140      */
141     private void processRoutesTable(final DataTreeCandidateNode node, final YangInstanceIdentifier identifier,
142         final DOMDataWriteTransaction tx, final YangInstanceIdentifier routeTableIdentifier) {
143         for (final DataTreeCandidateNode child : node.getChildNodes()) {
144             final YangInstanceIdentifier childIdentifier = identifier.node(child.getIdentifier());
145             switch (child.getModificationType()) {
146             case DELETE:
147                 LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
148                 tx.delete(LogicalDatastoreType.OPERATIONAL, childIdentifier);
149                 break;
150             case UNMODIFIED:
151                 // No-op
152                 break;
153             case SUBTREE_MODIFIED:
154                 //For be ables to use DELETE when we remove specific routes as we do when we remove the whole routes,
155                 // we need to go deeper three levels
156                 if (!routeTableIdentifier.equals(childIdentifier.getParent().getParent().getParent())) {
157                     processRoutesTable(child, childIdentifier, tx, routeTableIdentifier);
158                     break;
159                 }
160             case WRITE:
161                 if (child.getDataAfter().isPresent()) {
162                     final NormalizedNode<?,?> dataAfter = child.getDataAfter().get();
163                     LOG.trace("App peer -> AdjRibsIn path : {}", childIdentifier);
164                     LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
165                     tx.put(LogicalDatastoreType.OPERATIONAL, childIdentifier, dataAfter);
166                 }
167                 break;
168             default:
169                 break;
170             }
171         }
172     }
173
174     @Override
175     public String getName() {
176         return this.name;
177     }
178
179     @Override
180     public void close() {
181         this.writer.cleanTables(this.targetRib.getLocalTablesKeys());
182         this.chain.close();
183         this.writerChain.close();
184         if (this.moduleTracker != null) {
185             this.moduleTracker.onInstanceClose();
186         }
187     }
188
189     @Override
190     public byte[] getRawIdentifier() {
191         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
192     }
193
194     @Override
195     public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction,
196         final Throwable cause) {
197         LOG.error("Transaction chain failed.", cause);
198     }
199
200     @Override
201     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
202         LOG.debug("Transaction chain {} successfull.", chain);
203     }
204 }