501a7a90f93ec343f5af4df5d3d387d2a77506c5
[bgpcep.git] / bgp / path-selection-mode / src / main / java / org / opendaylight / protocol / bgp / mode / impl / base / BaseAbstractRouteEntry.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.mode.impl.base;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.primitives.UnsignedInteger;
12 import java.util.Optional;
13 import javax.annotation.Nullable;
14 import javax.annotation.concurrent.NotThreadSafe;
15 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
16 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
17 import org.opendaylight.protocol.bgp.mode.impl.BGPRouteEntryExportParametersImpl;
18 import org.opendaylight.protocol.bgp.mode.spi.AbstractRouteEntry;
19 import org.opendaylight.protocol.bgp.rib.spi.BGPPeerTracker;
20 import org.opendaylight.protocol.bgp.rib.spi.Peer;
21 import org.opendaylight.protocol.bgp.rib.spi.RIBSupport;
22 import org.opendaylight.protocol.bgp.rib.spi.entry.RouteEntryDependenciesContainer;
23 import org.opendaylight.protocol.bgp.rib.spi.entry.RouteEntryInfo;
24 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRibRoutingPolicy;
25 import org.opendaylight.protocol.bgp.rib.spi.policy.BGPRouteEntryExportParameters;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev171207.path.attributes.Attributes;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.PeerId;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.Route;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.Tables;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
31 import org.opendaylight.yangtools.yang.binding.Identifier;
32 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
33 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 @NotThreadSafe
38 abstract class BaseAbstractRouteEntry extends AbstractRouteEntry<BaseBestPath> {
39     private static final Logger LOG = LoggerFactory.getLogger(BaseAbstractRouteEntry.class);
40     private OffsetMap offsets = OffsetMap.EMPTY;
41     private Attributes[] values = EMPTY_ATTRIBUTES;
42     private BaseBestPath bestPath;
43     private BaseBestPath removedBestPath;
44
45     BaseAbstractRouteEntry(final BGPPeerTracker peerTracker) {
46         super(peerTracker);
47     }
48
49     /**
50      * Remove route.
51      *
52      * @param routerId router ID in unsigned integer
53      * @param offset   of removed route
54      * @return true if its the last route
55      */
56     protected final boolean removeRoute(final UnsignedInteger routerId, final int offset) {
57         this.values = this.offsets.removeValue(this.values, offset, EMPTY_ATTRIBUTES);
58         this.offsets = this.offsets.without(routerId);
59         return this.offsets.isEmpty();
60     }
61
62     @Override
63     public final boolean selectBest(final long localAs) {
64         /*
65          * FIXME: optimize flaps by making sure we consider stability of currently-selected route.
66          */
67         final BasePathSelector selector = new BasePathSelector(localAs);
68
69         // Select the best route.
70         for (int i = 0; i < this.offsets.size(); ++i) {
71             final UnsignedInteger routerId = this.offsets.getRouterKey(i);
72             final Attributes attributes = this.offsets.getValue(this.values, i);
73             LOG.trace("Processing router id {} attributes {}", routerId, attributes);
74             selector.processPath(routerId, attributes);
75         }
76
77         // Get the newly-selected best path.
78         final BaseBestPath newBestPath = selector.result();
79         final boolean modified = newBestPath == null || !newBestPath.equals(this.bestPath);
80         if (modified) {
81             if (this.offsets.isEmpty()) {
82                 this.removedBestPath = this.bestPath;
83             }
84             LOG.trace("Previous best {}, current best {}", this.bestPath, newBestPath);
85             this.bestPath = newBestPath;
86         }
87         return modified;
88     }
89
90     @Override
91     public int addRoute(final UnsignedInteger routerId, final long remotePathId, final Route route) {
92         final Attributes advertisedAttrs = route.getAttributes();
93         int offset = this.offsets.offsetOf(routerId);
94         if (offset < 0) {
95             final OffsetMap newOffsets = this.offsets.with(routerId);
96             offset = newOffsets.offsetOf(routerId);
97
98             this.values = newOffsets.expand(this.offsets, this.values, offset);
99             this.offsets = newOffsets;
100         }
101
102         this.offsets.setValue(this.values, offset, advertisedAttrs);
103         LOG.trace("Added route from {} attributes {}", routerId, advertisedAttrs);
104         return offset;
105     }
106
107     @Override
108     public void updateBestPaths(
109             final RouteEntryDependenciesContainer entryDependencies,
110             final String routeKey,
111             final WriteTransaction tx) {
112         if (this.removedBestPath != null) {
113             removePathFromDataStore(entryDependencies, routeKey, tx);
114             this.removedBestPath = null;
115         }
116         if (this.bestPath != null) {
117             addPathToDataStore(entryDependencies, routeKey, tx);
118         }
119     }
120
121     @Override
122     @SuppressWarnings("unchecked")
123     public void initializeBestPaths(
124             final RouteEntryDependenciesContainer entryDep,
125             final RouteEntryInfo entryInfo,
126             final WriteTransaction tx) {
127         if (this.bestPath == null) {
128             return;
129         }
130         final TablesKey localTK = entryDep.getLocalTablesKey();
131         final Peer toPeer = entryInfo.getToPeer();
132         if (!filterRoutes(this.bestPath.getPeerId(), toPeer, localTK)) {
133             return;
134         }
135         final RIBSupport ribSupport = entryDep.getRibSupport();
136         Identifier routeIdentifier = ribSupport.createRouteListKey(this.bestPath.getPathId(), entryInfo.getRouteKey());
137         final BGPRouteEntryExportParameters routeEntry = new BGPRouteEntryExportParametersImpl(
138                 this.peerTracker.getPeer(this.bestPath.getPeerId()), toPeer);
139         final Optional<Attributes> effAttrib = entryDep.getRoutingPolicies()
140                 .applyExportPolicies(routeEntry, this.bestPath.getAttributes());
141         final Route route = createRoute(ribSupport, entryInfo.getRouteKey(), this.bestPath.getPathId(), this.bestPath);
142         InstanceIdentifier ribOutIId = ribSupport.createRouteIdentifier(toPeer.getRibOutIId(localTK), routeIdentifier);
143         if (effAttrib.isPresent() && route != null) {
144             LOG.debug("Write route {} to peer AdjRibsOut {}", route, toPeer.getPeerId());
145             tx.put(LogicalDatastoreType.OPERATIONAL, ribOutIId, route);
146             tx.put(LogicalDatastoreType.OPERATIONAL, ribOutIId.child(Attributes.class), effAttrib.get());
147         }
148     }
149
150     @SuppressWarnings("unchecked")
151     private void removePathFromDataStore(final RouteEntryDependenciesContainer entryDep,
152             final String routeKey, final WriteTransaction tx) {
153         LOG.trace("Best Path removed {}", this.removedBestPath);
154         final KeyedInstanceIdentifier<Tables, TablesKey> locRibTarget = entryDep.getLocRibTableTarget();
155         final RIBSupport ribSup = entryDep.getRibSupport();
156         Identifier routeIdentifier = ribSup.createRouteListKey(this.removedBestPath.getPathId(), routeKey);
157         final InstanceIdentifier routeTarget = ribSup.createRouteIdentifier(locRibTarget, routeIdentifier);
158         LOG.debug("Delete route from LocRib {}", routeTarget);
159         tx.delete(LogicalDatastoreType.OPERATIONAL, routeTarget);
160         fillAdjRibsOut(null, null, routeIdentifier, this.removedBestPath.getPeerId(),
161                 entryDep, tx);
162     }
163
164     @SuppressWarnings("unchecked")
165     private void addPathToDataStore(final RouteEntryDependenciesContainer entryDep,
166             final String routeKey, final WriteTransaction tx) {
167         final RIBSupport ribSup = entryDep.getRibSupport();
168         final Route route = createRoute(ribSup, routeKey, this.bestPath.getPathId(), this.bestPath);
169         LOG.trace("Selected best route {}", route);
170
171         Identifier routeIdentifier = ribSup.createRouteListKey(this.bestPath.getPathId(), routeKey);
172         final KeyedInstanceIdentifier<Tables, TablesKey> locRibTarget = entryDep.getLocRibTableTarget();
173         final InstanceIdentifier routeTarget = ribSup.createRouteIdentifier(locRibTarget, routeIdentifier);
174         LOG.debug("Write route to LocRib {}", route);
175         tx.put(LogicalDatastoreType.OPERATIONAL, routeTarget, route);
176         fillAdjRibsOut(this.bestPath.getAttributes(), route, routeIdentifier, this.bestPath.getPeerId(),
177                 entryDep, tx);
178     }
179
180     final OffsetMap getOffsets() {
181         return this.offsets;
182     }
183
184     @VisibleForTesting
185     @SuppressWarnings("unchecked")
186     private void fillAdjRibsOut(
187             @Nullable final Attributes attributes,
188             @Nullable final Route route,
189             final Identifier routeKey, final PeerId fromPeerId,
190             final RouteEntryDependenciesContainer routeEntryDep,
191             final WriteTransaction tx) {
192         /*
193          * We need to keep track of routers and populate adj-ribs-out, too. If we do not, we need to
194          * expose from which client a particular route was learned from in the local RIB, and have
195          * the listener perform filtering.
196          *
197          * We walk the policy set in order to minimize the amount of work we do for multiple peers:
198          * if we have two eBGP peers, for example, there is no reason why we should perform the translation
199          * multiple times.
200          */
201         final TablesKey localTK = routeEntryDep.getLocalTablesKey();
202         final BGPRibRoutingPolicy routingPolicies = routeEntryDep.getRoutingPolicies();
203         final RIBSupport ribSupport = routeEntryDep.getRibSupport();
204         for (final Peer toPeer : this.peerTracker.getPeers()) {
205             if (!filterRoutes(fromPeerId, toPeer, localTK)) {
206                 continue;
207             }
208             Optional<Attributes> effAttr = Optional.empty();
209             final Peer fromPeer = this.peerTracker.getPeer(fromPeerId);
210             if (fromPeer != null && attributes != null) {
211                 final BGPRouteEntryExportParameters routeEntry
212                         = new BGPRouteEntryExportParametersImpl(fromPeer, toPeer);
213                 effAttr = routingPolicies.applyExportPolicies(routeEntry, attributes);
214             }
215             final InstanceIdentifier ribOutTarget
216                     = ribSupport.createRouteIdentifier(toPeer.getRibOutIId(localTK), routeKey);
217             if (effAttr.isPresent() && route != null) {
218                 LOG.debug("Write route {} to peer AdjRibsOut {}", route, toPeer.getPeerId());
219                 tx.put(LogicalDatastoreType.OPERATIONAL, ribOutTarget, route);
220                 tx.put(LogicalDatastoreType.OPERATIONAL, ribOutTarget.child(Attributes.class), effAttr.get());
221             } else {
222                 LOG.trace("Removing {} from transaction for peer {}", ribOutTarget, toPeer.getPeerId());
223                 tx.delete(LogicalDatastoreType.OPERATIONAL, ribOutTarget);
224             }
225         }
226     }
227 }