2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.bgp.rib.impl;
10 import static org.opendaylight.protocol.bgp.rib.impl.AdjRibInWriter.SIMPLE_ROUTING_POLICY_NID;
11 import static org.opendaylight.protocol.bgp.rib.spi.PeerRoleUtil.PEER_ROLE_NID;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.primitives.UnsignedInteger;
16 import java.util.Collection;
17 import java.util.HashMap;
19 import javax.annotation.Nonnull;
20 import javax.annotation.concurrent.NotThreadSafe;
21 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
22 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
23 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeService;
24 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeIdentifier;
25 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
26 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
27 import org.opendaylight.protocol.bgp.mode.api.PathSelectionMode;
28 import org.opendaylight.protocol.bgp.mode.api.RouteEntry;
29 import org.opendaylight.protocol.bgp.rib.impl.spi.RIBSupportContextRegistry;
30 import org.opendaylight.protocol.bgp.rib.impl.stats.UnsignedInt32Counter;
31 import org.opendaylight.protocol.bgp.rib.spi.CacheDisconnectedPeers;
32 import org.opendaylight.protocol.bgp.rib.spi.ExportPolicyPeerTracker;
33 import org.opendaylight.protocol.bgp.rib.spi.IdentifierUtils;
34 import org.opendaylight.protocol.bgp.rib.spi.PeerExportGroup;
35 import org.opendaylight.protocol.bgp.rib.spi.PeerRoleUtil;
36 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
37 import org.opendaylight.protocol.bgp.rib.spi.RibSupportUtils;
38 import org.opendaylight.protocol.bgp.rib.spi.RouterIds;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerId;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.PeerRole;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.SimpleRoutingPolicy;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.LocRib;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.Peer;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.EffectiveRibIn;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.bgp.rib.rib.peer.SupportedTables;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.Tables;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Attributes;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.tables.Routes;
51 import org.opendaylight.yangtools.concepts.ListenerRegistration;
52 import org.opendaylight.yangtools.yang.binding.BindingMapping;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
58 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
61 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
63 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
68 final class LocRibWriter implements AutoCloseable, DOMDataTreeChangeListener {
70 private static final Logger LOG = LoggerFactory.getLogger(LocRibWriter.class);
72 private static final LeafNode<Boolean> ATTRIBUTES_UPTODATE_TRUE = ImmutableNodes.leafNode(QName.create(Attributes.QNAME, "uptodate"), Boolean.TRUE);
73 private static final NodeIdentifier EFFRIBIN_NID = new NodeIdentifier(EffectiveRibIn.QNAME);
74 private static final NodeIdentifier TABLES_NID = new NodeIdentifier(Tables.QNAME);
75 private static final NodeIdentifier PEER_TABLES = new NodeIdentifier(SupportedTables.QNAME);
77 private final Map<PathArgument, RouteEntry> routeEntries = new HashMap<>();
78 private final YangInstanceIdentifier locRibTarget;
79 private final DOMTransactionChain chain;
80 private final ExportPolicyPeerTracker peerPolicyTracker;
81 private final NodeIdentifier attributesIdentifier;
82 private final Long ourAs;
83 private final RIBSupport ribSupport;
84 private final NodeIdentifierWithPredicates tableKey;
85 private final TablesKey localTablesKey;
86 private final ListenerRegistration<LocRibWriter> reg;
87 private final CacheDisconnectedPeers cacheDisconnectedPeers;
88 private final PathSelectionMode pathSelectionMode;
89 private final UnsignedInt32Counter routeCounter;
91 private LocRibWriter(final RIBSupportContextRegistry registry, final DOMTransactionChain chain, final YangInstanceIdentifier target, final Long ourAs,
92 final DOMDataTreeChangeService service, final PolicyDatabase pd, final TablesKey tablesKey, final CacheDisconnectedPeers cacheDisconnectedPeers,
93 @Nonnull final PathSelectionMode pathSelectionMode, final UnsignedInt32Counter routeCounter) {
94 this.chain = Preconditions.checkNotNull(chain);
95 this.tableKey = RibSupportUtils.toYangTablesKey(tablesKey);
96 this.localTablesKey = tablesKey;
97 this.locRibTarget = YangInstanceIdentifier.create(target.node(LocRib.QNAME).node(Tables.QNAME).node(this.tableKey).getPathArguments());
98 this.ourAs = Preconditions.checkNotNull(ourAs);
99 this.ribSupport = registry.getRIBSupportContext(tablesKey).getRibSupport();
100 this.attributesIdentifier = this.ribSupport.routeAttributesIdentifier();
101 this.peerPolicyTracker = new ExportPolicyPeerTrackerImpl(pd, this.localTablesKey);
102 this.cacheDisconnectedPeers = cacheDisconnectedPeers;
103 this.pathSelectionMode = pathSelectionMode;
104 this.routeCounter = routeCounter;
106 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
107 tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Routes.QNAME), this.ribSupport.emptyRoutes());
108 tx.merge(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(Attributes.QNAME).node(ATTRIBUTES_UPTODATE_TRUE.getNodeType()), ATTRIBUTES_UPTODATE_TRUE);
111 final YangInstanceIdentifier tableId = target.node(Peer.QNAME).node(Peer.QNAME);
113 this.reg = service.registerDataTreeChangeListener(new DOMDataTreeIdentifier(LogicalDatastoreType.OPERATIONAL, tableId), this);
116 public static LocRibWriter create(@Nonnull final RIBSupportContextRegistry registry, @Nonnull final TablesKey tablesKey, @Nonnull final DOMTransactionChain chain,
117 @Nonnull final YangInstanceIdentifier target, @Nonnull final AsNumber ourAs, @Nonnull final DOMDataTreeChangeService service, @Nonnull final PolicyDatabase pd,
118 final CacheDisconnectedPeers cacheDisconnectedPeers, @Nonnull final PathSelectionMode pathSelectionStrategy, @Nonnull final UnsignedInt32Counter routeCounter) {
119 return new LocRibWriter(registry, chain, target, ourAs.getValue(), service, pd, tablesKey, cacheDisconnectedPeers, pathSelectionStrategy, routeCounter);
123 public void close() {
125 // FIXME: wait for the chain to close? unfortunately RIBImpl is the listener, so that may require some work
130 private RouteEntry createEntry(final PathArgument routeId) {
131 final RouteEntry ret = this.pathSelectionMode.createRouteEntry(ribSupport.isComplexRoute());
132 this.routeEntries.put(routeId, ret);
133 LOG.trace("Created new entry for {}", routeId);
138 public void onDataTreeChanged(final Collection<DataTreeCandidate> changes) {
139 LOG.trace("Received data change {} to LocRib {}", changes, this);
141 final DOMDataWriteTransaction tx = this.chain.newWriteOnlyTransaction();
144 * We use two-stage processing here in hopes that we avoid duplicate
145 * calculations when multiple peers have changed a particular entry.
147 final Map<RouteUpdateKey, RouteEntry> toUpdate = update(tx, changes);
149 // Now walk all updated entries
150 walkThrough(tx, toUpdate);
151 } catch (final Exception e) {
152 LOG.error("Failed to completely propagate updates {}, state is undefined", changes, e);
158 private Map<RouteUpdateKey, RouteEntry> update(final DOMDataWriteTransaction tx, final Collection<DataTreeCandidate> changes) {
159 final Map<RouteUpdateKey, RouteEntry> ret = new HashMap<>();
161 for (final DataTreeCandidate tc : changes) {
162 final YangInstanceIdentifier rootPath = tc.getRootPath();
163 final DataTreeCandidateNode rootNode = tc.getRootNode();
164 final PeerId peerId = IdentifierUtils.peerKeyToPeerId(rootPath);
166 filterOutPeerRole(peerId, rootNode, rootPath);
167 filterOutChangesToSupportedTables(peerId, rootNode);
168 filterOutAnyChangeOutsideEffRibsIn(peerId, rootNode, ret, rootPath, tx);
174 private void filterOutAnyChangeOutsideEffRibsIn(final PeerId peerId, final DataTreeCandidateNode rootNode,
175 final Map<RouteUpdateKey, RouteEntry> ret, final YangInstanceIdentifier rootPath, final DOMDataWriteTransaction tx) {
176 final DataTreeCandidateNode ribIn = rootNode.getModifiedChild(EFFRIBIN_NID);
178 LOG.trace("Skipping change {}", rootNode.getIdentifier());
181 final DataTreeCandidateNode table = ribIn.getModifiedChild(TABLES_NID).getModifiedChild(this.tableKey);
183 LOG.trace("Skipping change {}", rootNode.getIdentifier());
186 initializeTableWithExistentRoutes(table, peerId, rootPath, tx);
187 updateNodes(table, peerId, tx, ret);
190 private void filterOutChangesToSupportedTables(final PeerId peerIdOfNewPeer, final DataTreeCandidateNode rootNode) {
191 final DataTreeCandidateNode tablesChange = rootNode.getModifiedChild(PEER_TABLES);
192 if (tablesChange != null) {
193 this.peerPolicyTracker.onTablesChanged(peerIdOfNewPeer, tablesChange);
197 private void initializeTableWithExistentRoutes(final DataTreeCandidateNode table, final PeerId peerIdOfNewPeer, final YangInstanceIdentifier rootPath,
198 final DOMDataWriteTransaction tx) {
199 if (!table.getDataBefore().isPresent() && this.peerPolicyTracker.isTableSupported(peerIdOfNewPeer)) {
200 LOG.debug("Peer {} table has been created, inserting existent routes", peerIdOfNewPeer);
201 final PeerRole newPeerRole = this.peerPolicyTracker.getRole(IdentifierUtils.peerPath(rootPath));
202 final PeerExportGroup peerGroup = this.peerPolicyTracker.getPeerGroup(newPeerRole);
203 this.routeEntries.entrySet().forEach(entry -> entry.getValue().writeRoute(peerIdOfNewPeer, entry.getKey(), rootPath, peerGroup,
204 this.localTablesKey, this.peerPolicyTracker, this.ribSupport, this.cacheDisconnectedPeers, tx));
208 private void filterOutPeerRole(final PeerId peerId, final DataTreeCandidateNode rootNode, final YangInstanceIdentifier rootPath) {
209 final DataTreeCandidateNode roleChange = rootNode.getModifiedChild(PEER_ROLE_NID);
210 if (roleChange != null) {
211 if (rootNode.getModificationType() != ModificationType.DELETE) {
212 this.cacheDisconnectedPeers.reconnected(peerId);
216 final Optional<NormalizedNode<?, ?>> maybePeerRole = roleChange.getDataAfter();
217 final YangInstanceIdentifier peerPath = IdentifierUtils.peerPath(rootPath);
218 LOG.debug("Data Changed for Peer role {} path {}, dataBefore {}, dataAfter {}", roleChange.getIdentifier(),
219 peerPath , roleChange.getDataBefore(), maybePeerRole);
220 final PeerRole role = PeerRoleUtil.roleForChange(maybePeerRole);
221 final SimpleRoutingPolicy srp = getSimpleRoutingPolicy(rootNode);
222 if(SimpleRoutingPolicy.AnnounceNone == srp) {
225 this.peerPolicyTracker.peerRoleChanged(peerPath, role);
229 private SimpleRoutingPolicy getSimpleRoutingPolicy(final DataTreeCandidateNode rootNode) {
230 final DataTreeCandidateNode statusChange = rootNode.getModifiedChild(SIMPLE_ROUTING_POLICY_NID);
231 if (statusChange != null) {
232 final Optional<NormalizedNode<?, ?>> maybePeerStatus = statusChange.getDataAfter();
233 if (maybePeerStatus.isPresent()) {
234 return SimpleRoutingPolicy.valueOf(BindingMapping.getClassName((String) (maybePeerStatus.get()).getValue()));
240 private void updateNodes(final DataTreeCandidateNode table, final PeerId peerId, final DOMDataWriteTransaction tx,
241 final Map<RouteUpdateKey, RouteEntry> routes) {
242 for (final DataTreeCandidateNode child : table.getChildNodes()) {
243 LOG.debug("Modification type {}", child.getModificationType());
244 if ((Attributes.QNAME).equals(child.getIdentifier().getNodeType())) {
245 if (child.getDataAfter().isPresent()) {
246 // putting uptodate attribute in
247 LOG.trace("Uptodate found for {}", child.getDataAfter());
248 tx.put(LogicalDatastoreType.OPERATIONAL, this.locRibTarget.node(child.getIdentifier()), child.getDataAfter().get());
252 updateRoutesEntries(child, peerId, routes);
256 private void updateRoutesEntries(final DataTreeCandidateNode child, final PeerId peerId, final Map<RouteUpdateKey, RouteEntry> routes) {
257 final UnsignedInteger routerId = RouterIds.routerIdForPeerId(peerId);
258 final Collection<DataTreeCandidateNode> modifiedRoutes = this.ribSupport.changedRoutes(child);
259 for (final DataTreeCandidateNode route : modifiedRoutes) {
260 final PathArgument routeId = this.ribSupport.createRouteKeyPathArgument(route.getIdentifier());
261 RouteEntry entry = this.routeEntries.get(routeId);
262 final Optional<NormalizedNode<?, ?>> maybeData = route.getDataAfter();
263 final Optional<NormalizedNode<?, ?>> maybeDataBefore = route.getDataBefore();
264 if (maybeData.isPresent()) {
266 entry = createEntry(routeId);
268 entry.addRoute(routerId, this.ribSupport.extractPathId(maybeData.get()), this.attributesIdentifier, maybeData.get());
269 } else if (entry != null && entry.removeRoute(routerId, this.ribSupport.extractPathId(maybeDataBefore.get()))) {
270 this.routeEntries.remove(routeId);
271 LOG.trace("Removed route from {}", routerId);
273 final RouteUpdateKey routeUpdateKey = new RouteUpdateKey(peerId, routeId);
274 LOG.debug("Updated route {} entry {}", routeId, entry);
275 routes.put(routeUpdateKey, entry);
277 updateRouteCounter();
281 * Update the statistic of loc-rib route
283 private void updateRouteCounter() {
284 routeCounter.setCount(this.routeEntries.size());
287 private void walkThrough(final DOMDataWriteTransaction tx, final Map<RouteUpdateKey, RouteEntry> toUpdate) {
288 for (final Map.Entry<RouteUpdateKey, RouteEntry> e : toUpdate.entrySet()) {
289 LOG.trace("Walking through {}", e);
290 final RouteEntry entry = e.getValue();
292 if (!entry.selectBest(this.ourAs)) {
293 LOG.trace("Best path has not changed, continuing");
296 entry.updateRoute(this.localTablesKey, this.peerPolicyTracker, this.locRibTarget, this.ribSupport, this.cacheDisconnectedPeers,
297 tx, e.getKey().getRouteId());