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