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