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