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