blob: 8a2e353c7179f2385915d8cf9b27ed206b37d12f [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Saurav Das62ae6792017-05-15 15:34:25 -070018import com.google.common.collect.ImmutableMap;
19import com.google.common.collect.ImmutableMap.Builder;
Charles Chanc22cef32016-04-29 14:38:22 -070020import com.google.common.collect.ImmutableSet;
Saurav Das1b391d52016-11-29 14:27:25 -080021import com.google.common.collect.Lists;
sanghofb7c7292015-04-13 15:15:58 -070022import com.google.common.collect.Maps;
23import com.google.common.collect.Sets;
Saurav Dasfbe74572017-08-03 18:30:35 -070024
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070025import org.onlab.packet.EthType;
Charles Chan19b70032019-04-17 14:20:26 -070026import com.google.common.collect.Streams;
sangho9b169e32015-04-14 16:27:13 -070027import org.onlab.packet.Ip4Address;
Pier Ventreadb4ae62016-11-23 09:57:42 -080028import org.onlab.packet.Ip6Address;
sangho80f11cb2015-04-01 13:05:26 -070029import org.onlab.packet.IpPrefix;
Charles Chan910be6a2017-08-23 14:46:43 -070030import org.onlab.packet.MacAddress;
31import org.onlab.packet.VlanId;
piera9941192019-04-24 16:12:47 +020032import org.onlab.util.PredictableExecutor;
33import org.onlab.util.PredictableExecutor.PickyCallable;
Saurav Das261c3002017-06-13 15:35:54 -070034import org.onosproject.cluster.NodeId;
Saurav Das00e553b2018-04-21 17:19:48 -070035import org.onosproject.mastership.MastershipEvent;
Charles Chanc22cef32016-04-29 14:38:22 -070036import org.onosproject.net.ConnectPoint;
sangho80f11cb2015-04-01 13:05:26 -070037import org.onosproject.net.Device;
38import org.onosproject.net.DeviceId;
sanghofb7c7292015-04-13 15:15:58 -070039import org.onosproject.net.Link;
Charles Chan910be6a2017-08-23 14:46:43 -070040import org.onosproject.net.PortNumber;
Charles Chan319d1a22015-11-03 10:42:14 -080041import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
42import org.onosproject.segmentrouting.config.DeviceConfiguration;
Saurav Das62ae6792017-05-15 15:34:25 -070043import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Charles Chand66d6712018-03-29 16:03:41 -070044import org.onosproject.store.serializers.KryoNamespaces;
pierf331a492020-01-07 15:39:39 +010045import org.onosproject.store.service.ConsistentMultimap;
Charles Chand66d6712018-03-29 16:03:41 -070046import org.onosproject.store.service.Serializer;
sangho80f11cb2015-04-01 13:05:26 -070047import org.slf4j.Logger;
48import org.slf4j.LoggerFactory;
49
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -070050import java.time.Instant;
sangho80f11cb2015-04-01 13:05:26 -070051import java.util.ArrayList;
Charles Chand66d6712018-03-29 16:03:41 -070052import java.util.Collections;
sangho80f11cb2015-04-01 13:05:26 -070053import java.util.HashMap;
54import java.util.HashSet;
Saurav Das261c3002017-06-13 15:35:54 -070055import java.util.Iterator;
Charles Chand66d6712018-03-29 16:03:41 -070056import java.util.List;
Saurav Das261c3002017-06-13 15:35:54 -070057import java.util.Map;
pierf331a492020-01-07 15:39:39 +010058import java.util.Map.Entry;
Saurav Dasd1872b02016-12-02 15:43:47 -080059import java.util.Objects;
Charles Chan6dbcd252018-04-02 11:46:38 -070060import java.util.Optional;
sangho80f11cb2015-04-01 13:05:26 -070061import java.util.Set;
piera9941192019-04-24 16:12:47 +020062import java.util.concurrent.CompletableFuture;
63import java.util.concurrent.ExecutionException;
64import java.util.concurrent.ExecutorService;
65import java.util.concurrent.Future;
Saurav Das07c74602016-04-27 18:35:50 -070066import java.util.concurrent.ScheduledExecutorService;
67import java.util.concurrent.TimeUnit;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +090068import java.util.concurrent.locks.Lock;
69import java.util.concurrent.locks.ReentrantLock;
Charles Chan19b70032019-04-17 14:20:26 -070070import java.util.stream.Collectors;
Saurav Dasdc7f2752018-03-18 21:28:15 -070071import java.util.stream.Stream;
72
Pier Ventreadb4ae62016-11-23 09:57:42 -080073import static com.google.common.base.Preconditions.checkNotNull;
74import static java.util.concurrent.Executors.newScheduledThreadPool;
75import static org.onlab.util.Tools.groupedThreads;
sangho80f11cb2015-04-01 13:05:26 -070076
Charles Chanb7f75ac2016-01-11 18:28:54 -080077/**
78 * Default routing handler that is responsible for route computing and
79 * routing rule population.
80 */
sangho80f11cb2015-04-01 13:05:26 -070081public class DefaultRoutingHandler {
Saurav Dasf9332192017-02-18 14:05:44 -080082 private static final int MAX_CONSTANT_RETRY_ATTEMPTS = 5;
Ray Milkey092e9e22018-02-01 13:49:47 -080083 private static final long RETRY_INTERVAL_MS = 250L;
Saurav Dasf9332192017-02-18 14:05:44 -080084 private static final int RETRY_INTERVAL_SCALE = 1;
Saurav Dasfbe74572017-08-03 18:30:35 -070085 private static final long STABLITY_THRESHOLD = 10; //secs
Saurav Das00e553b2018-04-21 17:19:48 -070086 private static final long MASTER_CHANGE_DELAY = 1000; // ms
Saurav Das68e1b6a2018-06-11 17:02:31 -070087 private static final long PURGE_DELAY = 1000; // ms
Charles Chanc22cef32016-04-29 14:38:22 -070088 private static Logger log = LoggerFactory.getLogger(DefaultRoutingHandler.class);
sangho80f11cb2015-04-01 13:05:26 -070089
90 private SegmentRoutingManager srManager;
91 private RoutingRulePopulator rulePopulator;
Shashikanth VH0637b162015-12-11 01:32:44 +053092 private HashMap<DeviceId, EcmpShortestPathGraph> currentEcmpSpgMap;
93 private HashMap<DeviceId, EcmpShortestPathGraph> updatedEcmpSpgMap;
sangho9b169e32015-04-14 16:27:13 -070094 private DeviceConfiguration config;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +090095 private final Lock statusLock = new ReentrantLock();
96 private volatile Status populationStatus;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -070097 private ScheduledExecutorService executorService
Saurav Dasd1872b02016-12-02 15:43:47 -080098 = newScheduledThreadPool(1, groupedThreads("retryftr", "retry-%d", log));
Saurav Das49368392018-04-23 18:42:12 -070099 private ScheduledExecutorService executorServiceMstChg
100 = newScheduledThreadPool(1, groupedThreads("masterChg", "mstch-%d", log));
Saurav Das68e1b6a2018-06-11 17:02:31 -0700101 private ScheduledExecutorService executorServiceFRR
102 = newScheduledThreadPool(1, groupedThreads("fullRR", "fullRR-%d", log));
piera9941192019-04-24 16:12:47 +0200103 // Route populators - 0 will leverage available processors
104 private static final int DEFAULT_THREADS = 0;
105 private ExecutorService routePopulators;
Saurav Das49368392018-04-23 18:42:12 -0700106
Saurav Das00e553b2018-04-21 17:19:48 -0700107 private Instant lastRoutingChange = Instant.EPOCH;
Saurav Das68e1b6a2018-06-11 17:02:31 -0700108 private Instant lastFullReroute = Instant.EPOCH;
sangho80f11cb2015-04-01 13:05:26 -0700109
Saurav Das00e553b2018-04-21 17:19:48 -0700110 // Distributed store to keep track of ONOS instance that should program the
111 // device pair. There should be only one instance (the king) that programs the same pair.
Charles Chand66d6712018-03-29 16:03:41 -0700112 Map<Set<DeviceId>, NodeId> shouldProgram;
Charles Chanfbcb8812018-04-18 18:41:05 -0700113 Map<DeviceId, Boolean> shouldProgramCache;
Charles Chand66d6712018-03-29 16:03:41 -0700114
pierf331a492020-01-07 15:39:39 +0100115 // Distributed routes store to keep track of the routes already seen
116 // destination device is the key and target sw is the value
117 ConsistentMultimap<DeviceId, DeviceId> seenBeforeRoutes;
118
Saurav Das00e553b2018-04-21 17:19:48 -0700119 // Local store to keep track of all devices that this instance was responsible
120 // for programming in the last run. Helps to determine if mastership changed
121 // during a run - only relevant for programming as a result of topo change.
122 Set<DeviceId> lastProgrammed;
123
sangho80f11cb2015-04-01 13:05:26 -0700124 /**
125 * Represents the default routing population status.
126 */
127 public enum Status {
128 // population process is not started yet.
129 IDLE,
sangho80f11cb2015-04-01 13:05:26 -0700130 // population process started.
131 STARTED,
piera9941192019-04-24 16:12:47 +0200132 // population process was aborted due to errors, mostly for groups not found.
sangho80f11cb2015-04-01 13:05:26 -0700133 ABORTED,
sangho80f11cb2015-04-01 13:05:26 -0700134 // population process was finished successfully.
135 SUCCEEDED
136 }
137
138 /**
139 * Creates a DefaultRoutingHandler object.
140 *
141 * @param srManager SegmentRoutingManager object
142 */
Charles Chand66d6712018-03-29 16:03:41 -0700143 DefaultRoutingHandler(SegmentRoutingManager srManager) {
Charles Chanfbcb8812018-04-18 18:41:05 -0700144 this.shouldProgram = srManager.storageService.<Set<DeviceId>, NodeId>consistentMapBuilder()
145 .withName("sr-should-program")
146 .withSerializer(Serializer.using(KryoNamespaces.API))
147 .withRelaxedReadConsistency()
148 .build().asJavaMap();
pierf331a492020-01-07 15:39:39 +0100149 this.seenBeforeRoutes = srManager.storageService.<DeviceId, DeviceId>consistentMultimapBuilder()
150 .withName("programmed-routes")
151 .withSerializer(Serializer.using(KryoNamespaces.API))
152 .withRelaxedReadConsistency()
153 .build();
Charles Chanfbcb8812018-04-18 18:41:05 -0700154 this.shouldProgramCache = Maps.newConcurrentMap();
155 update(srManager);
piera9941192019-04-24 16:12:47 +0200156 this.routePopulators = new PredictableExecutor(DEFAULT_THREADS,
157 groupedThreads("onos/sr", "r-populator-%d", log));
Charles Chanfbcb8812018-04-18 18:41:05 -0700158 }
159
160 /**
161 * Updates a DefaultRoutingHandler object.
162 *
163 * @param srManager SegmentRoutingManager object
164 */
165 void update(SegmentRoutingManager srManager) {
sangho80f11cb2015-04-01 13:05:26 -0700166 this.srManager = srManager;
167 this.rulePopulator = checkNotNull(srManager.routingRulePopulator);
sangho9b169e32015-04-14 16:27:13 -0700168 this.config = checkNotNull(srManager.deviceConfiguration);
sangho80f11cb2015-04-01 13:05:26 -0700169 this.populationStatus = Status.IDLE;
sanghofb7c7292015-04-13 15:15:58 -0700170 this.currentEcmpSpgMap = Maps.newHashMap();
Saurav Das00e553b2018-04-21 17:19:48 -0700171 this.lastProgrammed = Sets.newConcurrentHashSet();
sangho80f11cb2015-04-01 13:05:26 -0700172 }
173
174 /**
Saurav Das62ae6792017-05-15 15:34:25 -0700175 * Returns an immutable copy of the current ECMP shortest-path graph as
176 * computed by this controller instance.
177 *
Saurav Das261c3002017-06-13 15:35:54 -0700178 * @return immutable copy of the current ECMP graph
Saurav Das62ae6792017-05-15 15:34:25 -0700179 */
180 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEmcpSpgMap() {
181 Builder<DeviceId, EcmpShortestPathGraph> builder = ImmutableMap.builder();
182 currentEcmpSpgMap.entrySet().forEach(entry -> {
183 if (entry.getValue() != null) {
184 builder.put(entry.getKey(), entry.getValue());
185 }
186 });
187 return builder.build();
188 }
189
Saurav Dasfbe74572017-08-03 18:30:35 -0700190 /**
191 * Acquires the lock used when making routing changes.
192 */
193 public void acquireRoutingLock() {
194 statusLock.lock();
195 }
196
197 /**
198 * Releases the lock used when making routing changes.
199 */
200 public void releaseRoutingLock() {
201 statusLock.unlock();
202 }
203
204 /**
205 * Determines if routing in the network has been stable in the last
206 * STABLITY_THRESHOLD seconds, by comparing the current time to the last
207 * routing change timestamp.
208 *
209 * @return true if stable
210 */
211 public boolean isRoutingStable() {
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -0700212 long last = (long) (lastRoutingChange.toEpochMilli() / 1000.0);
213 long now = (long) (Instant.now().toEpochMilli() / 1000.0);
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700214 log.trace("Routing stable since {}s", now - last);
Saurav Dasfbe74572017-08-03 18:30:35 -0700215 return (now - last) > STABLITY_THRESHOLD;
216 }
217
Saurav Das49368392018-04-23 18:42:12 -0700218 /**
219 * Gracefully shuts down the defaultRoutingHandler. Typically called when
220 * the app is deactivated
221 */
222 public void shutdown() {
223 executorService.shutdown();
224 executorServiceMstChg.shutdown();
Saurav Das68e1b6a2018-06-11 17:02:31 -0700225 executorServiceFRR.shutdown();
piera9941192019-04-24 16:12:47 +0200226 routePopulators.shutdown();
Saurav Das49368392018-04-23 18:42:12 -0700227 }
Saurav Dasfbe74572017-08-03 18:30:35 -0700228
Saurav Das261c3002017-06-13 15:35:54 -0700229 //////////////////////////////////////
230 // Route path handling
231 //////////////////////////////////////
232
Saurav Dase6c448a2018-01-18 12:07:33 -0800233 /* The following three methods represent the three major ways in which
234 * route-path handling is triggered in the network
Saurav Das261c3002017-06-13 15:35:54 -0700235 * a) due to configuration change
236 * b) due to route-added event
237 * c) due to change in the topology
238 */
239
Saurav Das62ae6792017-05-15 15:34:25 -0700240 /**
Saurav Das261c3002017-06-13 15:35:54 -0700241 * Populates all routing rules to all switches. Typically triggered at
242 * startup or after a configuration event.
sangho80f11cb2015-04-01 13:05:26 -0700243 */
Saurav Das62ae6792017-05-15 15:34:25 -0700244 public void populateAllRoutingRules() {
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -0700245 lastRoutingChange = Instant.now();
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900246 statusLock.lock();
247 try {
Saurav Das261c3002017-06-13 15:35:54 -0700248 if (populationStatus == Status.STARTED) {
249 log.warn("Previous rule population is not finished. Cannot"
250 + " proceed with populateAllRoutingRules");
251 return;
252 }
253
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900254 populationStatus = Status.STARTED;
255 rulePopulator.resetCounter();
Saurav Das261c3002017-06-13 15:35:54 -0700256 log.info("Starting to populate all routing rules");
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900257 log.debug("populateAllRoutingRules: populationStatus is STARTED");
sangho80f11cb2015-04-01 13:05:26 -0700258
Saurav Das261c3002017-06-13 15:35:54 -0700259 // take a snapshot of the topology
260 updatedEcmpSpgMap = new HashMap<>();
261 Set<EdgePair> edgePairs = new HashSet<>();
262 Set<ArrayList<DeviceId>> routeChanges = new HashSet<>();
Jonathan Hart61e24e12017-11-30 18:23:42 -0800263 for (DeviceId dstSw : srManager.deviceConfiguration.getRouters()) {
Saurav Das261c3002017-06-13 15:35:54 -0700264 EcmpShortestPathGraph ecmpSpgUpdated =
Jonathan Hart61e24e12017-11-30 18:23:42 -0800265 new EcmpShortestPathGraph(dstSw, srManager);
266 updatedEcmpSpgMap.put(dstSw, ecmpSpgUpdated);
Charles Chan6dbcd252018-04-02 11:46:38 -0700267 Optional<DeviceId> pairDev = srManager.getPairDeviceId(dstSw);
268 if (pairDev.isPresent()) {
Saurav Das261c3002017-06-13 15:35:54 -0700269 // pairDev may not be available yet, but we still need to add
Charles Chan6dbcd252018-04-02 11:46:38 -0700270 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev.get(), srManager);
271 updatedEcmpSpgMap.put(pairDev.get(), ecmpSpgUpdated);
272 edgePairs.add(new EdgePair(dstSw, pairDev.get()));
Saurav Das261c3002017-06-13 15:35:54 -0700273 }
Charles Chand66d6712018-03-29 16:03:41 -0700274
275 if (!shouldProgram(dstSw)) {
Saurav Das00e553b2018-04-21 17:19:48 -0700276 lastProgrammed.remove(dstSw);
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900277 continue;
Saurav Das00e553b2018-04-21 17:19:48 -0700278 } else {
279 lastProgrammed.add(dstSw);
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900280 }
Saurav Das00e553b2018-04-21 17:19:48 -0700281 // To do a full reroute, assume all route-paths have changed
Charles Chand66d6712018-03-29 16:03:41 -0700282 for (DeviceId dev : deviceAndItsPair(dstSw)) {
Jonathan Hart61e24e12017-11-30 18:23:42 -0800283 for (DeviceId targetSw : srManager.deviceConfiguration.getRouters()) {
284 if (targetSw.equals(dev)) {
Saurav Das261c3002017-06-13 15:35:54 -0700285 continue;
286 }
Jonathan Hart61e24e12017-11-30 18:23:42 -0800287 routeChanges.add(Lists.newArrayList(targetSw, dev));
Saurav Das261c3002017-06-13 15:35:54 -0700288 }
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900289 }
Saurav Das261c3002017-06-13 15:35:54 -0700290 }
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900291
pierf331a492020-01-07 15:39:39 +0100292 log.debug("seenBeforeRoutes size {}", seenBeforeRoutes.size());
Saurav Das261c3002017-06-13 15:35:54 -0700293 if (!redoRouting(routeChanges, edgePairs, null)) {
294 log.debug("populateAllRoutingRules: populationStatus is ABORTED");
295 populationStatus = Status.ABORTED;
296 log.warn("Failed to repopulate all routing rules.");
297 return;
sangho80f11cb2015-04-01 13:05:26 -0700298 }
299
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900300 log.debug("populateAllRoutingRules: populationStatus is SUCCEEDED");
301 populationStatus = Status.SUCCEEDED;
Saurav Das261c3002017-06-13 15:35:54 -0700302 log.info("Completed all routing rule population. Total # of rules pushed : {}",
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900303 rulePopulator.getCounter());
Saurav Das62ae6792017-05-15 15:34:25 -0700304 return;
pierdebd15c2019-04-19 20:55:53 +0200305 } catch (Exception e) {
306 log.error("populateAllRoutingRules thrown an exception: {}",
307 e.getMessage(), e);
308 populationStatus = Status.ABORTED;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900309 } finally {
310 statusLock.unlock();
sangho80f11cb2015-04-01 13:05:26 -0700311 }
sangho80f11cb2015-04-01 13:05:26 -0700312 }
313
sanghofb7c7292015-04-13 15:15:58 -0700314 /**
Saurav Das261c3002017-06-13 15:35:54 -0700315 * Populate rules from all other edge devices to the connect-point(s)
316 * specified for the given subnets.
317 *
318 * @param cpts connect point(s) of the subnets being added
319 * @param subnets subnets being added
Charles Chan910be6a2017-08-23 14:46:43 -0700320 */
321 // XXX refactor
Saurav Das261c3002017-06-13 15:35:54 -0700322 protected void populateSubnet(Set<ConnectPoint> cpts, Set<IpPrefix> subnets) {
Charles Chan6db55b92017-09-11 15:21:57 -0700323 if (cpts == null || cpts.size() < 1 || cpts.size() > 2) {
324 log.warn("Skipping populateSubnet due to illegal size of connect points. {}", cpts);
325 return;
326 }
327
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -0700328 lastRoutingChange = Instant.now();
Saurav Das261c3002017-06-13 15:35:54 -0700329 statusLock.lock();
330 try {
331 if (populationStatus == Status.STARTED) {
332 log.warn("Previous rule population is not finished. Cannot"
333 + " proceed with routing rules for added routes");
334 return;
335 }
336 populationStatus = Status.STARTED;
337 rulePopulator.resetCounter();
Charles Chan910be6a2017-08-23 14:46:43 -0700338 log.info("Starting to populate routing rules for added routes, subnets={}, cpts={}",
339 subnets, cpts);
Saurav Das6430f412018-01-25 09:49:01 -0800340 // In principle an update to a subnet/prefix should not require a
341 // new ECMPspg calculation as it is not a topology event. As a
342 // result, we use the current/existing ECMPspg in the updated map
343 // used by the redoRouting method.
Saurav Das6de6ffd2018-02-09 09:15:03 -0800344 if (updatedEcmpSpgMap == null) {
345 updatedEcmpSpgMap = new HashMap<>();
346 }
Saurav Das6430f412018-01-25 09:49:01 -0800347 currentEcmpSpgMap.entrySet().forEach(entry -> {
348 updatedEcmpSpgMap.put(entry.getKey(), entry.getValue());
Saurav Dase321cff2018-02-09 17:26:45 -0800349 if (log.isTraceEnabled()) {
350 log.trace("Root switch: {}", entry.getKey());
351 log.trace(" Current/Existing SPG: {}", entry.getValue());
Saurav Das6430f412018-01-25 09:49:01 -0800352 }
353 });
pierf331a492020-01-07 15:39:39 +0100354 log.debug("seenBeforeRoutes size {}", seenBeforeRoutes.size());
Saurav Das261c3002017-06-13 15:35:54 -0700355 Set<EdgePair> edgePairs = new HashSet<>();
356 Set<ArrayList<DeviceId>> routeChanges = new HashSet<>();
357 boolean handleRouting = false;
358
359 if (cpts.size() == 2) {
360 // ensure connect points are edge-pairs
361 Iterator<ConnectPoint> iter = cpts.iterator();
362 DeviceId dev1 = iter.next().deviceId();
Charles Chan6dbcd252018-04-02 11:46:38 -0700363 Optional<DeviceId> pairDev = srManager.getPairDeviceId(dev1);
364 if (pairDev.isPresent() && iter.next().deviceId().equals(pairDev.get())) {
365 edgePairs.add(new EdgePair(dev1, pairDev.get()));
Saurav Das261c3002017-06-13 15:35:54 -0700366 } else {
367 log.warn("Connectpoints {} for subnets {} not on "
368 + "pair-devices.. aborting populateSubnet", cpts, subnets);
369 populationStatus = Status.ABORTED;
370 return;
371 }
372 for (ConnectPoint cp : cpts) {
Saurav Das6430f412018-01-25 09:49:01 -0800373 if (updatedEcmpSpgMap.get(cp.deviceId()) == null) {
374 EcmpShortestPathGraph ecmpSpgUpdated =
Saurav Das261c3002017-06-13 15:35:54 -0700375 new EcmpShortestPathGraph(cp.deviceId(), srManager);
Saurav Das6430f412018-01-25 09:49:01 -0800376 updatedEcmpSpgMap.put(cp.deviceId(), ecmpSpgUpdated);
377 log.warn("populateSubnet: no updated graph for dev:{}"
378 + " ... creating", cp.deviceId());
379 }
Charles Chand66d6712018-03-29 16:03:41 -0700380 if (!shouldProgram(cp.deviceId())) {
Saurav Das261c3002017-06-13 15:35:54 -0700381 continue;
382 }
383 handleRouting = true;
384 }
385 } else {
386 // single connect point
387 DeviceId dstSw = cpts.iterator().next().deviceId();
Saurav Das6430f412018-01-25 09:49:01 -0800388 if (updatedEcmpSpgMap.get(dstSw) == null) {
389 EcmpShortestPathGraph ecmpSpgUpdated =
Saurav Das261c3002017-06-13 15:35:54 -0700390 new EcmpShortestPathGraph(dstSw, srManager);
Saurav Das6430f412018-01-25 09:49:01 -0800391 updatedEcmpSpgMap.put(dstSw, ecmpSpgUpdated);
392 log.warn("populateSubnet: no updated graph for dev:{}"
393 + " ... creating", dstSw);
394 }
Charles Chand66d6712018-03-29 16:03:41 -0700395 handleRouting = shouldProgram(dstSw);
Saurav Das261c3002017-06-13 15:35:54 -0700396 }
397
398 if (!handleRouting) {
399 log.debug("This instance is not handling ecmp routing to the "
400 + "connectPoint(s) {}", cpts);
401 populationStatus = Status.ABORTED;
402 return;
403 }
404
405 // if it gets here, this instance should handle routing for the
406 // connectpoint(s). Assume all route-paths have to be updated to
407 // the connectpoint(s) with the following exceptions
408 // 1. if target is non-edge no need for routing rules
409 // 2. if target is one of the connectpoints
410 for (ConnectPoint cp : cpts) {
411 DeviceId dstSw = cp.deviceId();
412 for (Device targetSw : srManager.deviceService.getDevices()) {
413 boolean isEdge = false;
414 try {
415 isEdge = config.isEdgeDevice(targetSw.id());
416 } catch (DeviceConfigNotFoundException e) {
Charles Chaneaf3c9b2018-02-16 17:20:54 -0800417 log.warn(e.getMessage() + "aborting populateSubnet on targetSw {}", targetSw.id());
418 continue;
Saurav Das261c3002017-06-13 15:35:54 -0700419 }
Charles Chan6dbcd252018-04-02 11:46:38 -0700420 Optional<DeviceId> pairDev = srManager.getPairDeviceId(dstSw);
Saurav Das261c3002017-06-13 15:35:54 -0700421 if (dstSw.equals(targetSw.id()) || !isEdge ||
Charles Chan6dbcd252018-04-02 11:46:38 -0700422 (cpts.size() == 2 && pairDev.isPresent() && targetSw.id().equals(pairDev.get()))) {
Saurav Das261c3002017-06-13 15:35:54 -0700423 continue;
424 }
425 routeChanges.add(Lists.newArrayList(targetSw.id(), dstSw));
426 }
427 }
428
429 if (!redoRouting(routeChanges, edgePairs, subnets)) {
430 log.debug("populateSubnet: populationStatus is ABORTED");
431 populationStatus = Status.ABORTED;
432 log.warn("Failed to repopulate the rules for subnet.");
433 return;
434 }
435
436 log.debug("populateSubnet: populationStatus is SUCCEEDED");
437 populationStatus = Status.SUCCEEDED;
438 log.info("Completed subnet population. Total # of rules pushed : {}",
439 rulePopulator.getCounter());
440 return;
441
pierdebd15c2019-04-19 20:55:53 +0200442 } catch (Exception e) {
443 log.error("populateSubnet thrown an exception: {}",
444 e.getMessage(), e);
445 populationStatus = Status.ABORTED;
Saurav Das261c3002017-06-13 15:35:54 -0700446 } finally {
447 statusLock.unlock();
448 }
449 }
450
451 /**
Saurav Das62ae6792017-05-15 15:34:25 -0700452 * Populates the routing rules or makes hash group changes according to the
453 * route-path changes due to link failure, switch failure or link up. This
454 * method should only be called for one of these three possible event-types.
Saurav Dasdc7f2752018-03-18 21:28:15 -0700455 * Note that when a switch goes away, all of its links fail as well, but
456 * this is handled as a single switch removal event.
sanghofb7c7292015-04-13 15:15:58 -0700457 *
Saurav Dasdc7f2752018-03-18 21:28:15 -0700458 * @param linkDown the single failed link, or null for other conditions such
459 * as link-up or a removed switch
Saurav Das62ae6792017-05-15 15:34:25 -0700460 * @param linkUp the single link up, or null for other conditions such as
Saurav Dasdc7f2752018-03-18 21:28:15 -0700461 * link-down or a removed switch
462 * @param switchDown the removed switch, or null for other conditions such
463 * as link-down or link-up
464 * @param seenBefore true if this event is for a linkUp or linkDown for a
465 * seen link
466 */
467 // TODO This method should be refactored into three separated methods
Charles Chan9d2dd552018-06-19 20:56:33 -0700468 public void populateRoutingRulesForLinkStatusChange(Link linkDown, Link linkUp,
469 DeviceId switchDown, boolean seenBefore) {
Saurav Dasdc7f2752018-03-18 21:28:15 -0700470 if (Stream.of(linkDown, linkUp, switchDown).filter(Objects::nonNull)
471 .count() != 1) {
Saurav Das62ae6792017-05-15 15:34:25 -0700472 log.warn("Only one event can be handled for link status change .. aborting");
473 return;
474 }
Saurav Dasdc7f2752018-03-18 21:28:15 -0700475
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -0700476 lastRoutingChange = Instant.now();
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900477 statusLock.lock();
478 try {
sanghofb7c7292015-04-13 15:15:58 -0700479
480 if (populationStatus == Status.STARTED) {
Saurav Das261c3002017-06-13 15:35:54 -0700481 log.warn("Previous rule population is not finished. Cannot"
Saurav Das6430f412018-01-25 09:49:01 -0800482 + " proceeed with routingRules for Topology change");
Saurav Das62ae6792017-05-15 15:34:25 -0700483 return;
sanghofb7c7292015-04-13 15:15:58 -0700484 }
485
Saurav Das261c3002017-06-13 15:35:54 -0700486 // Take snapshots of the topology
sangho28d0b6d2015-05-07 13:30:57 -0700487 updatedEcmpSpgMap = new HashMap<>();
Saurav Das261c3002017-06-13 15:35:54 -0700488 Set<EdgePair> edgePairs = new HashSet<>();
sangho28d0b6d2015-05-07 13:30:57 -0700489 for (Device sw : srManager.deviceService.getDevices()) {
Shashikanth VH0637b162015-12-11 01:32:44 +0530490 EcmpShortestPathGraph ecmpSpgUpdated =
491 new EcmpShortestPathGraph(sw.id(), srManager);
sangho28d0b6d2015-05-07 13:30:57 -0700492 updatedEcmpSpgMap.put(sw.id(), ecmpSpgUpdated);
Charles Chan6dbcd252018-04-02 11:46:38 -0700493 Optional<DeviceId> pairDev = srManager.getPairDeviceId(sw.id());
494 if (pairDev.isPresent()) {
Saurav Das261c3002017-06-13 15:35:54 -0700495 // pairDev may not be available yet, but we still need to add
Charles Chan6dbcd252018-04-02 11:46:38 -0700496 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev.get(), srManager);
497 updatedEcmpSpgMap.put(pairDev.get(), ecmpSpgUpdated);
498 edgePairs.add(new EdgePair(sw.id(), pairDev.get()));
Saurav Das261c3002017-06-13 15:35:54 -0700499 }
sangho28d0b6d2015-05-07 13:30:57 -0700500 }
501
Saurav Das6430f412018-01-25 09:49:01 -0800502 log.info("Starting to populate routing rules from Topology change");
sanghodf0153f2015-05-05 14:13:34 -0700503
sanghofb7c7292015-04-13 15:15:58 -0700504 Set<ArrayList<DeviceId>> routeChanges;
Saurav Das62ae6792017-05-15 15:34:25 -0700505 log.debug("populateRoutingRulesForLinkStatusChange: "
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700506 + "populationStatus is STARTED");
pierf331a492020-01-07 15:39:39 +0100507 log.debug("seenBeforeRoutes size {}", seenBeforeRoutes.size());
sanghofb7c7292015-04-13 15:15:58 -0700508 populationStatus = Status.STARTED;
Saurav Das6430f412018-01-25 09:49:01 -0800509 rulePopulator.resetCounter(); //XXX maybe useful to have a rehash ctr
510 boolean hashGroupsChanged = false;
Saurav Das1b391d52016-11-29 14:27:25 -0800511 // try optimized re-routing
Saurav Das62ae6792017-05-15 15:34:25 -0700512 if (linkDown == null) {
513 // either a linkUp or a switchDown - compute all route changes by
514 // comparing all routes of existing ECMP SPG to new ECMP SPG
Saurav Dascea556f2018-03-05 14:37:16 -0800515 routeChanges = computeRouteChange(switchDown);
Saurav Das62ae6792017-05-15 15:34:25 -0700516
pier572d4a92019-04-25 18:51:51 +0200517 // deal with linkUp
518 if (linkUp != null) {
519 // deal with linkUp of a seen-before link
520 if (seenBefore) {
521 // link previously seen before
522 // do hash-bucket changes instead of a re-route
523 processHashGroupChangeForLinkUp(routeChanges);
524 // clear out routesChanges so a re-route is not attempted
525 routeChanges = ImmutableSet.of();
526 hashGroupsChanged = true;
527 } else {
528 // do hash-bucket changes first, method will return changed routes;
529 // for each route not changed it will perform a reroute
530 Set<ArrayList<DeviceId>> changedRoutes = processHashGroupChangeForLinkUp(routeChanges);
531 Set<ArrayList<DeviceId>> routeChangesTemp = getExpandedRoutes(routeChanges);
532 changedRoutes.forEach(routeChangesTemp::remove);
533 // if routesChanges is empty a re-route is not attempted
534 routeChanges = routeChangesTemp;
535 for (ArrayList<DeviceId> route : routeChanges) {
536 log.debug("remaining routes Target -> Root");
537 if (route.size() == 1) {
538 log.debug(" : all -> {}", route.get(0));
539 } else {
540 log.debug(" : {} -> {}", route.get(0), route.get(1));
541 }
542 }
543 // Mark hash groups as changed
544 if (!changedRoutes.isEmpty()) {
545 hashGroupsChanged = true;
546 }
547 }
548
Saurav Das62ae6792017-05-15 15:34:25 -0700549 }
550
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700551 //deal with switchDown
552 if (switchDown != null) {
pier572d4a92019-04-25 18:51:51 +0200553 processHashGroupChangeForFailure(routeChanges, switchDown);
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700554 // clear out routesChanges so a re-route is not attempted
555 routeChanges = ImmutableSet.of();
Saurav Das6430f412018-01-25 09:49:01 -0800556 hashGroupsChanged = true;
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700557 }
sanghofb7c7292015-04-13 15:15:58 -0700558 } else {
Saurav Das62ae6792017-05-15 15:34:25 -0700559 // link has gone down
560 // Compare existing ECMP SPG only with the link that went down
561 routeChanges = computeDamagedRoutes(linkDown);
pier572d4a92019-04-25 18:51:51 +0200562 processHashGroupChangeForFailure(routeChanges, null);
Saurav Das68e1b6a2018-06-11 17:02:31 -0700563 // clear out routesChanges so a re-route is not attempted
564 routeChanges = ImmutableSet.of();
565 hashGroupsChanged = true;
Saurav Dasb149be12016-06-07 10:08:06 -0700566 }
567
sanghofb7c7292015-04-13 15:15:58 -0700568 if (routeChanges.isEmpty()) {
Saurav Das6430f412018-01-25 09:49:01 -0800569 if (hashGroupsChanged) {
570 log.info("Hash-groups changed for link status change");
571 } else {
572 log.info("No re-route or re-hash attempted for the link"
573 + " status change");
574 updatedEcmpSpgMap.keySet().forEach(devId -> {
575 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
576 log.debug("Updating ECMPspg for remaining dev:{}", devId);
577 });
578 }
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700579 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sanghofb7c7292015-04-13 15:15:58 -0700580 populationStatus = Status.SUCCEEDED;
Saurav Das62ae6792017-05-15 15:34:25 -0700581 return;
sanghofb7c7292015-04-13 15:15:58 -0700582 }
583
pier572d4a92019-04-25 18:51:51 +0200584 if (hashGroupsChanged) {
585 log.debug("Hash-groups changed for link status change");
586 }
587
Saurav Das62ae6792017-05-15 15:34:25 -0700588 // reroute of routeChanges
Saurav Das261c3002017-06-13 15:35:54 -0700589 if (redoRouting(routeChanges, edgePairs, null)) {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700590 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sanghofb7c7292015-04-13 15:15:58 -0700591 populationStatus = Status.SUCCEEDED;
Saurav Das261c3002017-06-13 15:35:54 -0700592 log.info("Completed repopulation of rules for link-status change."
593 + " # of rules populated : {}", rulePopulator.getCounter());
Saurav Das62ae6792017-05-15 15:34:25 -0700594 return;
sanghofb7c7292015-04-13 15:15:58 -0700595 } else {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700596 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is ABORTED");
sanghofb7c7292015-04-13 15:15:58 -0700597 populationStatus = Status.ABORTED;
Saurav Das261c3002017-06-13 15:35:54 -0700598 log.warn("Failed to repopulate the rules for link status change.");
Saurav Das62ae6792017-05-15 15:34:25 -0700599 return;
sanghofb7c7292015-04-13 15:15:58 -0700600 }
pierdebd15c2019-04-19 20:55:53 +0200601 } catch (Exception e) {
602 log.error("populateRoutingRulesForLinkStatusChange thrown an exception: {}",
603 e.getMessage(), e);
604 populationStatus = Status.ABORTED;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900605 } finally {
606 statusLock.unlock();
sanghofb7c7292015-04-13 15:15:58 -0700607 }
608 }
609
Saurav Das62ae6792017-05-15 15:34:25 -0700610 /**
Saurav Das261c3002017-06-13 15:35:54 -0700611 * Processes a set a route-path changes by reprogramming routing rules and
612 * creating new hash-groups or editing them if necessary. This method also
613 * determines the next-hops for the route-path from the src-switch (target)
614 * of the path towards the dst-switch of the path.
Saurav Das62ae6792017-05-15 15:34:25 -0700615 *
Saurav Das261c3002017-06-13 15:35:54 -0700616 * @param routeChanges a set of route-path changes, where each route-path is
617 * a list with its first element the src-switch (target)
618 * of the path, and the second element the dst-switch of
619 * the path.
620 * @param edgePairs a set of edge-switches that are paired by configuration
621 * @param subnets a set of prefixes that need to be populated in the routing
622 * table of the target switch in the route-path. Can be null,
623 * in which case all the prefixes belonging to the dst-switch
624 * will be populated in the target switch
625 * @return true if successful in repopulating all routes
Saurav Das62ae6792017-05-15 15:34:25 -0700626 */
Saurav Das261c3002017-06-13 15:35:54 -0700627 private boolean redoRouting(Set<ArrayList<DeviceId>> routeChanges,
628 Set<EdgePair> edgePairs, Set<IpPrefix> subnets) {
629 // first make every entry two-elements
pier572d4a92019-04-25 18:51:51 +0200630 Set<ArrayList<DeviceId>> changedRoutes = getExpandedRoutes(routeChanges);
631 // no valid routes - fail fast
632 if (changedRoutes.isEmpty()) {
633 return false;
Saurav Das261c3002017-06-13 15:35:54 -0700634 }
635
pierf331a492020-01-07 15:39:39 +0100636 // Temporary stores the changed routes
637 Set<ArrayList<DeviceId>> tempRoutes = ImmutableSet.copyOf(changedRoutes);
Saurav Das261c3002017-06-13 15:35:54 -0700638 // now process changedRoutes according to edgePairs
639 if (!redoRoutingEdgePairs(edgePairs, subnets, changedRoutes)) {
640 return false; //abort routing and fail fast
641 }
pierf331a492020-01-07 15:39:39 +0100642 // Calculate the programmed routes pointing to the pairs
643 Set<ArrayList<DeviceId>> programmedPairRoutes = Sets.difference(tempRoutes, changedRoutes);
644 log.debug("Evaluating programmed pair routes");
645 storeSeenBeforeRoutes(programmedPairRoutes);
Saurav Das261c3002017-06-13 15:35:54 -0700646
pierf331a492020-01-07 15:39:39 +0100647 // Temporary stores the left routes
648 tempRoutes = ImmutableSet.copyOf(changedRoutes);
Saurav Das261c3002017-06-13 15:35:54 -0700649 // whatever is left in changedRoutes is now processed for individual dsts.
Saurav Das6430f412018-01-25 09:49:01 -0800650 Set<DeviceId> updatedDevices = Sets.newHashSet();
651 if (!redoRoutingIndividualDests(subnets, changedRoutes,
652 updatedDevices)) {
Saurav Das261c3002017-06-13 15:35:54 -0700653 return false; //abort routing and fail fast
654 }
pierf331a492020-01-07 15:39:39 +0100655 // Calculate the individual programmed routes
656 Set<ArrayList<DeviceId>> programmedIndividualRoutes = Sets.difference(tempRoutes, changedRoutes);
657 log.debug("Evaluating individual programmed routes");
658 storeSeenBeforeRoutes(programmedIndividualRoutes);
Saurav Das261c3002017-06-13 15:35:54 -0700659
Saurav Das261c3002017-06-13 15:35:54 -0700660 // update ecmpSPG for all edge-pairs
661 for (EdgePair ep : edgePairs) {
662 currentEcmpSpgMap.put(ep.dev1, updatedEcmpSpgMap.get(ep.dev1));
663 currentEcmpSpgMap.put(ep.dev2, updatedEcmpSpgMap.get(ep.dev2));
664 log.debug("Updating ECMPspg for edge-pair:{}-{}", ep.dev1, ep.dev2);
665 }
Saurav Das6430f412018-01-25 09:49:01 -0800666
667 // here is where we update all devices not touched by this instance
668 updatedEcmpSpgMap.keySet().stream()
669 .filter(devId -> !edgePairs.stream().anyMatch(ep -> ep.includes(devId)))
670 .filter(devId -> !updatedDevices.contains(devId))
671 .forEach(devId -> {
672 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
673 log.debug("Updating ECMPspg for remaining dev:{}", devId);
674 });
Saurav Das261c3002017-06-13 15:35:54 -0700675 return true;
676 }
677
678 /**
pierf331a492020-01-07 15:39:39 +0100679 * Stores the routes seen before. Routes are two-elements arrays.
680 * @param seenRoutes seen before routes
681 */
682 private void storeSeenBeforeRoutes(Set<ArrayList<DeviceId>> seenRoutes) {
683 Set<DeviceId> nextHops;
684 for (ArrayList<DeviceId> route : seenRoutes) {
685 log.debug("Route {} -> {} has been programmed", route.get(0), route.get(1));
686 nextHops = getNextHops(route.get(0), route.get(1));
687 // No valid next hops - cannot be considered a programmed route
688 if (nextHops.isEmpty()) {
689 log.debug("Could not find next hop from target:{} --> dst {} "
690 + "skipping this route", route.get(0), route.get(1));
691 continue;
692 }
693 // Already present - do not add again
694 if (seenBeforeRoutes.containsEntry(route.get(1), route.get(0))) {
695 log.debug("Route from target:{} --> dst {} " +
696 "already present, skipping this route", route.get(0), route.get(1));
697 continue;
698 }
699 seenBeforeRoutes.put(route.get(1), route.get(0));
700 }
701 }
702
703 /**
Saurav Das261c3002017-06-13 15:35:54 -0700704 * Programs targetSw in the changedRoutes for given prefixes reachable by
705 * an edgePair. If no prefixes are given, the method will use configured
706 * subnets/prefixes. If some configured subnets belong only to a specific
707 * destination in the edgePair, then the target switch will be programmed
708 * only to that destination.
709 *
710 * @param edgePairs set of edge-pairs for which target will be programmed
711 * @param subnets a set of prefixes that need to be populated in the routing
712 * table of the target switch in the changedRoutes. Can be null,
713 * in which case all the configured prefixes belonging to the
714 * paired switches will be populated in the target switch
715 * @param changedRoutes a set of route-path changes, where each route-path is
716 * a list with its first element the src-switch (target)
717 * of the path, and the second element the dst-switch of
718 * the path.
719 * @return true if successful
720 */
piera9941192019-04-24 16:12:47 +0200721 private boolean redoRoutingEdgePairs(Set<EdgePair> edgePairs, Set<IpPrefix> subnets,
722 Set<ArrayList<DeviceId>> changedRoutes) {
Saurav Das261c3002017-06-13 15:35:54 -0700723 for (EdgePair ep : edgePairs) {
724 // temp store for a target's changedRoutes to this edge-pair
725 Map<DeviceId, Set<ArrayList<DeviceId>>> targetRoutes = new HashMap<>();
726 Iterator<ArrayList<DeviceId>> i = changedRoutes.iterator();
727 while (i.hasNext()) {
728 ArrayList<DeviceId> route = i.next();
729 DeviceId dstSw = route.get(1);
730 if (ep.includes(dstSw)) {
731 // routeChange for edge pair found
732 // sort by target iff target is edge and remove from changedRoutes
733 DeviceId targetSw = route.get(0);
734 try {
735 if (!srManager.deviceConfiguration.isEdgeDevice(targetSw)) {
736 continue;
737 }
738 } catch (DeviceConfigNotFoundException e) {
739 log.warn(e.getMessage() + "aborting redoRouting");
740 return false;
741 }
742 // route is from another edge to this edge-pair
743 if (targetRoutes.containsKey(targetSw)) {
744 targetRoutes.get(targetSw).add(route);
745 } else {
746 Set<ArrayList<DeviceId>> temp = new HashSet<>();
747 temp.add(route);
748 targetRoutes.put(targetSw, temp);
749 }
750 i.remove();
751 }
752 }
753 // so now for this edgepair we have a per target set of routechanges
754 // process target->edgePair route
piera9941192019-04-24 16:12:47 +0200755 List<Future<Boolean>> futures = Lists.newArrayList();
pierf331a492020-01-07 15:39:39 +0100756 for (Entry<DeviceId, Set<ArrayList<DeviceId>>> entry :
Saurav Das261c3002017-06-13 15:35:54 -0700757 targetRoutes.entrySet()) {
758 log.debug("* redoRoutingDstPair Target:{} -> edge-pair {}",
759 entry.getKey(), ep);
piera9941192019-04-24 16:12:47 +0200760 futures.add(routePopulators.submit(new RedoRoutingEdgePair(entry.getKey(), entry.getValue(),
761 subnets, ep)));
762 }
763 if (!checkJobs(futures)) {
764 return false;
Saurav Das261c3002017-06-13 15:35:54 -0700765 }
766 // if it gets here it has succeeded for all targets to this edge-pair
767 }
768 return true;
769 }
770
piera9941192019-04-24 16:12:47 +0200771 private final class RedoRoutingEdgePair implements PickyCallable<Boolean> {
772 private DeviceId targetSw;
773 private Set<ArrayList<DeviceId>> routes;
774 private Set<IpPrefix> subnets;
775 private EdgePair ep;
776
777 /**
778 * Builds a RedoRoutingEdgePair task which provides a result.
779 *
780 * @param targetSw the target switch
781 * @param routes the changed routes
782 * @param subnets the subnets
783 * @param ep the edge pair
784 */
785 RedoRoutingEdgePair(DeviceId targetSw, Set<ArrayList<DeviceId>> routes,
786 Set<IpPrefix> subnets, EdgePair ep) {
787 this.targetSw = targetSw;
788 this.routes = routes;
789 this.subnets = subnets;
790 this.ep = ep;
791 }
792
793 @Override
794 public Boolean call() throws Exception {
795 return redoRoutingEdgePair();
796 }
797
798 @Override
799 public int hint() {
800 return targetSw.hashCode();
801 }
802
803 private boolean redoRoutingEdgePair() {
804 Map<DeviceId, Set<DeviceId>> perDstNextHops = new HashMap<>();
805 routes.forEach(route -> {
806 Set<DeviceId> nhops = getNextHops(route.get(0), route.get(1));
807 log.debug("route: target {} -> dst {} found with next-hops {}",
808 route.get(0), route.get(1), nhops);
809 perDstNextHops.put(route.get(1), nhops);
810 });
811
812 List<Set<IpPrefix>> batchedSubnetDev1, batchedSubnetDev2;
813 if (subnets != null) {
814 batchedSubnetDev1 = Lists.<Set<IpPrefix>>newArrayList(Sets.newHashSet(subnets));
815 batchedSubnetDev2 = Lists.<Set<IpPrefix>>newArrayList(Sets.newHashSet(subnets));
816 } else {
817 batchedSubnetDev1 = config.getBatchedSubnets(ep.dev1);
818 batchedSubnetDev2 = config.getBatchedSubnets(ep.dev2);
819 }
820 List<Set<IpPrefix>> batchedSubnetBoth = Streams
821 .zip(batchedSubnetDev1.stream(), batchedSubnetDev2.stream(), (a, b) -> Sets.intersection(a, b))
822 .filter(set -> !set.isEmpty())
823 .collect(Collectors.toList());
824 List<Set<IpPrefix>> batchedSubnetDev1Only = Streams
825 .zip(batchedSubnetDev1.stream(), batchedSubnetDev2.stream(), (a, b) -> Sets.difference(a, b))
826 .filter(set -> !set.isEmpty())
827 .collect(Collectors.toList());
828 List<Set<IpPrefix>> batchedSubnetDev2Only = Streams
829 .zip(batchedSubnetDev1.stream(), batchedSubnetDev2.stream(), (a, b) -> Sets.difference(b, a))
830 .filter(set -> !set.isEmpty())
831 .collect(Collectors.toList());
832
833 Set<DeviceId> nhDev1 = perDstNextHops.get(ep.dev1);
834 Set<DeviceId> nhDev2 = perDstNextHops.get(ep.dev2);
835
836 // handle routing to subnets common to edge-pair
837 // only if the targetSw is not part of the edge-pair and there
838 // exists a next hop to at least one of the devices in the edge-pair
839 if (!ep.includes(targetSw)
840 && ((nhDev1 != null && !nhDev1.isEmpty()) || (nhDev2 != null && !nhDev2.isEmpty()))) {
841 log.trace("getSubnets on both {} and {}: {}", ep.dev1, ep.dev2, batchedSubnetBoth);
842 for (Set<IpPrefix> prefixes : batchedSubnetBoth) {
843 if (!populateEcmpRoutingRulePartial(targetSw, ep.dev1, ep.dev2,
844 perDstNextHops, prefixes)) {
845 return false; // abort everything and fail fast
846 }
847 }
848
849 }
850 // handle routing to subnets that only belong to dev1 only if
851 // a next-hop exists from the target to dev1
852 if (!batchedSubnetDev1Only.isEmpty() &&
853 batchedSubnetDev1Only.stream().anyMatch(subnet -> !subnet.isEmpty()) &&
854 nhDev1 != null && !nhDev1.isEmpty()) {
855 Map<DeviceId, Set<DeviceId>> onlyDev1NextHops = new HashMap<>();
856 onlyDev1NextHops.put(ep.dev1, nhDev1);
857 log.trace("getSubnets on {} only: {}", ep.dev1, batchedSubnetDev1Only);
858 for (Set<IpPrefix> prefixes : batchedSubnetDev1Only) {
859 if (!populateEcmpRoutingRulePartial(targetSw, ep.dev1, null,
860 onlyDev1NextHops, prefixes)) {
861 return false; // abort everything and fail fast
862 }
863 }
864 }
865 // handle routing to subnets that only belong to dev2 only if
866 // a next-hop exists from the target to dev2
867 if (!batchedSubnetDev2Only.isEmpty() &&
868 batchedSubnetDev2Only.stream().anyMatch(subnet -> !subnet.isEmpty()) &&
869 nhDev2 != null && !nhDev2.isEmpty()) {
870 Map<DeviceId, Set<DeviceId>> onlyDev2NextHops = new HashMap<>();
871 onlyDev2NextHops.put(ep.dev2, nhDev2);
872 log.trace("getSubnets on {} only: {}", ep.dev2, batchedSubnetDev2Only);
873 for (Set<IpPrefix> prefixes : batchedSubnetDev2Only) {
874 if (!populateEcmpRoutingRulePartial(targetSw, ep.dev2, null,
875 onlyDev2NextHops, prefixes)) {
876 return false; // abort everything and fail fast
877 }
878 }
879 }
880 return true;
881 }
882 }
883
Saurav Das261c3002017-06-13 15:35:54 -0700884 /**
885 * Programs targetSw in the changedRoutes for given prefixes reachable by
886 * a destination switch that is not part of an edge-pair.
887 * If no prefixes are given, the method will use configured subnets/prefixes.
888 *
889 * @param subnets a set of prefixes that need to be populated in the routing
890 * table of the target switch in the changedRoutes. Can be null,
891 * in which case all the configured prefixes belonging to the
892 * paired switches will be populated in the target switch
893 * @param changedRoutes a set of route-path changes, where each route-path is
894 * a list with its first element the src-switch (target)
895 * of the path, and the second element the dst-switch of
896 * the path.
897 * @return true if successful
898 */
piera9941192019-04-24 16:12:47 +0200899 private boolean redoRoutingIndividualDests(Set<IpPrefix> subnets, Set<ArrayList<DeviceId>> changedRoutes,
Saurav Das6430f412018-01-25 09:49:01 -0800900 Set<DeviceId> updatedDevices) {
Saurav Das261c3002017-06-13 15:35:54 -0700901 // aggregate route-path changes for each dst device
902 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> routesBydevice =
903 new HashMap<>();
904 for (ArrayList<DeviceId> route: changedRoutes) {
905 DeviceId dstSw = route.get(1);
906 ArrayList<ArrayList<DeviceId>> deviceRoutes =
907 routesBydevice.get(dstSw);
908 if (deviceRoutes == null) {
909 deviceRoutes = new ArrayList<>();
910 routesBydevice.put(dstSw, deviceRoutes);
911 }
912 deviceRoutes.add(route);
913 }
piera9941192019-04-24 16:12:47 +0200914 // iterate over the impacted devices
Saurav Das261c3002017-06-13 15:35:54 -0700915 for (DeviceId impactedDstDevice : routesBydevice.keySet()) {
916 ArrayList<ArrayList<DeviceId>> deviceRoutes =
917 routesBydevice.get(impactedDstDevice);
piera9941192019-04-24 16:12:47 +0200918 List<Future<Boolean>> futures = Lists.newArrayList();
Saurav Das261c3002017-06-13 15:35:54 -0700919 for (ArrayList<DeviceId> route: deviceRoutes) {
920 log.debug("* redoRoutingIndiDst Target: {} -> dst: {}",
921 route.get(0), route.get(1));
piera9941192019-04-24 16:12:47 +0200922 futures.add(routePopulators.submit(new RedoRoutingIndividualDest(subnets, route)));
pierf331a492020-01-07 15:39:39 +0100923 changedRoutes.remove(route);
piera9941192019-04-24 16:12:47 +0200924 }
925 // check the execution of each job
926 if (!checkJobs(futures)) {
927 return false;
Saurav Das261c3002017-06-13 15:35:54 -0700928 }
929 //Only if all the flows for all impacted routes to a
930 //specific target are pushed successfully, update the
931 //ECMP graph for that target. Or else the next event
932 //would not see any changes in the ECMP graphs.
933 //In another case, the target switch has gone away, so
934 //routes can't be installed. In that case, the current map
935 //is updated here, without any flows being pushed.
936 currentEcmpSpgMap.put(impactedDstDevice,
937 updatedEcmpSpgMap.get(impactedDstDevice));
Saurav Das6430f412018-01-25 09:49:01 -0800938 updatedDevices.add(impactedDstDevice);
Saurav Das261c3002017-06-13 15:35:54 -0700939 log.debug("Updating ECMPspg for impacted dev:{}", impactedDstDevice);
940 }
941 return true;
942 }
943
piera9941192019-04-24 16:12:47 +0200944 private final class RedoRoutingIndividualDest implements PickyCallable<Boolean> {
945 private DeviceId targetSw;
946 private ArrayList<DeviceId> route;
947 private Set<IpPrefix> subnets;
948
949 /**
950 * Builds a RedoRoutingIndividualDest task, which provides a result.
951 *
952 * @param subnets a set of prefixes
953 * @param route a route-path change
954 */
955 RedoRoutingIndividualDest(Set<IpPrefix> subnets, ArrayList<DeviceId> route) {
956 this.targetSw = route.get(0);
957 this.route = route;
958 this.subnets = subnets;
959 }
960
961 @Override
962 public Boolean call() throws Exception {
963 DeviceId dstSw = route.get(1); // same as impactedDstDevice
964 Set<DeviceId> nextHops = getNextHops(targetSw, dstSw);
965 if (nextHops.isEmpty()) {
966 log.debug("Could not find next hop from target:{} --> dst {} "
967 + "skipping this route", targetSw, dstSw);
968 return true;
969 }
970 Map<DeviceId, Set<DeviceId>> nhops = new HashMap<>();
971 nhops.put(dstSw, nextHops);
972 if (!populateEcmpRoutingRulePartial(targetSw, dstSw, null, nhops,
973 (subnets == null) ? Sets.newHashSet() : subnets)) {
974 return false; // abort routing and fail fast
975 }
976 log.debug("Populating flow rules from target: {} to dst: {}"
977 + " is successful", targetSw, dstSw);
978 return true;
979 }
980
981 @Override
982 public int hint() {
983 return targetSw.hashCode();
984 }
985 }
986
Saurav Das261c3002017-06-13 15:35:54 -0700987 /**
988 * Populate ECMP rules for subnets from target to destination via nexthops.
989 *
990 * @param targetSw Device ID of target switch in which rules will be programmed
991 * @param destSw1 Device ID of final destination switch to which the rules will forward
992 * @param destSw2 Device ID of paired destination switch to which the rules will forward
993 * A null deviceId indicates packets should only be sent to destSw1
Saurav Das97241862018-02-14 14:14:54 -0800994 * @param nextHops Map of a set of next hops per destSw
Saurav Das261c3002017-06-13 15:35:54 -0700995 * @param subnets Subnets to be populated. If empty, populate all configured subnets.
996 * @return true if it succeeds in populating rules
997 */ // refactor
piera9941192019-04-24 16:12:47 +0200998 private boolean populateEcmpRoutingRulePartial(DeviceId targetSw, DeviceId destSw1, DeviceId destSw2,
999 Map<DeviceId, Set<DeviceId>> nextHops, Set<IpPrefix> subnets) {
Saurav Das261c3002017-06-13 15:35:54 -07001000 boolean result;
1001 // If both target switch and dest switch are edge routers, then set IP
1002 // rule for both subnet and router IP.
1003 boolean targetIsEdge;
1004 boolean dest1IsEdge;
1005 Ip4Address dest1RouterIpv4, dest2RouterIpv4 = null;
1006 Ip6Address dest1RouterIpv6, dest2RouterIpv6 = null;
1007
1008 try {
1009 targetIsEdge = config.isEdgeDevice(targetSw);
1010 dest1IsEdge = config.isEdgeDevice(destSw1);
1011 dest1RouterIpv4 = config.getRouterIpv4(destSw1);
1012 dest1RouterIpv6 = config.getRouterIpv6(destSw1);
1013 if (destSw2 != null) {
1014 dest2RouterIpv4 = config.getRouterIpv4(destSw2);
1015 dest2RouterIpv6 = config.getRouterIpv6(destSw2);
1016 }
1017 } catch (DeviceConfigNotFoundException e) {
1018 log.warn(e.getMessage() + " Aborting populateEcmpRoutingRulePartial.");
Saurav Das62ae6792017-05-15 15:34:25 -07001019 return false;
1020 }
Saurav Das261c3002017-06-13 15:35:54 -07001021
1022 if (targetIsEdge && dest1IsEdge) {
Charles Chan19b70032019-04-17 14:20:26 -07001023 List<Set<IpPrefix>> batchedSubnets;
1024 if (subnets != null && !subnets.isEmpty()) {
1025 batchedSubnets = Lists.<Set<IpPrefix>>newArrayList(Sets.newHashSet(subnets));
1026 } else {
1027 batchedSubnets = config.getBatchedSubnets(destSw1);
1028 }
Saurav Das97241862018-02-14 14:14:54 -08001029 // XXX - Rethink this - ignoring routerIPs in all other switches
1030 // even edge to edge switches
Saurav Das261c3002017-06-13 15:35:54 -07001031 /*subnets.add(dest1RouterIpv4.toIpPrefix());
1032 if (dest1RouterIpv6 != null) {
1033 subnets.add(dest1RouterIpv6.toIpPrefix());
1034 }
1035 if (destSw2 != null && dest2RouterIpv4 != null) {
1036 subnets.add(dest2RouterIpv4.toIpPrefix());
1037 if (dest2RouterIpv6 != null) {
1038 subnets.add(dest2RouterIpv6.toIpPrefix());
1039 }
1040 }*/
Charles Chan19b70032019-04-17 14:20:26 -07001041 log.trace("getSubnets on {}: {}", destSw1, batchedSubnets);
1042 for (Set<IpPrefix> prefixes : batchedSubnets) {
1043 log.debug(". populateEcmpRoutingRulePartial in device {} towards {} {} "
1044 + "for subnets {}", targetSw, destSw1,
1045 (destSw2 != null) ? ("& " + destSw2) : "",
1046 prefixes);
1047 if (!rulePopulator.populateIpRuleForSubnet(targetSw, prefixes, destSw1, destSw2, nextHops)) {
1048 return false;
1049 }
Saurav Das261c3002017-06-13 15:35:54 -07001050 }
Saurav Das62ae6792017-05-15 15:34:25 -07001051 }
Saurav Das261c3002017-06-13 15:35:54 -07001052
1053 if (!targetIsEdge && dest1IsEdge) {
1054 // MPLS rules in all non-edge target devices. These rules are for
1055 // individual destinations, even if the dsts are part of edge-pairs.
1056 log.debug(". populateEcmpRoutingRulePartial in device{} towards {} for "
1057 + "all MPLS rules", targetSw, destSw1);
piera9941192019-04-24 16:12:47 +02001058 result = rulePopulator.populateMplsRule(targetSw, destSw1, nextHops.get(destSw1), dest1RouterIpv4);
Saurav Das261c3002017-06-13 15:35:54 -07001059 if (!result) {
1060 return false;
1061 }
1062 if (dest1RouterIpv6 != null) {
Saurav Das97241862018-02-14 14:14:54 -08001063 int v4sid = 0, v6sid = 0;
1064 try {
1065 v4sid = config.getIPv4SegmentId(destSw1);
1066 v6sid = config.getIPv6SegmentId(destSw1);
1067 } catch (DeviceConfigNotFoundException e) {
1068 log.warn(e.getMessage());
1069 }
1070 if (v4sid != v6sid) {
piera9941192019-04-24 16:12:47 +02001071 result = rulePopulator.populateMplsRule(targetSw, destSw1, nextHops.get(destSw1),
Saurav Das97241862018-02-14 14:14:54 -08001072 dest1RouterIpv6);
1073 if (!result) {
1074 return false;
1075 }
Saurav Das261c3002017-06-13 15:35:54 -07001076 }
1077 }
1078 }
1079
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -07001080 if (!targetIsEdge && !dest1IsEdge) {
1081 // MPLS rules for inter-connected spines
1082 // can be merged with above if, left it here for clarity
1083 log.debug(". populateEcmpRoutingRulePartial in device{} towards {} for "
1084 + "all MPLS rules", targetSw, destSw1);
1085
piera9941192019-04-24 16:12:47 +02001086 result = rulePopulator.populateMplsRule(targetSw, destSw1, nextHops.get(destSw1), dest1RouterIpv4);
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -07001087 if (!result) {
1088 return false;
1089 }
1090
1091 if (dest1RouterIpv6 != null) {
1092 int v4sid = 0, v6sid = 0;
1093 try {
1094 v4sid = config.getIPv4SegmentId(destSw1);
1095 v6sid = config.getIPv6SegmentId(destSw1);
1096 } catch (DeviceConfigNotFoundException e) {
1097 log.warn(e.getMessage());
1098 }
1099 if (v4sid != v6sid) {
piera9941192019-04-24 16:12:47 +02001100 result = rulePopulator.populateMplsRule(targetSw, destSw1, nextHops.get(destSw1),
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -07001101 dest1RouterIpv6);
1102 if (!result) {
1103 return false;
1104 }
1105 }
1106 }
1107 }
1108
Saurav Das261c3002017-06-13 15:35:54 -07001109 // To save on ECMP groups
1110 // avoid MPLS rules in non-edge-devices to non-edge-devices
1111 // avoid MPLS transit rules in edge-devices
1112 // avoid loopback IP rules in edge-devices to non-edge-devices
1113 return true;
Saurav Das62ae6792017-05-15 15:34:25 -07001114 }
1115
1116 /**
pier572d4a92019-04-25 18:51:51 +02001117 * Processes a set a route-path changes due to a switch/link failure by editing hash groups.
Saurav Das62ae6792017-05-15 15:34:25 -07001118 *
1119 * @param routeChanges a set of route-path changes, where each route-path is
1120 * a list with its first element the src-switch of the path
1121 * and the second element the dst-switch of the path.
Saurav Das62ae6792017-05-15 15:34:25 -07001122 * @param failedSwitch the switchId if the route changes are for a failed switch,
1123 * otherwise null
1124 */
pier572d4a92019-04-25 18:51:51 +02001125 private void processHashGroupChangeForFailure(Set<ArrayList<DeviceId>> routeChanges,
1126 DeviceId failedSwitch) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001127 // first, ensure each routeChanges entry has two elements
pier572d4a92019-04-25 18:51:51 +02001128 Set<ArrayList<DeviceId>> changedRoutes = getAllExpandedRoutes(routeChanges);
Saurav Das6430f412018-01-25 09:49:01 -08001129 boolean someFailed = false;
pier572d4a92019-04-25 18:51:51 +02001130 boolean success;
Saurav Das6430f412018-01-25 09:49:01 -08001131 Set<DeviceId> updatedDevices = Sets.newHashSet();
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001132 for (ArrayList<DeviceId> route : changedRoutes) {
1133 DeviceId targetSw = route.get(0);
1134 DeviceId dstSw = route.get(1);
pier572d4a92019-04-25 18:51:51 +02001135 success = fixHashGroupsForRoute(route, true);
1136 // it's possible that we cannot fix hash groups for a route
1137 // if the target switch has failed. Nevertheless the ecmp graph
1138 // for the impacted switch must still be updated.
1139 if (!success && failedSwitch != null && targetSw.equals(failedSwitch)) {
1140 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
1141 currentEcmpSpgMap.remove(targetSw);
1142 log.debug("Updating ECMPspg for dst:{} removing failed switch "
1143 + "target:{}", dstSw, targetSw);
1144 updatedDevices.add(targetSw);
1145 updatedDevices.add(dstSw);
1146 continue;
pierf331a492020-01-07 15:39:39 +01001147
pier572d4a92019-04-25 18:51:51 +02001148 }
1149 //linkfailed - update both sides
1150 if (success) {
1151 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
1152 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
1153 log.debug("Updating ECMPspg for dst:{} and target:{} for linkdown"
1154 + " or switchdown", dstSw, targetSw);
1155 updatedDevices.add(targetSw);
1156 updatedDevices.add(dstSw);
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001157 } else {
pier572d4a92019-04-25 18:51:51 +02001158 someFailed = true;
Saurav Das62ae6792017-05-15 15:34:25 -07001159 }
1160 }
Saurav Das6430f412018-01-25 09:49:01 -08001161 if (!someFailed) {
1162 // here is where we update all devices not touched by this instance
1163 updatedEcmpSpgMap.keySet().stream()
1164 .filter(devId -> !updatedDevices.contains(devId))
1165 .forEach(devId -> {
1166 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
1167 log.debug("Updating ECMPspg for remaining dev:{}", devId);
1168 });
1169 }
Saurav Das62ae6792017-05-15 15:34:25 -07001170 }
1171
1172 /**
pier572d4a92019-04-25 18:51:51 +02001173 * Processes a set a route-path changes due to link up by editing hash groups.
1174 *
1175 * @param routeChanges a set of route-path changes, where each route-path is
1176 * a list with its first element the src-switch of the path
1177 * and the second element the dst-switch of the path.
1178 * @return set of changed routes
1179 */
1180 private Set<ArrayList<DeviceId>> processHashGroupChangeForLinkUp(Set<ArrayList<DeviceId>> routeChanges) {
1181 // Stores changed routes
1182 Set<ArrayList<DeviceId>> doneRoutes = new HashSet<>();
1183 // first, ensure each routeChanges entry has two elements
1184 Set<ArrayList<DeviceId>> changedRoutes = getAllExpandedRoutes(routeChanges);
1185 boolean someFailed = false;
1186 boolean success;
1187 Set<DeviceId> updatedDevices = Sets.newHashSet();
1188 for (ArrayList<DeviceId> route : changedRoutes) {
1189 DeviceId targetSw = route.get(0);
1190 DeviceId dstSw = route.get(1);
1191 // linkup - fix (if possible)
1192 success = fixHashGroupsForRoute(route, false);
1193 if (success) {
1194 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
1195 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
1196 log.debug("Updating ECMPspg for target:{} and dst:{} for linkup",
1197 targetSw, dstSw);
1198 updatedDevices.add(targetSw);
1199 updatedDevices.add(dstSw);
1200 doneRoutes.add(route);
1201 } else {
1202 someFailed = true;
1203 }
1204
1205 }
1206 if (!someFailed) {
1207 // here is where we update all devices not touched by this instance
1208 updatedEcmpSpgMap.keySet().stream()
1209 .filter(devId -> !updatedDevices.contains(devId))
1210 .forEach(devId -> {
1211 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
1212 log.debug("Updating ECMPspg for remaining dev:{}", devId);
1213 });
1214 }
1215 return doneRoutes;
1216 }
1217
1218 /**
Saurav Das62ae6792017-05-15 15:34:25 -07001219 * Edits hash groups in the src-switch (targetSw) of a route-path by
1220 * calling the groupHandler to either add or remove buckets in an existing
1221 * hash group.
1222 *
1223 * @param route a single list representing a route-path where the first element
1224 * is the src-switch (targetSw) of the route-path and the
1225 * second element is the dst-switch
1226 * @param revoke true if buckets in the hash-groups need to be removed;
1227 * false if buckets in the hash-groups need to be added
1228 * @return true if the hash group editing is successful
1229 */
1230 private boolean fixHashGroupsForRoute(ArrayList<DeviceId> route,
1231 boolean revoke) {
1232 DeviceId targetSw = route.get(0);
1233 if (route.size() < 2) {
1234 log.warn("Cannot fixHashGroupsForRoute - no dstSw in route {}", route);
1235 return false;
1236 }
1237 DeviceId destSw = route.get(1);
pierf331a492020-01-07 15:39:39 +01001238 if (!seenBeforeRoutes.containsEntry(destSw, targetSw)) {
1239 log.warn("Cannot fixHashGroupsForRoute {} -> {} has not been programmed before",
1240 targetSw, destSw);
1241 return false;
1242 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001243 log.debug("* processing fixHashGroupsForRoute: Target {} -> Dest {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001244 targetSw, destSw);
Saurav Das62ae6792017-05-15 15:34:25 -07001245 // figure out the new next hops at the targetSw towards the destSw
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001246 Set<DeviceId> nextHops = getNextHops(targetSw, destSw);
Saurav Das62ae6792017-05-15 15:34:25 -07001247 // call group handler to change hash group at targetSw
1248 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
1249 if (grpHandler == null) {
1250 log.warn("Cannot find grouphandler for dev:{} .. aborting"
1251 + " {} hash group buckets for route:{} ", targetSw,
1252 (revoke) ? "revoke" : "repopulate", route);
1253 return false;
1254 }
Saurav Das68e1b6a2018-06-11 17:02:31 -07001255 log.debug("{} hash-groups buckets For Route {} -> {} to new next-hops {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001256 (revoke) ? "revoke" : "repopulating",
1257 targetSw, destSw, nextHops);
1258 return (revoke) ? grpHandler.fixHashGroups(targetSw, nextHops,
1259 destSw, true)
1260 : grpHandler.fixHashGroups(targetSw, nextHops,
1261 destSw, false);
1262 }
1263
1264 /**
Saurav Das261c3002017-06-13 15:35:54 -07001265 * Start the flow rule population process if it was never started. The
1266 * process finishes successfully when all flow rules are set and stops with
1267 * ABORTED status when any groups required for flows is not set yet.
Saurav Das62ae6792017-05-15 15:34:25 -07001268 */
Saurav Das261c3002017-06-13 15:35:54 -07001269 public void startPopulationProcess() {
1270 statusLock.lock();
1271 try {
1272 if (populationStatus == Status.IDLE
1273 || populationStatus == Status.SUCCEEDED
1274 || populationStatus == Status.ABORTED) {
1275 populateAllRoutingRules();
sangho28d0b6d2015-05-07 13:30:57 -07001276 } else {
Saurav Das261c3002017-06-13 15:35:54 -07001277 log.warn("Not initiating startPopulationProcess as populationStatus is {}",
1278 populationStatus);
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001279 }
Saurav Das261c3002017-06-13 15:35:54 -07001280 } finally {
1281 statusLock.unlock();
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001282 }
sanghofb7c7292015-04-13 15:15:58 -07001283 }
1284
Saurav Dasb149be12016-06-07 10:08:06 -07001285 /**
Saurav Das261c3002017-06-13 15:35:54 -07001286 * Revoke rules of given subnet in all edge switches.
1287 *
1288 * @param subnets subnet being removed
1289 * @return true if succeed
1290 */
1291 protected boolean revokeSubnet(Set<IpPrefix> subnets) {
piera9941192019-04-24 16:12:47 +02001292 DeviceId targetSw;
1293 List<Future<Boolean>> futures = Lists.newArrayList();
1294 for (Device sw : srManager.deviceService.getAvailableDevices()) {
1295 targetSw = sw.id();
1296 if (shouldProgram(targetSw)) {
1297 futures.add(routePopulators.submit(new RevokeSubnet(targetSw, subnets)));
1298 } else {
1299 futures.add(CompletableFuture.completedFuture(true));
1300 }
1301 }
1302 // check the execution of each job
1303 return checkJobs(futures);
1304 }
1305
1306 private final class RevokeSubnet implements PickyCallable<Boolean> {
1307 private DeviceId targetSw;
1308 private Set<IpPrefix> subnets;
1309
1310 /**
1311 * Builds a RevokeSubnet task, which provides a result.
1312 *
1313 * @param subnets a set of prefixes
1314 * @param targetSw target switch
1315 */
1316 RevokeSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
1317 this.targetSw = targetSw;
1318 this.subnets = subnets;
1319 }
1320
1321 @Override
1322 public Boolean call() throws Exception {
1323 return srManager.routingRulePopulator.revokeIpRuleForSubnet(targetSw, subnets);
1324 }
1325
1326 @Override
1327 public int hint() {
1328 return targetSw.hashCode();
Saurav Das261c3002017-06-13 15:35:54 -07001329 }
1330 }
1331
1332 /**
Charles Chan910be6a2017-08-23 14:46:43 -07001333 * Populates IP rules for a route that has direct connection to the switch
1334 * if the current instance is the master of the switch.
1335 *
1336 * @param deviceId device ID of the device that next hop attaches to
1337 * @param prefix IP prefix of the route
1338 * @param hostMac MAC address of the next hop
1339 * @param hostVlanId Vlan ID of the nexthop
1340 * @param outPort port where the next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001341 * @param directHost host is of type direct or indirect
Charles Chan910be6a2017-08-23 14:46:43 -07001342 */
1343 void populateRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001344 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Charles Chand66d6712018-03-29 16:03:41 -07001345 if (shouldProgram(deviceId)) {
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001346 srManager.routingRulePopulator.populateRoute(deviceId, prefix, hostMac, hostVlanId, outPort, directHost);
Charles Chan910be6a2017-08-23 14:46:43 -07001347 }
1348 }
1349
1350 /**
1351 * Removes IP rules for a route when the next hop is gone.
1352 * if the current instance is the master of the switch.
1353 *
1354 * @param deviceId device ID of the device that next hop attaches to
1355 * @param prefix IP prefix of the route
1356 * @param hostMac MAC address of the next hop
1357 * @param hostVlanId Vlan ID of the nexthop
1358 * @param outPort port that next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001359 * @param directHost host is of type direct or indirect
Charles Chan910be6a2017-08-23 14:46:43 -07001360 */
1361 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001362 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Charles Chand66d6712018-03-29 16:03:41 -07001363 if (shouldProgram(deviceId)) {
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001364 srManager.routingRulePopulator.revokeRoute(deviceId, prefix, hostMac, hostVlanId, outPort, directHost);
Charles Chan910be6a2017-08-23 14:46:43 -07001365 }
1366 }
1367
Charles Chand66d6712018-03-29 16:03:41 -07001368 void populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
1369 if (shouldProgram(deviceId)) {
1370 srManager.routingRulePopulator.populateBridging(deviceId, port, mac, vlanId);
1371 }
1372 }
1373
1374 void revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
1375 if (shouldProgram(deviceId)) {
1376 srManager.routingRulePopulator.revokeBridging(deviceId, port, mac, vlanId);
1377 }
1378 }
1379
1380 void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
1381 VlanId vlanId, boolean popVlan, boolean install) {
1382 if (shouldProgram(deviceId)) {
1383 srManager.routingRulePopulator.updateBridging(deviceId, portNum, hostMac, vlanId, popVlan, install);
1384 }
1385 }
1386
1387 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1388 VlanId vlanId, boolean popVlan, boolean install) {
1389 if (shouldProgram(deviceId)) {
1390 srManager.routingRulePopulator.updateFwdObj(deviceId, portNumber, prefix, hostMac,
1391 vlanId, popVlan, install);
1392 }
1393 }
1394
Charles Chan910be6a2017-08-23 14:46:43 -07001395 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001396 * Populates IP rules for a route when the next hop is double-tagged.
1397 *
1398 * @param deviceId device ID that next hop attaches to
1399 * @param prefix IP prefix of the route
1400 * @param hostMac MAC address of the next hop
1401 * @param innerVlan Inner Vlan ID of the next hop
1402 * @param outerVlan Outer Vlan ID of the next hop
1403 * @param outerTpid Outer TPID of the next hop
1404 * @param outPort port that the next hop attaches to
1405 */
1406 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId innerVlan,
1407 VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1408 if (srManager.mastershipService.isLocalMaster(deviceId)) {
Charles Chan61c086d2019-07-26 17:46:15 -07001409 srManager.routingRulePopulator.populateDoubleTaggedRoute(
1410 deviceId, prefix, hostMac, innerVlan, outerVlan, outerTpid, outPort);
1411 srManager.routingRulePopulator.processDoubleTaggedFilter(
1412 deviceId, outPort, outerVlan, innerVlan, true);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001413 }
1414 }
1415
1416 /**
1417 * Revokes IP rules for a route when the next hop is double-tagged.
1418 *
1419 * @param deviceId device ID that next hop attaches to
1420 * @param prefix IP prefix of the route
1421 * @param hostMac MAC address of the next hop
1422 * @param innerVlan Inner Vlan ID of the next hop
1423 * @param outerVlan Outer Vlan ID of the next hop
1424 * @param outerTpid Outer TPID of the next hop
1425 * @param outPort port that the next hop attaches to
1426 */
1427 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId innerVlan,
1428 VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1429 // Revoke route either if this node have the mastership (when device is available) or
1430 // if this node is the leader (even when device is unavailable)
1431 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1432 if (srManager.deviceService.isAvailable(deviceId)) {
1433 // Master node will revoke specified rule.
1434 log.debug("This node is not a master for {}, stop revoking route.", deviceId);
1435 return;
1436 }
1437
1438 // isLocalMaster will return false when the device is unavailable.
1439 // Verify if this node is the leader in that case.
1440 NodeId leader = srManager.leadershipService.runForLeadership(
1441 deviceId.toString()).leaderNodeId();
1442 if (!srManager.clusterService.getLocalNode().id().equals(leader)) {
1443 // Leader node will revoke specified rule.
1444 log.debug("This node is not a master for {}, stop revoking route.", deviceId);
1445 return;
1446 }
1447 }
1448
Charles Chan61c086d2019-07-26 17:46:15 -07001449 srManager.routingRulePopulator.revokeDoubleTaggedRoute(deviceId, prefix, hostMac,
1450 innerVlan, outerVlan, outerTpid, outPort);
1451 srManager.routingRulePopulator.processDoubleTaggedFilter(deviceId, outPort, outerVlan, innerVlan, false);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001452 }
1453
pierf331a492020-01-07 15:39:39 +01001454 /**
1455 * Purges seen before routes for a given device.
1456 * @param deviceId the device id
1457 */
1458 void purgeSeenBeforeRoutes(DeviceId deviceId) {
1459 log.debug("Purging seen before routes having as target {}", deviceId);
1460 Set<Entry<DeviceId, DeviceId>> routesToPurge = seenBeforeRoutes.stream()
1461 .filter(entry -> entry.getValue().equals(deviceId))
1462 .collect(Collectors.toSet());
1463 routesToPurge.forEach(entry -> seenBeforeRoutes.remove(entry.getKey(), entry.getValue()));
1464 }
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001465
1466 /**
Saurav Das261c3002017-06-13 15:35:54 -07001467 * Remove ECMP graph entry for the given device. Typically called when
1468 * device is no longer available.
1469 *
1470 * @param deviceId the device for which graphs need to be purged
1471 */
Charles Chanfbcb8812018-04-18 18:41:05 -07001472 void purgeEcmpGraph(DeviceId deviceId) {
Saurav Das6430f412018-01-25 09:49:01 -08001473 statusLock.lock();
1474 try {
Saurav Das6430f412018-01-25 09:49:01 -08001475 if (populationStatus == Status.STARTED) {
1476 log.warn("Previous rule population is not finished. Cannot"
1477 + " proceeed with purgeEcmpGraph for {}", deviceId);
1478 return;
1479 }
1480 log.debug("Updating ECMPspg for unavailable dev:{}", deviceId);
1481 currentEcmpSpgMap.remove(deviceId);
1482 if (updatedEcmpSpgMap != null) {
1483 updatedEcmpSpgMap.remove(deviceId);
1484 }
1485 } finally {
1486 statusLock.unlock();
Saurav Das261c3002017-06-13 15:35:54 -07001487 }
1488 }
1489
Saurav Das00e553b2018-04-21 17:19:48 -07001490 /**
1491 * Attempts a full reroute of route-paths if topology has changed relatively
1492 * close to a mastership change event. Does not do a reroute if mastership
1493 * change is due to reasons other than a ONOS cluster event - for example a
1494 * call to balance-masters, or a switch up/down event.
1495 *
1496 * @param devId the device identifier for which mastership has changed
1497 * @param me the mastership event
1498 */
1499 void checkFullRerouteForMasterChange(DeviceId devId, MastershipEvent me) {
1500 // give small delay to absorb mastership events that are caused by
1501 // device that has disconnected from cluster
Saurav Das49368392018-04-23 18:42:12 -07001502 executorServiceMstChg.schedule(new MasterChange(devId, me),
1503 MASTER_CHANGE_DELAY, TimeUnit.MILLISECONDS);
Saurav Das00e553b2018-04-21 17:19:48 -07001504 }
1505
1506 protected final class MasterChange implements Runnable {
1507 private DeviceId devId;
1508 private MastershipEvent me;
1509 private static final long CLUSTER_EVENT_THRESHOLD = 4500; // ms
1510 private static final long DEVICE_EVENT_THRESHOLD = 2000; // ms
Saurav Dasec683dc2018-04-27 18:42:30 -07001511 private static final long EDGE_PORT_EVENT_THRESHOLD = 10000; //ms
Saurav Das68e1b6a2018-06-11 17:02:31 -07001512 private static final long FULL_REROUTE_THRESHOLD = 10000; // ms
Saurav Das00e553b2018-04-21 17:19:48 -07001513
1514 MasterChange(DeviceId devId, MastershipEvent me) {
1515 this.devId = devId;
1516 this.me = me;
1517 }
1518
1519 @Override
1520 public void run() {
1521 long lce = srManager.clusterListener.timeSinceLastClusterEvent();
1522 boolean clusterEvent = lce < CLUSTER_EVENT_THRESHOLD;
1523
1524 // ignore event for lost switch if cluster event hasn't happened -
1525 // device down event will handle it
1526 if ((me.roleInfo().master() == null
1527 || !srManager.deviceService.isAvailable(devId))
1528 && !clusterEvent) {
1529 log.debug("Full reroute not required for lost device: {}/{} "
1530 + "clusterEvent/timeSince: {}/{}",
1531 devId, me.roleInfo(), clusterEvent, lce);
1532 return;
1533 }
1534
1535 long update = srManager.deviceService.getLastUpdatedInstant(devId);
1536 long lde = Instant.now().toEpochMilli() - update;
1537 boolean deviceEvent = lde < DEVICE_EVENT_THRESHOLD;
1538
1539 // ignore event for recently connected switch if cluster event hasn't
1540 // happened - link up events will handle it
1541 if (srManager.deviceService.isAvailable(devId) && deviceEvent
1542 && !clusterEvent) {
1543 log.debug("Full reroute not required for recently available"
1544 + " device: {}/{} deviceEvent/timeSince: {}/{} "
1545 + "clusterEvent/timeSince: {}/{}",
1546 devId, me.roleInfo(), deviceEvent, lde, clusterEvent, lce);
1547 return;
1548 }
1549
Saurav Dasec683dc2018-04-27 18:42:30 -07001550 long lepe = Instant.now().toEpochMilli()
1551 - srManager.lastEdgePortEvent.toEpochMilli();
1552 boolean edgePortEvent = lepe < EDGE_PORT_EVENT_THRESHOLD;
1553
Saurav Das00e553b2018-04-21 17:19:48 -07001554 // if it gets here, then mastership change is likely due to onos
1555 // instance failure, or network partition in onos cluster
1556 // normally a mastership change like this does not require re-programming
1557 // but if topology changes happen at the same time then we may miss events
1558 if (!isRoutingStable() && clusterEvent) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001559 log.warn("Mastership changed for dev: {}/{} while programming route-paths "
Saurav Das00e553b2018-04-21 17:19:48 -07001560 + "due to clusterEvent {} ms ago .. attempting full reroute",
1561 devId, me.roleInfo(), lce);
1562 if (srManager.mastershipService.isLocalMaster(devId)) {
1563 // old master could have died when populating filters
1564 populatePortAddressingRules(devId);
1565 }
Saurav Das68e1b6a2018-06-11 17:02:31 -07001566 // old master could have died when creating groups
Saurav Das00e553b2018-04-21 17:19:48 -07001567 // XXX right now we have no fine-grained way to only make changes
Saurav Das68e1b6a2018-06-11 17:02:31 -07001568 // for the route paths affected by this device. Thus we do a
1569 // full reroute after purging all hash groups. We also try to do
1570 // it only once, irrespective of the number of devices
1571 // that changed mastership when their master instance died.
1572 long lfrr = Instant.now().toEpochMilli() - lastFullReroute.toEpochMilli();
1573 boolean doFullReroute = lfrr > FULL_REROUTE_THRESHOLD;
1574 if (doFullReroute) {
1575 lastFullReroute = Instant.now();
1576 for (Device dev : srManager.deviceService.getDevices()) {
1577 if (shouldProgram(dev.id())) {
1578 srManager.purgeHashedNextObjectiveStore(dev.id());
pierf331a492020-01-07 15:39:39 +01001579 seenBeforeRoutes.removeAll(dev.id());
Saurav Das68e1b6a2018-06-11 17:02:31 -07001580 }
1581 }
1582 // give small delay to ensure entire store is purged
1583 executorServiceFRR.schedule(new FullRerouteAfterPurge(),
1584 PURGE_DELAY,
1585 TimeUnit.MILLISECONDS);
1586 } else {
1587 log.warn("Full reroute attempted {} ms ago .. skipping", lfrr);
1588 }
Saurav Dasec683dc2018-04-27 18:42:30 -07001589
1590 } else if (edgePortEvent && clusterEvent) {
1591 log.warn("Mastership changed for dev: {}/{} due to clusterEvent {} ms ago "
1592 + "while edge-port event happened {} ms ago "
1593 + " .. reprogramming all edge-ports",
1594 devId, me.roleInfo(), lce, lepe);
1595 if (shouldProgram(devId)) {
1596 srManager.deviceService.getPorts(devId).stream()
1597 .filter(p -> srManager.interfaceService
1598 .isConfigured(new ConnectPoint(devId, p.number())))
1599 .forEach(p -> srManager.processPortUpdated(devId, p));
1600 }
1601
Saurav Das00e553b2018-04-21 17:19:48 -07001602 } else {
1603 log.debug("Stable route-paths .. full reroute not attempted for "
1604 + "mastership change {}/{} deviceEvent/timeSince: {}/{} "
1605 + "clusterEvent/timeSince: {}/{}", devId, me.roleInfo(),
1606 deviceEvent, lde, clusterEvent, lce);
1607 }
1608 }
1609 }
1610
Saurav Das68e1b6a2018-06-11 17:02:31 -07001611 /**
1612 * Performs a full reroute of routing rules in all the switches. Assumes
1613 * caller has purged hash groups from the nextObjective store, otherwise
1614 * re-uses ones available in the store.
1615 */
1616 protected final class FullRerouteAfterPurge implements Runnable {
1617 @Override
1618 public void run() {
1619 populateAllRoutingRules();
1620 }
1621 }
1622
1623
Saurav Das261c3002017-06-13 15:35:54 -07001624 //////////////////////////////////////
1625 // Routing helper methods and classes
1626 //////////////////////////////////////
1627
1628 /**
Saurav Das68e1b6a2018-06-11 17:02:31 -07001629 * Computes set of affected routes due to failed link. Assumes previous ecmp
1630 * shortest-path graph exists for a switch in order to compute affected
1631 * routes. If such a graph does not exist, the method returns null.
Saurav Dasb149be12016-06-07 10:08:06 -07001632 *
1633 * @param linkFail the failed link
1634 * @return the set of affected routes which may be empty if no routes were
Saurav Das68e1b6a2018-06-11 17:02:31 -07001635 * affected
Saurav Dasb149be12016-06-07 10:08:06 -07001636 */
sanghofb7c7292015-04-13 15:15:58 -07001637 private Set<ArrayList<DeviceId>> computeDamagedRoutes(Link linkFail) {
sanghofb7c7292015-04-13 15:15:58 -07001638 Set<ArrayList<DeviceId>> routes = new HashSet<>();
1639
1640 for (Device sw : srManager.deviceService.getDevices()) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001641 log.debug("Computing the impacted routes for device {} due to link fail",
1642 sw.id());
Charles Chand66d6712018-03-29 16:03:41 -07001643 if (!shouldProgram(sw.id())) {
Saurav Das00e553b2018-04-21 17:19:48 -07001644 lastProgrammed.remove(sw.id());
sanghofb7c7292015-04-13 15:15:58 -07001645 continue;
1646 }
Charles Chand66d6712018-03-29 16:03:41 -07001647 for (DeviceId rootSw : deviceAndItsPair(sw.id())) {
Saurav Das00e553b2018-04-21 17:19:48 -07001648 // check for mastership change since last run
1649 if (!lastProgrammed.contains(sw.id())) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001650 log.warn("New responsibility for this node to program dev:{}"
Saurav Das00e553b2018-04-21 17:19:48 -07001651 + " ... nuking current ECMPspg", sw.id());
1652 currentEcmpSpgMap.remove(sw.id());
1653 }
Saurav Das68e1b6a2018-06-11 17:02:31 -07001654 lastProgrammed.add(sw.id());
1655
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001656 EcmpShortestPathGraph ecmpSpg = currentEcmpSpgMap.get(rootSw);
1657 if (ecmpSpg == null) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001658 log.warn("No existing ECMP graph for switch {}. Assuming "
1659 + "all route-paths have changed towards it.", rootSw);
1660 for (DeviceId targetSw : srManager.deviceConfiguration.getRouters()) {
1661 if (targetSw.equals(rootSw)) {
1662 continue;
1663 }
1664 routes.add(Lists.newArrayList(targetSw, rootSw));
1665 log.debug("Impacted route:{}->{}", targetSw, rootSw);
1666 }
1667 continue;
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001668 }
Saurav Das68e1b6a2018-06-11 17:02:31 -07001669
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001670 if (log.isDebugEnabled()) {
1671 log.debug("Root switch: {}", rootSw);
1672 log.debug(" Current/Existing SPG: {}", ecmpSpg);
1673 log.debug(" New/Updated SPG: {}", updatedEcmpSpgMap.get(rootSw));
1674 }
1675 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>>
1676 switchVia = ecmpSpg.getAllLearnedSwitchesAndVia();
1677 // figure out if the broken link affected any route-paths in this graph
1678 for (Integer itrIdx : switchVia.keySet()) {
1679 log.trace("Current/Exiting SPG Iterindex# {}", itrIdx);
1680 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1681 switchVia.get(itrIdx);
1682 for (DeviceId targetSw : swViaMap.keySet()) {
1683 log.trace("TargetSwitch {} --> RootSwitch {}",
1684 targetSw, rootSw);
Saurav Dasb149be12016-06-07 10:08:06 -07001685 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1686 log.trace(" Via:");
Pier Ventreadb4ae62016-11-23 09:57:42 -08001687 via.forEach(e -> log.trace(" {}", e));
Saurav Dasb149be12016-06-07 10:08:06 -07001688 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001689 Set<ArrayList<DeviceId>> subLinks =
1690 computeLinks(targetSw, rootSw, swViaMap);
1691 for (ArrayList<DeviceId> alink: subLinks) {
1692 if ((alink.get(0).equals(linkFail.src().deviceId()) &&
1693 alink.get(1).equals(linkFail.dst().deviceId()))
1694 ||
1695 (alink.get(0).equals(linkFail.dst().deviceId()) &&
1696 alink.get(1).equals(linkFail.src().deviceId()))) {
1697 log.debug("Impacted route:{}->{}", targetSw, rootSw);
1698 ArrayList<DeviceId> aRoute = new ArrayList<>();
1699 aRoute.add(targetSw); // switch with rules to populate
1700 aRoute.add(rootSw); // towards this destination
1701 routes.add(aRoute);
1702 break;
1703 }
sanghofb7c7292015-04-13 15:15:58 -07001704 }
1705 }
1706 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001707
sanghofb7c7292015-04-13 15:15:58 -07001708 }
sangho28d0b6d2015-05-07 13:30:57 -07001709
sanghofb7c7292015-04-13 15:15:58 -07001710 }
sanghofb7c7292015-04-13 15:15:58 -07001711 return routes;
1712 }
1713
Saurav Das1b391d52016-11-29 14:27:25 -08001714 /**
1715 * Computes set of affected routes due to new links or failed switches.
1716 *
Saurav Dasdc7f2752018-03-18 21:28:15 -07001717 * @param failedSwitch deviceId of failed switch if any
Saurav Das1b391d52016-11-29 14:27:25 -08001718 * @return the set of affected routes which may be empty if no routes were
1719 * affected
1720 */
Saurav Dascea556f2018-03-05 14:37:16 -08001721 private Set<ArrayList<DeviceId>> computeRouteChange(DeviceId failedSwitch) {
Saurav Das261c3002017-06-13 15:35:54 -07001722 ImmutableSet.Builder<ArrayList<DeviceId>> changedRtBldr =
Saurav Das1b391d52016-11-29 14:27:25 -08001723 ImmutableSet.builder();
sanghofb7c7292015-04-13 15:15:58 -07001724
1725 for (Device sw : srManager.deviceService.getDevices()) {
Saurav Das261c3002017-06-13 15:35:54 -07001726 log.debug("Computing the impacted routes for device {}", sw.id());
Charles Chand66d6712018-03-29 16:03:41 -07001727 if (!shouldProgram(sw.id())) {
Saurav Das00e553b2018-04-21 17:19:48 -07001728 lastProgrammed.remove(sw.id());
sanghofb7c7292015-04-13 15:15:58 -07001729 continue;
1730 }
Charles Chand66d6712018-03-29 16:03:41 -07001731 for (DeviceId rootSw : deviceAndItsPair(sw.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001732 if (log.isTraceEnabled()) {
1733 log.trace("Device links for dev: {}", rootSw);
1734 for (Link link: srManager.linkService.getDeviceLinks(rootSw)) {
1735 log.trace("{} -> {} ", link.src().deviceId(),
1736 link.dst().deviceId());
1737 }
Saurav Dasb149be12016-06-07 10:08:06 -07001738 }
Saurav Das00e553b2018-04-21 17:19:48 -07001739 // check for mastership change since last run
1740 if (!lastProgrammed.contains(sw.id())) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001741 log.warn("New responsibility for this node to program dev:{}"
Saurav Das00e553b2018-04-21 17:19:48 -07001742 + " ... nuking current ECMPspg", sw.id());
1743 currentEcmpSpgMap.remove(sw.id());
1744 }
Saurav Das68e1b6a2018-06-11 17:02:31 -07001745 lastProgrammed.add(sw.id());
Saurav Das261c3002017-06-13 15:35:54 -07001746 EcmpShortestPathGraph currEcmpSpg = currentEcmpSpgMap.get(rootSw);
1747 if (currEcmpSpg == null) {
1748 log.debug("No existing ECMP graph for device {}.. adding self as "
1749 + "changed route", rootSw);
1750 changedRtBldr.add(Lists.newArrayList(rootSw));
1751 continue;
1752 }
1753 EcmpShortestPathGraph newEcmpSpg = updatedEcmpSpgMap.get(rootSw);
Saurav Dasdebcf882018-04-06 20:16:01 -07001754 if (newEcmpSpg == null) {
1755 log.warn("Cannot find updated ECMP graph for dev:{}", rootSw);
1756 continue;
1757 }
Saurav Das261c3002017-06-13 15:35:54 -07001758 if (log.isDebugEnabled()) {
1759 log.debug("Root switch: {}", rootSw);
1760 log.debug(" Current/Existing SPG: {}", currEcmpSpg);
1761 log.debug(" New/Updated SPG: {}", newEcmpSpg);
1762 }
1763 // first use the updated/new map to compare to current/existing map
1764 // as new links may have come up
1765 changedRtBldr.addAll(compareGraphs(newEcmpSpg, currEcmpSpg, rootSw));
1766 // then use the current/existing map to compare to updated/new map
1767 // as switch may have been removed
1768 changedRtBldr.addAll(compareGraphs(currEcmpSpg, newEcmpSpg, rootSw));
sangho28d0b6d2015-05-07 13:30:57 -07001769 }
Saurav Das1b391d52016-11-29 14:27:25 -08001770 }
sanghofb7c7292015-04-13 15:15:58 -07001771
Saurav Dascea556f2018-03-05 14:37:16 -08001772 // handle clearing state for a failed switch in case the switch does
1773 // not have a pair, or the pair is not available
1774 if (failedSwitch != null) {
Charles Chan6dbcd252018-04-02 11:46:38 -07001775 Optional<DeviceId> pairDev = srManager.getPairDeviceId(failedSwitch);
1776 if (!pairDev.isPresent() || !srManager.deviceService.isAvailable(pairDev.get())) {
Saurav Dascea556f2018-03-05 14:37:16 -08001777 log.debug("Proxy Route changes to downed Sw:{}", failedSwitch);
1778 srManager.deviceService.getDevices().forEach(dev -> {
1779 if (!dev.id().equals(failedSwitch) &&
1780 srManager.mastershipService.isLocalMaster(dev.id())) {
1781 log.debug(" : {}", dev.id());
1782 changedRtBldr.add(Lists.newArrayList(dev.id(), failedSwitch));
1783 }
1784 });
1785 }
1786 }
1787
Saurav Das261c3002017-06-13 15:35:54 -07001788 Set<ArrayList<DeviceId>> changedRoutes = changedRtBldr.build();
Saurav Das1b391d52016-11-29 14:27:25 -08001789 for (ArrayList<DeviceId> route: changedRoutes) {
1790 log.debug("Route changes Target -> Root");
1791 if (route.size() == 1) {
1792 log.debug(" : all -> {}", route.get(0));
1793 } else {
1794 log.debug(" : {} -> {}", route.get(0), route.get(1));
1795 }
1796 }
1797 return changedRoutes;
1798 }
1799
pier572d4a92019-04-25 18:51:51 +02001800 // Utility method to expands the route changes in two elements array using
1801 // the ECMP graph. Caller represents all to dst switch routes with an
1802 // array containing only the dst switch.
1803 private Set<ArrayList<DeviceId>> getExpandedRoutes(Set<ArrayList<DeviceId>> routeChanges) {
1804 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
1805 // Ensure each routeChanges entry has two elements
1806 for (ArrayList<DeviceId> route : routeChanges) {
1807 if (route.size() == 1) {
1808 DeviceId dstSw = route.get(0);
1809 EcmpShortestPathGraph ec = updatedEcmpSpgMap.get(dstSw);
1810 if (ec == null) {
1811 log.warn("No graph found for {} .. aborting redoRouting", dstSw);
1812 return Collections.emptySet();
1813 }
1814 ec.getAllLearnedSwitchesAndVia().keySet().forEach(key -> {
1815 ec.getAllLearnedSwitchesAndVia().get(key).keySet().forEach(target -> {
1816 changedRoutes.add(Lists.newArrayList(target, dstSw));
1817 });
1818 });
1819 } else {
1820 DeviceId targetSw = route.get(0);
1821 DeviceId dstSw = route.get(1);
1822 changedRoutes.add(Lists.newArrayList(targetSw, dstSw));
1823 }
1824 }
1825 return changedRoutes;
1826 }
1827
1828 // Utility method to expands the route changes in two elements array using
1829 // the available devices. Caller represents all to dst switch routes with an
1830 // array containing only the dst switch.
1831 private Set<ArrayList<DeviceId>> getAllExpandedRoutes(Set<ArrayList<DeviceId>> routeChanges) {
1832 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
1833 // Ensure each routeChanges entry has two elements
1834 for (ArrayList<DeviceId> route : routeChanges) {
1835 if (route.size() == 1) {
1836 // route-path changes are from everyone else to this switch
1837 DeviceId dstSw = route.get(0);
1838 srManager.deviceService.getAvailableDevices().forEach(sw -> {
1839 if (!sw.id().equals(dstSw)) {
1840 changedRoutes.add(Lists.newArrayList(sw.id(), dstSw));
1841 }
1842 });
1843 } else {
1844 changedRoutes.add(route);
1845 }
1846 }
1847 return changedRoutes;
1848 }
1849
Saurav Das1b391d52016-11-29 14:27:25 -08001850 /**
1851 * For the root switch, searches all the target nodes reachable in the base
1852 * graph, and compares paths to the ones in the comp graph.
1853 *
1854 * @param base the graph that is indexed for all reachable target nodes
1855 * from the root node
1856 * @param comp the graph that the base graph is compared to
1857 * @param rootSw both ecmp graphs are calculated for the root node
1858 * @return all the routes that have changed in the base graph
1859 */
1860 private Set<ArrayList<DeviceId>> compareGraphs(EcmpShortestPathGraph base,
1861 EcmpShortestPathGraph comp,
1862 DeviceId rootSw) {
1863 ImmutableSet.Builder<ArrayList<DeviceId>> changedRoutesBuilder =
1864 ImmutableSet.builder();
1865 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> baseMap =
1866 base.getAllLearnedSwitchesAndVia();
1867 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> compMap =
1868 comp.getAllLearnedSwitchesAndVia();
1869 for (Integer itrIdx : baseMap.keySet()) {
1870 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> baseViaMap =
1871 baseMap.get(itrIdx);
1872 for (DeviceId targetSw : baseViaMap.keySet()) {
1873 ArrayList<ArrayList<DeviceId>> basePath = baseViaMap.get(targetSw);
1874 ArrayList<ArrayList<DeviceId>> compPath = getVia(compMap, targetSw);
1875 if ((compPath == null) || !basePath.equals(compPath)) {
Saurav Das62ae6792017-05-15 15:34:25 -07001876 log.trace("Impacted route:{} -> {}", targetSw, rootSw);
Saurav Das1b391d52016-11-29 14:27:25 -08001877 ArrayList<DeviceId> route = new ArrayList<>();
Saurav Das261c3002017-06-13 15:35:54 -07001878 route.add(targetSw); // switch with rules to populate
1879 route.add(rootSw); // towards this destination
Saurav Das1b391d52016-11-29 14:27:25 -08001880 changedRoutesBuilder.add(route);
sanghofb7c7292015-04-13 15:15:58 -07001881 }
1882 }
sangho28d0b6d2015-05-07 13:30:57 -07001883 }
Saurav Das1b391d52016-11-29 14:27:25 -08001884 return changedRoutesBuilder.build();
sanghofb7c7292015-04-13 15:15:58 -07001885 }
1886
Saurav Das261c3002017-06-13 15:35:54 -07001887 /**
1888 * Returns the ECMP paths traversed to reach the target switch.
1889 *
1890 * @param switchVia a per-iteration view of the ECMP graph for a root switch
1891 * @param targetSw the switch to reach from the root switch
1892 * @return the nodes traversed on ECMP paths to the target switch
1893 */
sanghofb7c7292015-04-13 15:15:58 -07001894 private ArrayList<ArrayList<DeviceId>> getVia(HashMap<Integer, HashMap<DeviceId,
Saurav Das1b391d52016-11-29 14:27:25 -08001895 ArrayList<ArrayList<DeviceId>>>> switchVia, DeviceId targetSw) {
sanghofb7c7292015-04-13 15:15:58 -07001896 for (Integer itrIdx : switchVia.keySet()) {
1897 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1898 switchVia.get(itrIdx);
Saurav Das1b391d52016-11-29 14:27:25 -08001899 if (swViaMap.get(targetSw) == null) {
sanghofb7c7292015-04-13 15:15:58 -07001900 continue;
1901 } else {
Saurav Das1b391d52016-11-29 14:27:25 -08001902 return swViaMap.get(targetSw);
sanghofb7c7292015-04-13 15:15:58 -07001903 }
1904 }
1905
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001906 return null;
sanghofb7c7292015-04-13 15:15:58 -07001907 }
1908
Saurav Das261c3002017-06-13 15:35:54 -07001909 /**
1910 * Utility method to break down a path from src to dst device into a collection
1911 * of links.
1912 *
1913 * @param src src device of the path
1914 * @param dst dst device of the path
1915 * @param viaMap path taken from src to dst device
1916 * @return collection of links in the path
1917 */
sanghofb7c7292015-04-13 15:15:58 -07001918 private Set<ArrayList<DeviceId>> computeLinks(DeviceId src,
1919 DeviceId dst,
1920 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> viaMap) {
1921 Set<ArrayList<DeviceId>> subLinks = Sets.newHashSet();
1922 for (ArrayList<DeviceId> via : viaMap.get(src)) {
1923 DeviceId linkSrc = src;
1924 DeviceId linkDst = dst;
1925 for (DeviceId viaDevice: via) {
1926 ArrayList<DeviceId> link = new ArrayList<>();
1927 linkDst = viaDevice;
1928 link.add(linkSrc);
1929 link.add(linkDst);
1930 subLinks.add(link);
1931 linkSrc = viaDevice;
1932 }
1933 ArrayList<DeviceId> link = new ArrayList<>();
1934 link.add(linkSrc);
1935 link.add(dst);
1936 subLinks.add(link);
1937 }
1938
1939 return subLinks;
1940 }
1941
Charles Chanc22cef32016-04-29 14:38:22 -07001942 /**
Charles Chand66d6712018-03-29 16:03:41 -07001943 * Determines whether this controller instance should program the
Saurav Das261c3002017-06-13 15:35:54 -07001944 * given {@code deviceId}, based on mastership and pairDeviceId if one exists.
Charles Chand66d6712018-03-29 16:03:41 -07001945 * <p>
1946 * Once an instance is elected, it will be the only instance responsible for programming
1947 * both devices in the pair until it goes down.
Charles Chanc22cef32016-04-29 14:38:22 -07001948 *
Saurav Das261c3002017-06-13 15:35:54 -07001949 * @param deviceId device identifier to consider for routing
Charles Chand66d6712018-03-29 16:03:41 -07001950 * @return true if current instance should handle the routing for given device
Charles Chanc22cef32016-04-29 14:38:22 -07001951 */
Charles Chand66d6712018-03-29 16:03:41 -07001952 boolean shouldProgram(DeviceId deviceId) {
Charles Chanfbcb8812018-04-18 18:41:05 -07001953 Boolean cached = shouldProgramCache.get(deviceId);
1954 if (cached != null) {
Saurav Das00e553b2018-04-21 17:19:48 -07001955 log.debug("shouldProgram dev:{} cached:{}", deviceId, cached);
Charles Chanfbcb8812018-04-18 18:41:05 -07001956 return cached;
1957 }
1958
Charles Chand66d6712018-03-29 16:03:41 -07001959 Optional<DeviceId> pairDeviceId = srManager.getPairDeviceId(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001960
Charles Chand66d6712018-03-29 16:03:41 -07001961 NodeId currentNodeId = srManager.clusterService.getLocalNode().id();
1962 NodeId masterNodeId = srManager.mastershipService.getMasterFor(deviceId);
1963 Optional<NodeId> pairMasterNodeId = pairDeviceId.map(srManager.mastershipService::getMasterFor);
Saurav Das68e1b6a2018-06-11 17:02:31 -07001964 log.debug("Evaluate shouldProgram {}/pair={}. currentNodeId={}, master={}, pairMaster={}",
Charles Chand66d6712018-03-29 16:03:41 -07001965 deviceId, pairDeviceId, currentNodeId, masterNodeId, pairMasterNodeId);
1966
1967 // No pair device configured. Only handle when current instance is the master of the device
1968 if (!pairDeviceId.isPresent()) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001969 log.debug("No pair device. currentNodeId={}, master={}", currentNodeId, masterNodeId);
Charles Chand66d6712018-03-29 16:03:41 -07001970 return currentNodeId.equals(masterNodeId);
sangho80f11cb2015-04-01 13:05:26 -07001971 }
Charles Chand66d6712018-03-29 16:03:41 -07001972
1973 // Should not handle if current instance is not the master of either switch
1974 if (!currentNodeId.equals(masterNodeId) &&
1975 !(pairMasterNodeId.isPresent() && currentNodeId.equals(pairMasterNodeId.get()))) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001976 log.debug("Current nodeId {} is neither the master of target device {} nor pair device {}",
Charles Chand66d6712018-03-29 16:03:41 -07001977 currentNodeId, deviceId, pairDeviceId);
1978 return false;
1979 }
1980
1981 Set<DeviceId> key = Sets.newHashSet(deviceId, pairDeviceId.get());
1982
1983 NodeId king = shouldProgram.compute(key, ((k, v) -> {
1984 if (v == null) {
1985 // There is no value in the map. Elect a node
1986 return elect(Lists.newArrayList(masterNodeId, pairMasterNodeId.orElse(null)));
1987 } else {
1988 if (v.equals(masterNodeId) || v.equals(pairMasterNodeId.orElse(null))) {
1989 // Use the node in the map if it is still alive and is a master of any of the two switches
1990 return v;
1991 } else {
1992 // Previously elected node is no longer the master of either switch. Re-elect a node.
1993 return elect(Lists.newArrayList(masterNodeId, pairMasterNodeId.orElse(null)));
1994 }
1995 }
1996 }));
1997
1998 if (king != null) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001999 log.debug("{} is king, should handle routing for {}/pair={}", king, deviceId, pairDeviceId);
Charles Chanfbcb8812018-04-18 18:41:05 -07002000 shouldProgramCache.put(deviceId, king.equals(currentNodeId));
Charles Chand66d6712018-03-29 16:03:41 -07002001 return king.equals(currentNodeId);
2002 } else {
2003 log.error("Fail to elect a king for {}/pair={}. Abort.", deviceId, pairDeviceId);
Charles Chanfbcb8812018-04-18 18:41:05 -07002004 shouldProgramCache.remove(deviceId);
Charles Chand66d6712018-03-29 16:03:41 -07002005 return false;
2006 }
2007 }
2008
2009 /**
2010 * Elects a node who should take responsibility of programming devices.
2011 * @param nodeIds list of candidate node ID
2012 *
2013 * @return NodeId of the node that gets elected, or null if none of the node can be elected
2014 */
2015 private NodeId elect(List<NodeId> nodeIds) {
2016 // Remove all null elements. This could happen when some device has no master
2017 nodeIds.removeAll(Collections.singleton(null));
2018 nodeIds.sort(null);
2019 return nodeIds.size() == 0 ? null : nodeIds.get(0);
2020 }
2021
Charles Chanfbcb8812018-04-18 18:41:05 -07002022 void invalidateShouldProgramCache(DeviceId deviceId) {
2023 shouldProgramCache.remove(deviceId);
2024 }
2025
Charles Chand66d6712018-03-29 16:03:41 -07002026 /**
2027 * Returns a set of device ID, containing given device and its pair device if exist.
2028 *
2029 * @param deviceId Device ID
2030 * @return a set of device ID, containing given device and its pair device if exist.
2031 */
2032 private Set<DeviceId> deviceAndItsPair(DeviceId deviceId) {
2033 Set<DeviceId> ret = Sets.newHashSet(deviceId);
2034 srManager.getPairDeviceId(deviceId).ifPresent(ret::add);
2035 return ret;
sangho80f11cb2015-04-01 13:05:26 -07002036 }
2037
Charles Chanc22cef32016-04-29 14:38:22 -07002038 /**
Saurav Das261c3002017-06-13 15:35:54 -07002039 * Returns the set of deviceIds which are the next hops from the targetSw
2040 * to the dstSw according to the latest ECMP spg.
2041 *
2042 * @param targetSw the switch for which the next-hops are desired
2043 * @param dstSw the switch to which the next-hops lead to from the targetSw
2044 * @return set of next hop deviceIds, could be empty if no next hops are found
2045 */
2046 private Set<DeviceId> getNextHops(DeviceId targetSw, DeviceId dstSw) {
2047 boolean targetIsEdge = false;
2048 try {
2049 targetIsEdge = srManager.deviceConfiguration.isEdgeDevice(targetSw);
2050 } catch (DeviceConfigNotFoundException e) {
2051 log.warn(e.getMessage() + "Cannot determine if targetIsEdge {}.. "
2052 + "continuing to getNextHops", targetSw);
2053 }
2054
2055 EcmpShortestPathGraph ecmpSpg = updatedEcmpSpgMap.get(dstSw);
2056 if (ecmpSpg == null) {
2057 log.debug("No ecmpSpg found for dstSw: {}", dstSw);
2058 return ImmutableSet.of();
2059 }
2060 HashMap<Integer,
2061 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> switchVia =
2062 ecmpSpg.getAllLearnedSwitchesAndVia();
2063 for (Integer itrIdx : switchVia.keySet()) {
2064 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
2065 switchVia.get(itrIdx);
2066 for (DeviceId target : swViaMap.keySet()) {
2067 if (!target.equals(targetSw)) {
2068 continue;
2069 }
Saurav Das49368392018-04-23 18:42:12 -07002070 // optimization for spines to not use leaves to get
2071 // to a spine or other leaves. Also leaves should not use other
2072 // leaves to get to the destination
2073 if ((!targetIsEdge && itrIdx > 1) || targetIsEdge) {
Saurav Das97241862018-02-14 14:14:54 -08002074 boolean pathdevIsEdge = false;
2075 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
Saurav Das49368392018-04-23 18:42:12 -07002076 log.debug("Evaluating next-hop in path: {}", via);
Saurav Das97241862018-02-14 14:14:54 -08002077 for (DeviceId pathdev : via) {
2078 try {
2079 pathdevIsEdge = srManager.deviceConfiguration
2080 .isEdgeDevice(pathdev);
2081 } catch (DeviceConfigNotFoundException e) {
2082 log.warn(e.getMessage());
2083 }
2084 if (pathdevIsEdge) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07002085 log.debug("Avoiding {} hop path for targetSw:{}"
Saurav Das97241862018-02-14 14:14:54 -08002086 + " --> dstSw:{} which goes through an edge"
2087 + " device {} in path {}", itrIdx,
2088 targetSw, dstSw, pathdev, via);
2089 return ImmutableSet.of();
2090 }
2091 }
2092 }
Saurav Das261c3002017-06-13 15:35:54 -07002093 }
2094 Set<DeviceId> nextHops = new HashSet<>();
2095 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
2096 if (via.isEmpty()) {
2097 // the dstSw is the next-hop from the targetSw
2098 nextHops.add(dstSw);
2099 } else {
2100 // first elem is next-hop in each ECMP path
2101 nextHops.add(via.get(0));
2102 }
2103 }
Saurav Das49368392018-04-23 18:42:12 -07002104 log.debug("target {} --> dst: {} has next-hops:{}", targetSw,
2105 dstSw, nextHops);
Saurav Das261c3002017-06-13 15:35:54 -07002106 return nextHops;
2107 }
2108 }
Saurav Das49368392018-04-23 18:42:12 -07002109 log.debug("No next hops found for target:{} --> dst: {}", targetSw, dstSw);
Saurav Das261c3002017-06-13 15:35:54 -07002110 return ImmutableSet.of(); //no next-hops found
2111 }
2112
Saurav Das261c3002017-06-13 15:35:54 -07002113 //////////////////////////////////////
2114 // Filtering rule creation
2115 //////////////////////////////////////
2116
2117 /**
Saurav Dasf9332192017-02-18 14:05:44 -08002118 * Populates filtering rules for port, and punting rules
2119 * for gateway IPs, loopback IPs and arp/ndp traffic.
2120 * Should only be called by the master instance for this device/port.
sangho80f11cb2015-04-01 13:05:26 -07002121 *
2122 * @param deviceId Switch ID to set the rules
2123 */
Charles Chanfbcb8812018-04-18 18:41:05 -07002124 void populatePortAddressingRules(DeviceId deviceId) {
Saurav Das07c74602016-04-27 18:35:50 -07002125 // Although device is added, sometimes device store does not have the
2126 // ports for this device yet. It results in missing filtering rules in the
2127 // switch. We will attempt it a few times. If it still does not work,
2128 // user can manually repopulate using CLI command sr-reroute-network
Charles Chan18fa4252017-02-08 16:10:40 -08002129 PortFilterInfo firstRun = rulePopulator.populateVlanMacFilters(deviceId);
Saurav Dasd1872b02016-12-02 15:43:47 -08002130 if (firstRun == null) {
2131 firstRun = new PortFilterInfo(0, 0, 0);
Saurav Das07c74602016-04-27 18:35:50 -07002132 }
Saurav Dasd1872b02016-12-02 15:43:47 -08002133 executorService.schedule(new RetryFilters(deviceId, firstRun),
2134 RETRY_INTERVAL_MS, TimeUnit.MILLISECONDS);
sangho80f11cb2015-04-01 13:05:26 -07002135 }
2136
2137 /**
Saurav Dasd1872b02016-12-02 15:43:47 -08002138 * RetryFilters populates filtering objectives for a device and keeps retrying
2139 * till the number of ports filtered are constant for a predefined number
2140 * of attempts.
2141 */
2142 protected final class RetryFilters implements Runnable {
2143 int constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS;
2144 DeviceId devId;
2145 int counter;
2146 PortFilterInfo prevRun;
2147
2148 private RetryFilters(DeviceId deviceId, PortFilterInfo previousRun) {
Saurav Das07c74602016-04-27 18:35:50 -07002149 devId = deviceId;
Saurav Dasd1872b02016-12-02 15:43:47 -08002150 prevRun = previousRun;
2151 counter = 0;
Saurav Das07c74602016-04-27 18:35:50 -07002152 }
2153
2154 @Override
2155 public void run() {
Charles Chan077314e2017-06-22 14:27:17 -07002156 log.debug("RETRY FILTER ATTEMPT {} ** dev:{}", ++counter, devId);
Charles Chan18fa4252017-02-08 16:10:40 -08002157 PortFilterInfo thisRun = rulePopulator.populateVlanMacFilters(devId);
Saurav Dasd1872b02016-12-02 15:43:47 -08002158 boolean sameResult = prevRun.equals(thisRun);
2159 log.debug("dev:{} prevRun:{} thisRun:{} sameResult:{}", devId, prevRun,
2160 thisRun, sameResult);
Ray Milkey614352e2018-02-26 09:36:31 -08002161 if (thisRun == null || !sameResult || (--constantAttempts > 0)) {
Saurav Dasf9332192017-02-18 14:05:44 -08002162 // exponentially increasing intervals for retries
2163 executorService.schedule(this,
2164 RETRY_INTERVAL_MS * (int) Math.pow(counter, RETRY_INTERVAL_SCALE),
2165 TimeUnit.MILLISECONDS);
Saurav Dasd1872b02016-12-02 15:43:47 -08002166 if (!sameResult) {
2167 constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS; //reset
2168 }
Saurav Das07c74602016-04-27 18:35:50 -07002169 }
Saurav Dasd1872b02016-12-02 15:43:47 -08002170 prevRun = (thisRun == null) ? prevRun : thisRun;
Saurav Das07c74602016-04-27 18:35:50 -07002171 }
Saurav Das07c74602016-04-27 18:35:50 -07002172 }
piera9941192019-04-24 16:12:47 +02002173
2174 // Check jobs completion. It returns false if one of the job fails
2175 // and cancel the remaining
2176 private boolean checkJobs(List<Future<Boolean>> futures) {
2177 boolean completed = true;
2178 for (Future<Boolean> future : futures) {
2179 try {
2180 if (completed) {
2181 if (!future.get()) {
2182 completed = false;
2183 }
2184 } else {
2185 future.cancel(true);
2186 }
2187 } catch (InterruptedException | ExecutionException e) {
2188 completed = false;
2189 }
2190 }
2191 return completed;
2192 }
sangho80f11cb2015-04-01 13:05:26 -07002193}