3cbd173c11b78eaa91231ea076e590824f3bb973
[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 DOMTransactionChain chain;
69     private final ExportPolicyPeerTracker exportPolicyPeerTracker;
70     private final NodeIdentifier attributesIdentifier;
71     private final Long ourAs;
72     private final RIBSupport ribSupport;
73     private final TablesKey localTablesKey;
74     private final ListenerRegistration<LocRibWriter> reg;
75     private final PathSelectionMode pathSelectionMode;
76     private final UnsignedInt32Counter routeCounter;
77
78     private LocRibWriter(final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier target,
79         final Long ourAs, final DOMDataTreeChangeService service, final ExportPolicyPeerTracker exportPolicyPeerTracker, final TablesKey tablesKey,
80         @Nonnull final PathSelectionMode pathSelectionMode, final UnsignedInt32Counter routeCounter) {
81         this.chain = Preconditions.checkNotNull(chain);
82         final NodeIdentifierWithPredicates tableKey = RibSupportUtils.toYangTablesKey(tablesKey);
83         this.localTablesKey = tablesKey;
84         this.locRibTarget = YangInstanceIdentifier.create(target.node(LocRib.QNAME).node(Tables.QNAME).node(tableKey).getPathArguments());
85         this.ourAs = Preconditions.checkNotNull(ourAs);
86         this.ribSupport = registry.getRIBSupportContext(tablesKey).getRibSupport();
87         this.attributesIdentifier = this.ribSupport.routeAttributesIdentifier();
88         this.exportPolicyPeerTracker = exportPolicyPeerTracker;
89         this.pathSelectionMode = pathSelectionMode;
90         this.routeCounter = routeCounter;
91
92         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
93         tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Routes.QNAME), this.ribSupport.emptyRoutes());
94         tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
95         tx.submit();
96
97         final YangInstanceIdentifier tableId = target.node(Peer.QNAME).node(Peer.QNAME).node(EffectiveRibIn.QNAME).node(Tables.QNAME).node(tableKey);
98         final DOMDataTreeIdentifier wildcard = new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, tableId);
99         this.reg = service.registerDataTreeChangeListener(wildcard, this);
100     }
101
102     public static LocRibWriter create(@Nonnull final RIBSupportContextRegistry registry, @Nonnull final TablesKey tablesKey, @Nonnull final DOMTransactionChain chain,
103         @Nonnull final YangInstanceIdentifier target, @Nonnull final AsNumber ourAs, @Nonnull final DOMDataTreeChangeService service, @Nonnull final ExportPolicyPeerTracker ep,
104         @Nonnull final PathSelectionMode pathSelectionStrategy, @Nonnull final UnsignedInt32Counter routeCounter) {
105         return new LocRibWriter(registry, chain, target, ourAs.getValue(), service, ep, tablesKey, pathSelectionStrategy, routeCounter);
106     }
107
108     @Override
109     public void close() {
110         this.reg.close();
111         // FIXME: wait for the chain to close? unfortunately RIBImpl is the listener, so that may require some work
112         this.chain.close();
113     }
114
115     @Nonnull
116     private RouteEntry createEntry(final PathArgument routeId) {
117         final RouteEntry ret = this.pathSelectionMode.createRouteEntry(ribSupport.isComplexRoute());
118         this.routeEntries.put(routeId, ret);
119         LOG.trace("Created new entry for {}", routeId);
120         return ret;
121     }
122
123     /**
124      * We use two-stage processing here in hopes that we avoid duplicate
125      * calculations when multiple peers have changed a particular entry.
126      *
127      * @param changes on supported table
128      */
129     @Override
130     public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
131         LOG.trace("Received data change {} to LocRib {}", changes, this);
132
133         final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
134         try {
135             final Map<RouteUpdateKey, RouteEntry> toUpdate = update(tx, changes);
136
137             if (!toUpdate.isEmpty()) {
138                 walkThrough(tx, toUpdate.entrySet());
139             }
140         } catch (final Exception e) {
141             LOG.error("Failed to completely propagate updates {}, state is undefined", changes, e);
142         } finally {
143             tx.submit();
144         }
145     }
146
147     private Map<RouteUpdateKey, RouteEntry> update(final DOMDataWriteTransaction tx, final Collection<DataTreeCandidate> changes) {
148         final Map<RouteUpdateKey, RouteEntry> ret = new HashMap<>();
149         changes.forEach(tc -> {
150             final DataTreeCandidateNode table = tc.getRootNode();
151             final YangInstanceIdentifier rootPath = tc.getRootPath();
152             final PeerId peerId = IdentifierUtils.peerKeyToPeerId(rootPath);
153             initializeTableWithExistentRoutes(table, peerId, rootPath, tx);
154             updateNodes(table, peerId, tx, ret);
155         });
156         return ret;
157     }
158
159     private void initializeTableWithExistentRoutes(final DataTreeCandidateNode table, final PeerId peerIdOfNewPeer, final YangInstanceIdentifier rootPath,
160         final DOMDataWriteTransaction tx) {
161         if (!table.getDataBefore().isPresent() && this.exportPolicyPeerTracker.isTableSupported(peerIdOfNewPeer)) {
162             LOG.debug("Peer {} table has been created, inserting existent routes", peerIdOfNewPeer);
163             final PeerRole newPeerRole = this.exportPolicyPeerTracker.getRole(IdentifierUtils.peerPath(rootPath));
164             final PeerExportGroup peerGroup = this.exportPolicyPeerTracker.getPeerGroup(newPeerRole);
165             this.routeEntries.entrySet().forEach(entry -> entry.getValue().writeRoute(peerIdOfNewPeer, entry.getKey(),
166                 rootPath.getParent().getParent().getParent(), peerGroup, this.localTablesKey, this.exportPolicyPeerTracker, this.ribSupport, tx));
167         }
168     }
169
170     private void updateNodes(final DataTreeCandidateNode table, final PeerId peerId, final DOMDataWriteTransaction tx,
171         final Map<RouteUpdateKey, RouteEntry> routes) {
172         for (final DataTreeCandidateNode child : table.getChildNodes()) {
173             LOG.debug("Modification type {}", child.getModificationType());
174             if ((Attributes.QNAME).equals(child.getIdentifier().getNodeType())) {
175                 if (child.getDataAfter().isPresent()) {
176                     // putting uptodate attribute in
177                     LOG.trace("Uptodate found for {}", child.getDataAfter());
178                     tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(child.getIdentifier()), child.getDataAfter().get());
179                 }
180                 continue;
181             }
182             updateRoutesEntries(child, peerId, routes);
183         }
184     }
185
186     private void updateRoutesEntries(final DataTreeCandidateNode child, final PeerId peerId, final Map<RouteUpdateKey, RouteEntry> routes) {
187         final UnsignedInteger routerId = RouterIds.routerIdForPeerId(peerId);
188         final Collection<DataTreeCandidateNode> modifiedRoutes = this.ribSupport.changedRoutes(child);
189         for (final DataTreeCandidateNode route : modifiedRoutes) {
190             final PathArgument routeId = this.ribSupport.createRouteKeyPathArgument(route.getIdentifier());
191             RouteEntry entry = this.routeEntries.get(routeId);
192             final Optional<NormalizedNode<?, ?>> maybeData = route.getDataAfter();
193             final Optional<NormalizedNode<?, ?>> maybeDataBefore = route.getDataBefore();
194             if (maybeData.isPresent()) {
195                 if (entry == null) {
196                     entry = createEntry(routeId);
197                 }
198                 entry.addRoute(routerId, this.ribSupport.extractPathId(maybeData.get()), this.attributesIdentifier, maybeData.get());
199             } else if (entry != null && entry.removeRoute(routerId, this.ribSupport.extractPathId(maybeDataBefore.get()))) {
200                 this.routeEntries.remove(routeId);
201                 LOG.trace("Removed route from {}", routerId);
202             }
203             final RouteUpdateKey routeUpdateKey = new RouteUpdateKey(peerId, routeId);
204             LOG.debug("Updated route {} entry {}", routeId, entry);
205             routes.put(routeUpdateKey, entry);
206         }
207         updateRouteCounter();
208     }
209
210     /**
211      * Update the statistic of loc-rib route
212      */
213     private void updateRouteCounter() {
214         routeCounter.setCount(this.routeEntries.size());
215     }
216
217     private void walkThrough(final DOMDataWriteTransaction tx, final Set<Map.Entry<RouteUpdateKey, RouteEntry>> toUpdate) {
218         for (final Map.Entry<RouteUpdateKey, RouteEntry> e : toUpdate) {
219             LOG.trace("Walking through {}", e);
220             final RouteEntry entry = e.getValue();
221
222             if (!entry.selectBest(this.ourAs)) {
223                 LOG.trace("Best path has not changed, continuing");
224                 continue;
225             }
226             entry.updateRoute(this.localTablesKey, this.exportPolicyPeerTracker, this.locRibTarget, this.ribSupport, tx, e.getKey().getRouteId());
227         }
228     }
229 }