264e04662fa6a923d4e275bc68d326737522c747
[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
12 import com.google.common.base.Verify;
13 import com.google.common.net.InetAddresses;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.HashSet;
20 import java.util.Set;
21 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
22 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
23 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
24 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
25 import org.opendaylight.controller.md.sal.dom.api.ClusteredDOMDataTreeChangeListener;
26 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
29 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
30 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
31 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
32 import org.opendaylight.protocol.bgp.rib.impl.state.BGPPeerStateImpl;
33 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl;
34 import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker;
35 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
36 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
37 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
38 import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState;
39 import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState;
40 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
41 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
42 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
43 import org.opendaylight.protocol.concepts.AbstractRegistration;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
45 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev171207.SendReceive;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.ApplicationRibId;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerId;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.PeerRole;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.Peer;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.bgp.rib.rib.peer.AdjRibIn;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.Tables;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.rib.TablesKey;
54 import org.opendaylight.yangtools.concepts.ListenerRegistration;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
58 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
60 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 /**
65  * Application Peer is a special case of BGP peer. It serves as an interface
66  * for user to advertise user routes to ODL and through ODL to other BGP peers.
67  *
68  * This peer has it's own RIB, where it stores all user routes. This RIB is
69  * located in configurational datastore. Routes are added through RESTCONF.
70  *
71  * They are then processed as routes from any other peer, through AdjRib,
72  * EffectiveRib,LocRib and if they are advertised further, through AdjRibOut.
73  *
74  * For purposed of import policies such as Best Path Selection, application
75  * peer needs to have a BGP-ID that is configurable.
76  */
77 public class ApplicationPeer extends BGPPeerStateImpl implements org.opendaylight.protocol.bgp.rib.spi.Peer,
78         ClusteredDOMDataTreeChangeListener, TransactionChainListener {
79
80     private static final Logger LOG = LoggerFactory.getLogger(ApplicationPeer.class);
81
82     private final byte[] rawIdentifier;
83     private final String name;
84     private final YangInstanceIdentifier adjRibsInId;
85     private final Ipv4Address ipAddress;
86     private final RIB rib;
87     private final YangInstanceIdentifier peerIId;
88     private DOMTransactionChain chain;
89     private DOMTransactionChain writerChain;
90     private EffectiveRibInWriter effectiveRibInWriter;
91     private AdjRibInWriter adjRibInWriter;
92     private ListenerRegistration<ApplicationPeer> registration;
93     private final Set<NodeIdentifierWithPredicates> supportedTables = new HashSet<>();
94     private final BGPSessionStateImpl bgpSessionState = new BGPSessionStateImpl();
95     private PeerId peerId;
96     private AbstractRegistration trackerRegistration;
97
98     @FunctionalInterface
99     interface RegisterAppPeerListener {
100         /**
101          * Register Application Peer Change Listener once AdjRibIn has been successfully initialized.
102          */
103         void register();
104     }
105
106     public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address ipAddress, final RIB rib) {
107         super(rib.getInstanceIdentifier(), "application-peers", new IpAddress(ipAddress),
108                 rib.getLocalTablesKeys(), Collections.emptySet());
109         this.name = applicationRibId.getValue();
110         final RIB targetRib = requireNonNull(rib);
111         this.rawIdentifier = InetAddresses.forString(ipAddress.getValue()).getAddress();
112         final NodeIdentifierWithPredicates peerIId = IdentifierUtils.domPeerId(RouterIds.createPeerId(ipAddress));
113         this.peerIId = targetRib.getYangRibId().node(Peer.QNAME).node(peerIId);
114         this.adjRibsInId = this.peerIId.node(AdjRibIn.QNAME).node(Tables.QNAME);
115         this.rib = targetRib;
116         this.ipAddress = ipAddress;
117     }
118
119     public synchronized void instantiateServiceInstance(final DOMDataTreeChangeService dataTreeChangeService,
120             final DOMDataTreeIdentifier appPeerDOMId) {
121         setActive(true);
122         this.chain = this.rib.createPeerChain(this);
123         this.writerChain = this.rib.createPeerChain(this);
124
125         this.peerId = RouterIds.createPeerId(this.ipAddress);
126         final Set<TablesKey> localTables = this.rib.getLocalTablesKeys();
127         localTables.forEach(tablesKey -> {
128             final ExportPolicyPeerTracker exportTracker = this.rib.getExportPolicyPeerTracker(tablesKey);
129             if (exportTracker != null) {
130                 exportTracker.registerPeer(this.peerId, null, this.peerIId, PeerRole.Internal);
131             }
132             this.supportedTables.add(RibSupportUtils.toYangTablesKey(tablesKey));
133         });
134         setAdvertizedGracefulRestartTableTypes(Collections.emptyList());
135
136         this.adjRibInWriter = AdjRibInWriter.create(this.rib.getYangRibId(), PeerRole.Internal, this.writerChain);
137         final RIBSupportContextRegistry context = this.rib.getRibSupportContext();
138         final RegisterAppPeerListener registerAppPeerListener = () -> {
139             synchronized (this) {
140                 if (this.chain != null) {
141                     this.registration = dataTreeChangeService.registerDataTreeChangeListener(appPeerDOMId, this);
142                 }
143             }
144         };
145         this.adjRibInWriter = this.adjRibInWriter.transform(this.peerId, context, localTables, Collections.emptyMap(),
146                 registerAppPeerListener);
147         this.effectiveRibInWriter = EffectiveRibInWriter
148                 .create(this.rib.getService(), this.rib.createPeerChain(this), this.peerIId,
149                 this.rib.getImportPolicyPeerTracker(), context, PeerRole.Internal,
150                 localTables);
151         this.bgpSessionState.registerMessagesCounter(this);
152         this.trackerRegistration = this.rib.getPeerTracker().registerPeer(this);
153     }
154
155     /**
156      * Routes come from application RIB that is identified by (configurable) name.
157      * Each route is pushed into AdjRibsInWriter with it's whole context. In this
158      * method, it doesn't matter if the routes are removed or added, this will
159      * be determined in LocRib.
160      */
161     @Override
162     public synchronized void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
163         if (this.chain == null) {
164             LOG.trace("Skipping data changed called to Application Peer. Change : {}", changes);
165             return;
166         }
167         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
168         LOG.debug("Received data change to ApplicationRib {}", changes);
169         for (final DataTreeCandidate tc : changes) {
170             LOG.debug("Modification Type {}", tc.getRootNode().getModificationType());
171             final YangInstanceIdentifier path = tc.getRootPath();
172             final PathArgument lastArg = path.getLastPathArgument();
173             Verify.verify(lastArg instanceof NodeIdentifierWithPredicates,
174                     "Unexpected type %s in path %s", lastArg.getClass(), path);
175             final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
176             if (!this.supportedTables.contains(tableKey)) {
177                 LOG.trace("Skipping received data change for non supported family {}.", tableKey);
178                 continue;
179             }
180             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
181                 final PathArgument childIdentifier = child.getIdentifier();
182                 final YangInstanceIdentifier tableId = this.adjRibsInId.node(tableKey).node(childIdentifier);
183                 switch (child.getModificationType()) {
184                     case DELETE:
185                         LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
186                         tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
187                         break;
188                     case UNMODIFIED:
189                         // No-op
190                         break;
191                     case SUBTREE_MODIFIED:
192                         if (EffectiveRibInWriter.TABLE_ROUTES.equals(childIdentifier)) {
193                             processRoutesTable(child, tableId, tx, tableId);
194                             break;
195                         }
196                     case WRITE:
197                         if (child.getDataAfter().isPresent()) {
198                             final NormalizedNode<?, ?> dataAfter = child.getDataAfter().get();
199                             LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
200                             LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
201                             tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
202                         }
203                         break;
204                     default:
205                         break;
206                 }
207             }
208         }
209         tx.submit();
210     }
211
212     private synchronized void processRoutesTable(final DataTreeCandidateNode node,
213             final YangInstanceIdentifier identifier, final DOMDataWriteTransaction tx,
214             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     // FIXME ListenableFuture<?> should be used once closeServiceInstance uses wildcard too
252     @Override
253     public synchronized ListenableFuture<Void> close() {
254         setActive(false);
255         if (this.registration != null) {
256             this.registration.close();
257             this.registration = null;
258         }
259         if (this.effectiveRibInWriter != null) {
260             this.effectiveRibInWriter.close();
261         }
262         final ListenableFuture<Void> future;
263         if (this.adjRibInWriter != null) {
264             future = this.adjRibInWriter.removePeer();
265         } else {
266             future = Futures.immediateFuture(null);
267         }
268         if (this.chain != null) {
269             this.chain.close();
270             this.chain = null;
271         }
272         if (this.writerChain != null) {
273             this.writerChain.close();
274             this.writerChain = null;
275         }
276         if (this.trackerRegistration != null) {
277             this.trackerRegistration.close();
278             this.trackerRegistration = null;
279         }
280         return future;
281     }
282
283     @Override
284     public byte[] getRawIdentifier() {
285         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
286     }
287
288     @Override
289     public PeerId getPeerId() {
290         return this.peerId;
291     }
292
293     @Override
294     public boolean supportsAddPathSupported(final TablesKey tableKey) {
295         return false;
296     }
297
298     @Override
299     public SendReceive getSupportedAddPathTables(final TablesKey tableKey) {
300         return null;
301     }
302
303     @Override
304     public boolean supportsTable(final TablesKey tableKey) {
305         return this.rib.supportsTable(tableKey);
306     }
307
308     @Override
309     public YangInstanceIdentifier getPeerRibInstanceIdentifier() {
310         return this.peerIId;
311     }
312
313     @Override
314     public PeerRole getRole() {
315         return PeerRole.Internal;
316     }
317
318     @Override
319     public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
320         final AsyncTransaction<?, ?> transaction, final Throwable cause) {
321         LOG.error("Transaction chain {} failed.", transaction != null ? transaction.getIdentifier() : null, cause);
322     }
323
324     @Override
325     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
326         LOG.debug("Transaction chain {} successful.", chain);
327     }
328
329     @Override
330     public BGPErrorHandlingState getBGPErrorHandlingState() {
331         return this;
332     }
333
334     @Override
335     public BGPAfiSafiState getBGPAfiSafiState() {
336         return this;
337     }
338
339     @Override
340     public BGPSessionState getBGPSessionState() {
341         return this.bgpSessionState;
342     }
343
344     @Override
345     public BGPTimersState getBGPTimersState() {
346         return this.bgpSessionState;
347     }
348
349     @Override
350     public BGPTransportState getBGPTransportState() {
351         return this.bgpSessionState;
352     }
353 }