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