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