Clean up
[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.Optional;
21 import java.util.Set;
22 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
25 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
26 import org.opendaylight.controller.md.sal.dom.api.ClusteredDOMDataTreeChangeListener;
27 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
28 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
29 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
30 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
31 import org.opendaylight.protocol.bgp.rib.impl.spi.RIB;
32 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
33 import org.opendaylight.protocol.bgp.rib.impl.state.BGPPeerStateImpl;
34 import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl;
35 import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker;
36 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
37 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
38 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
39 import org.opendaylight.protocol.bgp.rib.spi.state.BGPAfiSafiState;
40 import org.opendaylight.protocol.bgp.rib.spi.state.BGPErrorHandlingState;
41 import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
42 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
43 import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
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.rib.rev130925.ApplicationRibId;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.SimpleRoutingPolicy;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.AdjRibIn;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.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
96     @FunctionalInterface
97     interface RegisterAppPeerListener {
98         /**
99          * Register Application Peer Change Listener once AdjRibIn has been successfully initialized.
100          */
101         void register();
102     }
103
104     public ApplicationPeer(final ApplicationRibId applicationRibId, final Ipv4Address ipAddress, final RIB rib) {
105         super(rib.getInstanceIdentifier(), "application-peers", new IpAddress(ipAddress),
106                 rib.getLocalTablesKeys(), Collections.emptySet());
107         this.name = applicationRibId.getValue();
108         final RIB targetRib = requireNonNull(rib);
109         this.rawIdentifier = InetAddresses.forString(ipAddress.getValue()).getAddress();
110         final NodeIdentifierWithPredicates peerId = IdentifierUtils.domPeerId(RouterIds.createPeerId(ipAddress));
111         this.peerIId = targetRib.getYangRibId().node(Peer.QNAME).node(peerId);
112         this.adjRibsInId = this.peerIId.node(AdjRibIn.QNAME).node(Tables.QNAME);
113         this.rib = targetRib;
114         this.ipAddress = ipAddress;
115     }
116
117     public synchronized void instantiateServiceInstance(final DOMDataTreeChangeService dataTreeChangeService,
118             final DOMDataTreeIdentifier appPeerDOMId) {
119         setActive(true);
120         this.chain = this.rib.createPeerChain(this);
121         this.writerChain = this.rib.createPeerChain(this);
122
123         final Optional<SimpleRoutingPolicy> simpleRoutingPolicy = Optional.of(SimpleRoutingPolicy.AnnounceNone);
124         final PeerId peerId = RouterIds.createPeerId(this.ipAddress);
125         final Set<TablesKey> localTables = this.rib.getLocalTablesKeys();
126         localTables.forEach(tablesKey -> {
127             final ExportPolicyPeerTracker exportTracker = this.rib.getExportPolicyPeerTracker(tablesKey);
128             if (exportTracker != null) {
129                 exportTracker.registerPeer(peerId, null, this.peerIId, PeerRole.Internal, simpleRoutingPolicy);
130             }
131             this.supportedTables.add(RibSupportUtils.toYangTablesKey(tablesKey));
132         });
133         setAdvertizedGracefulRestartTableTypes(Collections.emptyList());
134
135         this.adjRibInWriter = AdjRibInWriter.create(this.rib.getYangRibId(), PeerRole.Internal, simpleRoutingPolicy,
136                 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(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     }
153
154     /**
155      * Routes come from application RIB that is identified by (configurable) name.
156      * Each route is pushed into AdjRibsInWriter with it's whole context. In this
157      * method, it doesn't matter if the routes are removed or added, this will
158      * be determined in LocRib.
159      */
160     @Override
161     public synchronized void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
162         if (this.chain == null) {
163             LOG.trace("Skipping data changed called to Application Peer. Change : {}", changes);
164             return;
165         }
166         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
167         LOG.debug("Received data change to ApplicationRib {}", changes);
168         for (final DataTreeCandidate tc : changes) {
169             LOG.debug("Modification Type {}", tc.getRootNode().getModificationType());
170             final YangInstanceIdentifier path = tc.getRootPath();
171             final PathArgument lastArg = path.getLastPathArgument();
172             Verify.verify(lastArg instanceof NodeIdentifierWithPredicates,
173                     "Unexpected type %s in path %s", lastArg.getClass(), path);
174             final NodeIdentifierWithPredicates tableKey = (NodeIdentifierWithPredicates) lastArg;
175             if (!this.supportedTables.contains(tableKey)) {
176                 LOG.trace("Skipping received data change for non supported family {}.", tableKey);
177                 continue;
178             }
179             for (final DataTreeCandidateNode child : tc.getRootNode().getChildNodes()) {
180                 final PathArgument childIdentifier = child.getIdentifier();
181                 final YangInstanceIdentifier tableId = this.adjRibsInId.node(tableKey).node(childIdentifier);
182                 switch (child.getModificationType()) {
183                     case DELETE:
184                         LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
185                         tx.delete(LogicalDatastoreType.OPERATIONAL, tableId);
186                         break;
187                     case UNMODIFIED:
188                         // No-op
189                         break;
190                     case SUBTREE_MODIFIED:
191                         if (EffectiveRibInWriter.TABLE_ROUTES.equals(childIdentifier)) {
192                             processRoutesTable(child, tableId, tx, tableId);
193                             break;
194                         }
195                     case WRITE:
196                         if (child.getDataAfter().isPresent()) {
197                             final NormalizedNode<?, ?> dataAfter = child.getDataAfter().get();
198                             LOG.trace("App peer -> AdjRibsIn path : {}", tableId);
199                             LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
200                             tx.put(LogicalDatastoreType.OPERATIONAL, tableId, dataAfter);
201                         }
202                         break;
203                     default:
204                         break;
205                 }
206             }
207         }
208         tx.submit();
209     }
210
211     /**
212      * Applies modification under table routes based on modification type instead of only put. BUG 4438
213      *
214      * @param node
215      * @param identifier
216      * @param tx
217      * @param routeTableIdentifier
218      */
219     private synchronized void processRoutesTable(final DataTreeCandidateNode node,
220             final YangInstanceIdentifier identifier, final DOMDataWriteTransaction tx,
221             final YangInstanceIdentifier routeTableIdentifier) {
222         for (final DataTreeCandidateNode child : node.getChildNodes()) {
223             final YangInstanceIdentifier childIdentifier = identifier.node(child.getIdentifier());
224             switch (child.getModificationType()) {
225                 case DELETE:
226                     LOG.trace("App peer -> AdjRibsIn path delete: {}", childIdentifier);
227                     tx.delete(LogicalDatastoreType.OPERATIONAL, childIdentifier);
228                     break;
229                 case UNMODIFIED:
230                     // No-op
231                     break;
232                 case SUBTREE_MODIFIED:
233                     //For be ables to use DELETE when we remove specific routes as we do when we remove the whole routes,
234                     // we need to go deeper three levels
235                     if (!routeTableIdentifier.equals(childIdentifier.getParent().getParent().getParent())) {
236                         processRoutesTable(child, childIdentifier, tx, routeTableIdentifier);
237                         break;
238                     }
239                 case WRITE:
240                     if (child.getDataAfter().isPresent()) {
241                         final NormalizedNode<?, ?> dataAfter = child.getDataAfter().get();
242                         LOG.trace("App peer -> AdjRibsIn path : {}", childIdentifier);
243                         LOG.trace("App peer -> AdjRibsIn data : {}", dataAfter);
244                         tx.put(LogicalDatastoreType.OPERATIONAL, childIdentifier, dataAfter);
245                     }
246                     break;
247                 default:
248                     break;
249             }
250         }
251     }
252
253     @Override
254     public String getName() {
255         return this.name;
256     }
257
258     // FIXME ListenableFuture<?> should be used once closeServiceInstance uses wildcard too
259     @Override
260     public synchronized ListenableFuture<Void> close() {
261         setActive(false);
262         if (this.registration != null) {
263             this.registration.close();
264             this.registration = null;
265         }
266         if (this.effectiveRibInWriter != null) {
267             this.effectiveRibInWriter.close();
268         }
269         final ListenableFuture<Void> future;
270         if (this.adjRibInWriter != null) {
271             future = this.adjRibInWriter.removePeer();
272         } else {
273             future = Futures.immediateFuture(null);
274         }
275         if (this.chain != null) {
276             this.chain.close();
277             this.chain = null;
278         }
279         if (this.writerChain != null) {
280             this.writerChain.close();
281             this.writerChain = null;
282         }
283         return future;
284     }
285
286     @Override
287     public byte[] getRawIdentifier() {
288         return Arrays.copyOf(this.rawIdentifier, this.rawIdentifier.length);
289     }
290
291     @Override
292     public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
293             final AsyncTransaction<?, ?> transaction, final Throwable cause) {
294         LOG.error("Transaction chain {} failed.", transaction != null ? transaction.getIdentifier() : null, cause);
295     }
296
297     @Override
298     public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
299         LOG.debug("Transaction chain {} successful.", chain);
300     }
301
302     @Override
303     public BGPErrorHandlingState getBGPErrorHandlingState() {
304         return this;
305     }
306
307     @Override
308     public BGPAfiSafiState getBGPAfiSafiState() {
309         return this;
310     }
311
312     @Override
313     public BGPSessionState getBGPSessionState() {
314         return this.bgpSessionState;
315     }
316
317     @Override
318     public BGPTimersState getBGPTimersState() {
319         return this.bgpSessionState;
320     }
321
322     @Override
323     public BGPTransportState getBGPTransportState() {
324         return this.bgpSessionState;
325     }
326 }