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