YANG revision dates mass-update
[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 static java.util.Objects.requireNonNull;
11 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ADJRIBIN_NID;
12 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.PEER_NID;
13 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.ROUTES_NID;
14 import static org.opendaylight.protocol.bgp.rib.spi.RIBNodeIdentifiers.TABLES_NID;
15
16 import com.google.common.base.Verify;
17 import com.google.common.cache.CacheBuilder;
18 import com.google.common.cache.CacheLoader;
19 import com.google.common.cache.LoadingCache;
20 import com.google.common.net.InetAddresses;
21 import com.google.common.util.concurrent.FluentFuture;
22 import com.google.common.util.concurrent.FutureCallback;
23 import com.google.common.util.concurrent.MoreExecutors;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashSet;
28 import java.util.List;
29 import java.util.Set;
30 import org.opendaylight.mdsal.binding.api.Transaction;
31 import org.opendaylight.mdsal.binding.api.TransactionChain;
32 import org.opendaylight.mdsal.common.api.CommitInfo;
33 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
34 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
35 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
36 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
37 import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction;
38 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
39 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
40 import org.opendaylight.protocol.bgp.openconfig.spi.BGPTableTypeRegistryConsumer;
41 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
42 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
43 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl;
44 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
45 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
46 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
47 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
48 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
49 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddressNoZone;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4AddressNoZone;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.SendReceive;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.ApplicationRibId;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerRole;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.Peer;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.PeerKey;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.bgp.rib.rib.peer.AdjRibOut;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev200120.RouteTarget;
61 import org.opendaylight.yangtools.concepts.ListenerRegistration;
62 import org.opendaylight.yangtools.concepts.Registration;
63 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
64 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
68 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73
74 /**
75  * Application Peer is a special case of BGP peer. It serves as an interface
76  * for user to advertise user routes to ODL and through ODL to other BGP peers.
77  *
78  * <p>
79  * This peer has it's own RIB, where it stores all user routes. This RIB is
80  * located in configurational datastore. Routes are added through RESTCONF.
81  *
82  * <p>
83  * They are then processed as routes from any other peer, through AdjRib,
84  * EffectiveRib,LocRib and if they are advertised further, through AdjRibOut.
85  *
86  * <p>
87  * For purposed of import policies such as Best Path Selection, application
88  * peer needs to have a BGP-ID that is configurable.
89  */
90 public class ApplicationPeer extends AbstractPeer implements ClusteredDOMDataTreeChangeListener {
91
92     private static final Logger LOG = LoggerFactory.getLogger(ApplicationPeer.class);
93
94     private static final String APP_PEER_GROUP = "application-peers";
95     private final YangInstanceIdentifier adjRibsInId;
96     private final InstanceIdentifier<AdjRibOut> peerRibOutIId;
97     private final KeyedInstanceIdentifier<Peer, PeerKey> peerIId;
98     private final BGPTableTypeRegistryConsumer tableTypeRegistry;
99     private EffectiveRibInWriter effectiveRibInWriter;
100     private AdjRibInWriter adjRibInWriter;
101     private ListenerRegistration<ApplicationPeer> registration;
102     private final Set<NodeIdentifierWithPredicates> supportedTables = new HashSet<>();
103     private final BGPSessionStateImpl bgpSessionState = new BGPSessionStateImpl();
104     private final LoadingCache<TablesKey, KeyedInstanceIdentifier<Tables, TablesKey>> tablesIId
105             = CacheBuilder.newBuilder()
106             .build(new CacheLoader<TablesKey, KeyedInstanceIdentifier<Tables, TablesKey>>() {
107                 @Override
108                 public KeyedInstanceIdentifier<Tables, TablesKey> load(final TablesKey tablesKey) {
109                     return ApplicationPeer.this.peerRibOutIId.child(Tables.class, tablesKey);
110                 }
111             });
112     private Registration trackerRegistration;
113     private YangInstanceIdentifier peerPath;
114
115     @Override
116     public List<RouteTarget> getMemberships() {
117         return Collections.emptyList();
118     }
119
120     @FunctionalInterface
121     interface RegisterAppPeerListener {
122         /**
123          * Register Application Peer Change Listener once AdjRibIn has been successfully initialized.
124          */
125         void register();
126     }
127
128     public ApplicationPeer(
129             final BGPTableTypeRegistryConsumer tableTypeRegistry,
130             final ApplicationRibId applicationRibId, final Ipv4AddressNoZone ipAddress, final RIB rib) {
131         super(rib, applicationRibId.getValue(), APP_PEER_GROUP, PeerRole.Internal,
132                 new IpAddressNoZone(ipAddress), Collections.emptySet());
133         this.tableTypeRegistry = requireNonNull(tableTypeRegistry);
134         final RIB targetRib = requireNonNull(rib);
135         this.rawIdentifier = InetAddresses.forString(ipAddress.getValue()).getAddress();
136         this.adjRibsInId = targetRib.getYangRibId().node(PEER_NID)
137                 .node(IdentifierUtils.domPeerId(RouterIds.createPeerId(ipAddress)))
138                 .node(ADJRIBIN_NID).node(TABLES_NID);
139         this.peerId = RouterIds.createPeerId(ipAddress);
140         this.peerIId = getInstanceIdentifier().child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns
141                 .yang.bgp.rib.rev180329.bgp.rib.rib.Peer.class, new PeerKey(this.peerId));
142         this.peerRibOutIId = this.peerIId.child(AdjRibOut.class);
143     }
144
145     public synchronized void instantiateServiceInstance(final DOMDataTreeChangeService dataTreeChangeService,
146             final DOMDataTreeIdentifier appPeerDOMId) {
147         setActive(true);
148         final Set<TablesKey> localTables = this.rib.getLocalTablesKeys();
149         localTables.forEach(tablesKey -> this.supportedTables.add(RibSupportUtils.toYangTablesKey(tablesKey)));
150         setAdvertizedGracefulRestartTableTypes(Collections.emptyList());
151
152         createDomChain();
153         this.adjRibInWriter = AdjRibInWriter.create(this.rib.getYangRibId(), PeerRole.Internal, this);
154         final RIBSupportContextRegistry context = this.rib.getRibSupportContext();
155         final RegisterAppPeerListener registerAppPeerListener = () -> {
156             synchronized (this) {
157                 if (getDomChain() != null) {
158                     this.registration = dataTreeChangeService.registerDataTreeChangeListener(appPeerDOMId, this);
159                 }
160             }
161         };
162         this.peerPath = createPeerPath();
163         this.adjRibInWriter = this.adjRibInWriter.transform(this.peerId, this.peerPath, context, localTables,
164                 Collections.emptyMap(), registerAppPeerListener);
165         this.effectiveRibInWriter = new EffectiveRibInWriter(this, this.rib,
166                 this.rib.createPeerDOMChain(this), this.peerPath, localTables, this.tableTypeRegistry,
167                 new ArrayList<>(), this.rtCache);
168         this.effectiveRibInWriter.init();
169         this.bgpSessionState.registerMessagesCounter(this);
170         this.trackerRegistration = this.rib.getPeerTracker().registerPeer(this);
171     }
172
173     /**
174      * Routes come from application RIB that is identified by (configurable) name.
175      * Each route is pushed into AdjRibsInWriter with it's whole context. In this
176      * method, it doesn't matter if the routes are removed or added, this will
177      * be determined in LocRib.
178      */
179     @Override
180     public synchronized void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
181         if (getDomChain() == null) {
182             LOG.trace("Skipping data changed called to Application Peer. Change : {}", changes);
183             return;
184         }
185         final DOMDataTreeWriteTransaction tx = getDomChain().newWriteOnlyTransaction();
186         LOG.debug("Received data change to ApplicationRib {}", changes);
187         for (final DataTreeCandidate tc : changes) {
188             LOG.debug("Modification Type {}", tc.getRootNode().getModificationType());
189             final YangInstanceIdentifier path = tc.getRootPath();
190             final PathArgument lastArg = path.getLastPathArgument();
191             Verify.verify(lastArg instanceof NodeIdentifierWithPredicates,
192                     "Unexpected type %s in path %s", lastArg.getClass(), path);
193             final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
194             if (!this.supportedTables.contains(tableKey)) {
195                 LOG.trace("Skipping received data change for non supported family {}.", tableKey);
196                 continue;
197             }
198             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
199                 final PathArgument childIdentifier = child.getIdentifier();
200                 final YangInstanceIdentifier tableId = this.adjRibsInId.node(tableKey).node(childIdentifier);
201                 switch (child.getModificationType()) {
202                     case DELETE:
203                     case DISAPPEARED:
204                         LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
205                         tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
206                         break;
207                     case UNMODIFIED:
208                         // No-op
209                         break;
210                     case SUBTREE_MODIFIED:
211                         if (ROUTES_NID.equals(childIdentifier)) {
212                             processRoutesTable(child, tableId, tx, tableId);
213                         } else {
214                             processWrite(child, tableId, tx);
215                         }
216                         break;
217                     case WRITE:
218                     case APPEARED:
219                         processWrite(child, tableId, tx);
220                         break;
221                     default:
222                         break;
223                 }
224             }
225         }
226         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
227             @Override
228             public void onSuccess(final CommitInfo result) {
229                 LOG.trace("Successful commit");
230             }
231
232             @Override
233             public void onFailure(final Throwable trw) {
234                 LOG.error("Failed commit", trw);
235             }
236         }, MoreExecutors.directExecutor());
237     }
238
239     private static void processWrite(final DataTreeCandidateNode child, final YangInstanceIdentifier tableId,
240             final DOMDataTreeWriteTransaction tx) {
241         if (child.getDataAfter().isPresent()) {
242             final NormalizedNode<?, ?> dataAfter = child.getDataAfter().get();
243             LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
244             LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
245             tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
246         }
247     }
248
249     private synchronized void processRoutesTable(final DataTreeCandidateNode node,
250             final YangInstanceIdentifier identifier, final DOMDataTreeWriteTransaction tx,
251             final YangInstanceIdentifier routeTableIdentifier) {
252         for (final DataTreeCandidateNode child : node.getChildNodes()) {
253             final YangInstanceIdentifier childIdentifier = identifier.node(child.getIdentifier());
254             switch (child.getModificationType()) {
255                 case DELETE:
256                     LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
257                     tx.delete(LogicalDatastoreType.OPERATIONAL, childIdentifier);
258                     break;
259                 case UNMODIFIED:
260                     // No-op
261                     break;
262                 case SUBTREE_MODIFIED:
263                     // For be ables to use DELETE when we remove specific routes as we do when we remove the whole
264                     // routes, we need to go deeper three levels
265                     if (!routeTableIdentifier.equals(childIdentifier.getParent().getParent().getParent())) {
266                         processRoutesTable(child, childIdentifier, tx, routeTableIdentifier);
267                     } else {
268                         processRouteWrite(child, childIdentifier, tx);
269                     }
270                     break;
271                 case WRITE:
272                     processRouteWrite(child, childIdentifier, tx);
273                     break;
274                 default:
275                     break;
276             }
277         }
278     }
279
280     private static void processRouteWrite(final DataTreeCandidateNode child,
281             final YangInstanceIdentifier childIdentifier, final DOMDataTreeWriteTransaction tx) {
282         if (child.getDataAfter().isPresent()) {
283             final NormalizedNode<?, ?> dataAfter = child.getDataAfter().get();
284             LOG.trace("App peer -> AdjRibsIn path : {}", childIdentifier);
285             LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
286             tx.put(LogicalDatastoreType.OPERATIONAL, childIdentifier, dataAfter);
287         }
288     }
289
290     @Override
291     public synchronized FluentFuture<? extends CommitInfo> close() {
292         setActive(false);
293         if (this.registration != null) {
294             this.registration.close();
295             this.registration = null;
296         }
297         if (this.adjRibInWriter != null) {
298             this.adjRibInWriter.releaseChain();
299         }
300         if (this.effectiveRibInWriter != null) {
301             this.effectiveRibInWriter.close();
302         }
303         final FluentFuture<? extends CommitInfo> future;
304         future = removePeer(this.peerPath);
305         closeDomChain();
306         if (this.trackerRegistration != null) {
307             this.trackerRegistration.close();
308             this.trackerRegistration = null;
309         }
310         return future;
311     }
312
313     @Override
314     public boolean supportsAddPathSupported(final TablesKey tableKey) {
315         return false;
316     }
317
318     @Override
319     public SendReceive getSupportedAddPathTables(final TablesKey tableKey) {
320         return null;
321     }
322
323     @Override
324     public boolean supportsTable(final TablesKey tableKey) {
325         return this.rib.supportsTable(tableKey);
326     }
327
328     @Override
329     public KeyedInstanceIdentifier<Tables, TablesKey> getRibOutIId(final TablesKey tablesKey) {
330         return this.tablesIId.getUnchecked(tablesKey);
331     }
332
333     @Override
334     public void onTransactionChainFailed(final DOMTransactionChain chain, final DOMDataTreeTransaction transaction,
335             final Throwable cause) {
336         LOG.error("Transaction chain {} failed.", transaction != null ? transaction.getIdentifier() : null, cause);
337     }
338
339     @Override
340     public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
341             final Throwable cause) {
342         LOG.error("Transaction chain {} failed.", transaction != null ? transaction.getIdentifier() : null, cause);
343     }
344
345     @Override
346     public BGPSessionState getBGPSessionState() {
347         return this.bgpSessionState;
348     }
349
350     @Override
351     public BGPTimersState getBGPTimersState() {
352         return this.bgpSessionState;
353     }
354
355     @Override
356     public BGPTransportState getBGPTransportState() {
357         return this.bgpSessionState;
358     }
359 }