Bump versions by x.y.(z+1)
[bgpcep.git] / bgp / rib-impl / src / main / java / org / opendaylight / protocol / bgp / rib / impl / LocRibWriter.java
1 /*
2  * Copyright (c) 2015 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.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.primitives.UnsignedInteger;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.Map;
16 import java.util.Set;
17 import javax.annotation.Nonnull;
18 import javax.annotation.concurrent.NotThreadSafe;
19 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
20 import org.opendaylight.controller.md.sal.dom.api.ClusteredDOMDataTreeChangeListener;
21 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
22 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
23 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
24 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
25 import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode;
26 import org.opendaylight.protocol.bgp.mode.api.RouteEntry;
27 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
28 import org.opendaylight.protocol.bgp.rib.impl.stats.UnsignedInt32Counter;
29 import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker;
30 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
31 import org.opendaylight.protocol.bgp.rib.spi.PeerExportGroup;
32 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
33 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
34 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
35 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.LocRib;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.EffectiveRibIn;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Attributes;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Routes;
45 import org.opendaylight.yangtools.concepts.ListenerRegistration;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
51 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
54 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
55 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 @NotThreadSafe
60 final class LocRibWriter implements AutoCloseable, ClusteredDOMDataTreeChangeListener {
61
62     private static final Logger LOG = LoggerFactory.getLogger(LocRibWriter.class);
63
64     private static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_TRUE = ImmutableNodes.leafNode(QName.create(Attributes.QNAME, "uptodate"), Boolean.TRUE);
65
66     private final Map<PathArgument, RouteEntry> routeEntries = new HashMap<>();
67     private final YangInstanceIdentifier locRibTarget;
68     private final NodeIdentifierWithPredicates tableKey;
69     private DOMTransactionChain chain;
70     private final ExportPolicyPeerTracker exportPolicyPeerTracker;
71     private final NodeIdentifier attributesIdentifier;
72     private final Long ourAs;
73     private final RIBSupport ribSupport;
74     private final TablesKey localTablesKey;
75     private final YangInstanceIdentifier target;
76     private final DOMDataTreeChangeService service;
77     private ListenerRegistration<LocRibWriter> reg;
78     private final PathSelectionMode pathSelectionMode;
79     private final UnsignedInt32Counter routeCounter;
80
81     private LocRibWriter(final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier target,
82         final Long ourAs, final DOMDataTreeChangeService service, final ExportPolicyPeerTracker exportPolicyPeerTracker, final TablesKey tablesKey,
83         @Nonnull final PathSelectionMode pathSelectionMode, final UnsignedInt32Counter routeCounter) {
84         this.chain = Preconditions.checkNotNull(chain);
85         this.target = Preconditions.checkNotNull(target);
86         final NodeIdentifierWithPredicates tableKey = RibSupportUtils.toYangTablesKey(tablesKey);
87         this.localTablesKey = tablesKey;
88         this.tableKey = tableKey;
89         this.locRibTarget = YangInstanceIdentifier.create(target.node(LocRib.QNAME).node(Tables.QNAME).node(tableKey).getPathArguments());
90         this.ourAs = Preconditions.checkNotNull(ourAs);
91         this.service = Preconditions.checkNotNull(service);
92         this.ribSupport = registry.getRIBSupportContext(tablesKey).getRibSupport();
93         this.attributesIdentifier = this.ribSupport.routeAttributesIdentifier();
94         this.exportPolicyPeerTracker = exportPolicyPeerTracker;
95         this.pathSelectionMode = pathSelectionMode;
96         this.routeCounter = routeCounter;
97
98         init();
99     }
100
101     private synchronized void init() {
102         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
103         tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Routes.QNAME), this.ribSupport.emptyRoutes());
104         tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Attributes.QNAME)
105             .node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
106         tx.submit();
107
108         final YangInstanceIdentifier tableId = this.target.node(Peer.QNAME).node(Peer.QNAME).node(EffectiveRibIn.QNAME)
109             .node(Tables.QNAME).node(this.tableKey);
110         final DOMDataTreeIdentifier wildcard = new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, tableId);
111         this.reg = this.service.registerDataTreeChangeListener(wildcard, this);
112     }
113
114     public static LocRibWriter create(@Nonnull final RIBSupportContextRegistry registry, @Nonnull final TablesKey tablesKey, @Nonnull final DOMTransactionChain chain,
115         @Nonnull final YangInstanceIdentifier target, @Nonnull final AsNumber ourAs, @Nonnull final DOMDataTreeChangeService service, @Nonnull final ExportPolicyPeerTracker ep,
116         @Nonnull final PathSelectionMode pathSelectionStrategy, @Nonnull final UnsignedInt32Counter routeCounter) {
117         return new LocRibWriter(registry, chain, target, ourAs.getValue(), service, ep, tablesKey, pathSelectionStrategy, routeCounter);
118     }
119
120     /**
121      * Re-initialize this LocRibWriter with new transaction chain.
122      *
123      * @param newChain new transaction chain
124      */
125     synchronized void restart(@Nonnull final DOMTransactionChain newChain) {
126         Preconditions.checkNotNull(newChain);
127         close();
128         this.chain = newChain;
129         init();
130     }
131
132     @Override
133     public void close() {
134         this.reg.close();
135         this.reg = null;
136         this.chain.close();
137     }
138
139     @Nonnull
140     private RouteEntry createEntry(final PathArgument routeId) {
141         final RouteEntry ret = this.pathSelectionMode.createRouteEntry(ribSupport.isComplexRoute());
142         this.routeEntries.put(routeId, ret);
143         LOG.trace("Created new entry for {}", routeId);
144         return ret;
145     }
146
147     /**
148      * We use two-stage processing here in hopes that we avoid duplicate
149      * calculations when multiple peers have changed a particular entry.
150      *
151      * @param changes on supported table
152      */
153     @Override
154     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
155         LOG.trace("Received data change {} to LocRib {}", changes, this);
156
157         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
158         try {
159             final Map<RouteUpdateKey, RouteEntry> toUpdate = update(tx, changes);
160
161             if (!toUpdate.isEmpty()) {
162                 walkThrough(tx, toUpdate.entrySet());
163             }
164         } catch (final Exception e) {
165             LOG.error("Failed to completely propagate updates {}, state is undefined", changes, e);
166         } finally {
167             tx.submit();
168         }
169     }
170
171     private Map<RouteUpdateKey, RouteEntry> update(final DOMDataWriteTransaction tx, final Collection<DataTreeCandidate> changes) {
172         final Map<RouteUpdateKey, RouteEntry> ret = new HashMap<>();
173         changes.forEach(tc -> {
174             final DataTreeCandidateNode table = tc.getRootNode();
175             final YangInstanceIdentifier rootPath = tc.getRootPath();
176             final PeerId peerId = IdentifierUtils.peerKeyToPeerId(rootPath);
177             initializeTableWithExistentRoutes(table, peerId, rootPath, tx);
178             updateNodes(table, peerId, tx, ret);
179         });
180         return ret;
181     }
182
183     private void initializeTableWithExistentRoutes(final DataTreeCandidateNode table, final PeerId peerIdOfNewPeer, final YangInstanceIdentifier rootPath,
184         final DOMDataWriteTransaction tx) {
185         if (!table.getDataBefore().isPresent() && this.exportPolicyPeerTracker.isTableSupported(peerIdOfNewPeer)) {
186             LOG.debug("Peer {} table has been created, inserting existent routes", peerIdOfNewPeer);
187             final PeerRole newPeerRole = this.exportPolicyPeerTracker.getRole(IdentifierUtils.peerPath(rootPath));
188             final PeerExportGroup peerGroup = this.exportPolicyPeerTracker.getPeerGroup(newPeerRole);
189             this.routeEntries.entrySet().forEach(entry -> entry.getValue().writeRoute(peerIdOfNewPeer, entry.getKey(),
190                 rootPath.getParent().getParent().getParent(), peerGroup, this.localTablesKey, this.exportPolicyPeerTracker, this.ribSupport, tx));
191         }
192     }
193
194     private void updateNodes(final DataTreeCandidateNode table, final PeerId peerId, final DOMDataWriteTransaction tx,
195         final Map<RouteUpdateKey, RouteEntry> routes) {
196         for (final DataTreeCandidateNode child : table.getChildNodes()) {
197             LOG.debug("Modification type {}", child.getModificationType());
198             if ((Attributes.QNAME).equals(child.getIdentifier().getNodeType())) {
199                 if (child.getDataAfter().isPresent()) {
200                     // putting uptodate attribute in
201                     LOG.trace("Uptodate found for {}", child.getDataAfter());
202                     tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(child.getIdentifier()), child.getDataAfter().get());
203                 }
204                 continue;
205             }
206             updateRoutesEntries(child, peerId, routes);
207         }
208     }
209
210     private void updateRoutesEntries(final DataTreeCandidateNode child, final PeerId peerId, final Map<RouteUpdateKey, RouteEntry> routes) {
211         final UnsignedInteger routerId = RouterIds.routerIdForPeerId(peerId);
212         final Collection<DataTreeCandidateNode> modifiedRoutes = this.ribSupport.changedRoutes(child);
213         for (final DataTreeCandidateNode route : modifiedRoutes) {
214             final PathArgument routeId = this.ribSupport.createRouteKeyPathArgument(route.getIdentifier());
215             RouteEntry entry = this.routeEntries.get(routeId);
216             final Optional<NormalizedNode<?, ?>> maybeData = route.getDataAfter();
217             final Optional<NormalizedNode<?, ?>> maybeDataBefore = route.getDataBefore();
218             if (maybeData.isPresent()) {
219                 if (entry == null) {
220                     entry = createEntry(routeId);
221                 }
222                 entry.addRoute(routerId, this.ribSupport.extractPathId(maybeData.get()), this.attributesIdentifier, maybeData.get());
223             } else if (entry != null && entry.removeRoute(routerId, this.ribSupport.extractPathId(maybeDataBefore.get()))) {
224                 this.routeEntries.remove(routeId);
225                 LOG.trace("Removed route from {}", routerId);
226             }
227             final RouteUpdateKey routeUpdateKey = new RouteUpdateKey(peerId, routeId);
228             LOG.debug("Updated route {} entry {}", routeId, entry);
229             routes.put(routeUpdateKey, entry);
230         }
231         updateRouteCounter();
232     }
233
234     /**
235      * Update the statistic of loc-rib route
236      */
237     private void updateRouteCounter() {
238         routeCounter.setCount(this.routeEntries.size());
239     }
240
241     private void walkThrough(final DOMDataWriteTransaction tx, final Set<Map.Entry<RouteUpdateKey, RouteEntry>> toUpdate) {
242         for (final Map.Entry<RouteUpdateKey, RouteEntry> e : toUpdate) {
243             LOG.trace("Walking through {}", e);
244             final RouteEntry entry = e.getValue();
245
246             if (!entry.selectBest(this.ourAs)) {
247                 LOG.trace("Best path has not changed, continuing");
248                 continue;
249             }
250             entry.updateRoute(this.localTablesKey, this.exportPolicyPeerTracker, this.locRibTarget, this.ribSupport, tx, e.getKey().getRouteId());
251         }
252     }
253 }