blob: c058a0c6e8fa41902394953056f357309772ca9a [file] [log] [blame]
sanghob35a6192015-04-01 13:05:26 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sanghob35a6192015-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 Dasc88d4662017-05-15 15:34:25 -070018import com.google.common.collect.ImmutableMap;
19import com.google.common.collect.ImmutableMap.Builder;
Charles Chan93e71ba2016-04-29 14:38:22 -070020import com.google.common.collect.ImmutableSet;
Saurav Das4e3224f2016-11-29 14:27:25 -080021import com.google.common.collect.Lists;
sangho20eff1d2015-04-13 15:15:58 -070022import com.google.common.collect.Maps;
23import com.google.common.collect.Sets;
Saurav Dasceccf242017-08-03 18:30:35 -070024
Jonghwan Hyuna76bf032018-04-09 09:40:50 -070025import org.onlab.packet.EthType;
Charles Chan022d6672019-04-17 14:20:26 -070026import com.google.common.collect.Streams;
sangho666cd6d2015-04-14 16:27:13 -070027import org.onlab.packet.Ip4Address;
Pier Ventree0ae7a32016-11-23 09:57:42 -080028import org.onlab.packet.Ip6Address;
sanghob35a6192015-04-01 13:05:26 -070029import org.onlab.packet.IpPrefix;
Charles Chan2fde6d42017-08-23 14:46:43 -070030import org.onlab.packet.MacAddress;
31import org.onlab.packet.VlanId;
pier8b4ba992019-04-24 16:12:47 +020032import org.onlab.util.PredictableExecutor;
33import org.onlab.util.PredictableExecutor.PickyCallable;
Saurav Das7bcbe702017-06-13 15:35:54 -070034import org.onosproject.cluster.NodeId;
Saurav Dasc6dc1772018-04-21 17:19:48 -070035import org.onosproject.mastership.MastershipEvent;
Charles Chan93e71ba2016-04-29 14:38:22 -070036import org.onosproject.net.ConnectPoint;
sanghob35a6192015-04-01 13:05:26 -070037import org.onosproject.net.Device;
38import org.onosproject.net.DeviceId;
sangho20eff1d2015-04-13 15:15:58 -070039import org.onosproject.net.Link;
Charles Chan2fde6d42017-08-23 14:46:43 -070040import org.onosproject.net.PortNumber;
Charles Chan0b4e6182015-11-03 10:42:14 -080041import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
42import org.onosproject.segmentrouting.config.DeviceConfiguration;
Saurav Dasc88d4662017-05-15 15:34:25 -070043import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Jonghwan Hyuna76bf032018-04-09 09:40:50 -070044import org.onosproject.segmentrouting.storekey.DummyVlanIdStoreKey;
Charles Chan2ff1bac2018-03-29 16:03:41 -070045import org.onosproject.store.serializers.KryoNamespaces;
46import org.onosproject.store.service.Serializer;
sanghob35a6192015-04-01 13:05:26 -070047import org.slf4j.Logger;
48import org.slf4j.LoggerFactory;
49
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -070050import java.time.Instant;
sanghob35a6192015-04-01 13:05:26 -070051import java.util.ArrayList;
Charles Chan2ff1bac2018-03-29 16:03:41 -070052import java.util.Collections;
sanghob35a6192015-04-01 13:05:26 -070053import java.util.HashMap;
54import java.util.HashSet;
Saurav Das7bcbe702017-06-13 15:35:54 -070055import java.util.Iterator;
Charles Chan2ff1bac2018-03-29 16:03:41 -070056import java.util.List;
Saurav Das7bcbe702017-06-13 15:35:54 -070057import java.util.Map;
Saurav Dasd2fded02016-12-02 15:43:47 -080058import java.util.Objects;
Charles Chanba6c5752018-04-02 11:46:38 -070059import java.util.Optional;
sanghob35a6192015-04-01 13:05:26 -070060import java.util.Set;
pier8b4ba992019-04-24 16:12:47 +020061import java.util.concurrent.CompletableFuture;
62import java.util.concurrent.ExecutionException;
63import java.util.concurrent.ExecutorService;
64import java.util.concurrent.Future;
Saurav Das59232cf2016-04-27 18:35:50 -070065import java.util.concurrent.ScheduledExecutorService;
66import java.util.concurrent.TimeUnit;
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +090067import java.util.concurrent.locks.Lock;
68import java.util.concurrent.locks.ReentrantLock;
Charles Chan022d6672019-04-17 14:20:26 -070069import java.util.stream.Collectors;
Saurav Das604ab3a2018-03-18 21:28:15 -070070import java.util.stream.Stream;
71
Pier Ventree0ae7a32016-11-23 09:57:42 -080072import static com.google.common.base.Preconditions.checkNotNull;
73import static java.util.concurrent.Executors.newScheduledThreadPool;
74import static org.onlab.util.Tools.groupedThreads;
sanghob35a6192015-04-01 13:05:26 -070075
Charles Chane849c192016-01-11 18:28:54 -080076/**
77 * Default routing handler that is responsible for route computing and
78 * routing rule population.
79 */
sanghob35a6192015-04-01 13:05:26 -070080public class DefaultRoutingHandler {
Saurav Das018605f2017-02-18 14:05:44 -080081 private static final int MAX_CONSTANT_RETRY_ATTEMPTS = 5;
Ray Milkey3717e602018-02-01 13:49:47 -080082 private static final long RETRY_INTERVAL_MS = 250L;
Saurav Das018605f2017-02-18 14:05:44 -080083 private static final int RETRY_INTERVAL_SCALE = 1;
Saurav Dasceccf242017-08-03 18:30:35 -070084 private static final long STABLITY_THRESHOLD = 10; //secs
Saurav Dasc6dc1772018-04-21 17:19:48 -070085 private static final long MASTER_CHANGE_DELAY = 1000; // ms
Saurav Dasf1027d42018-06-11 17:02:31 -070086 private static final long PURGE_DELAY = 1000; // ms
Charles Chan93e71ba2016-04-29 14:38:22 -070087 private static Logger log = LoggerFactory.getLogger(DefaultRoutingHandler.class);
sanghob35a6192015-04-01 13:05:26 -070088
89 private SegmentRoutingManager srManager;
90 private RoutingRulePopulator rulePopulator;
Shashikanth VH013a7bc2015-12-11 01:32:44 +053091 private HashMap<DeviceId, EcmpShortestPathGraph> currentEcmpSpgMap;
92 private HashMap<DeviceId, EcmpShortestPathGraph> updatedEcmpSpgMap;
sangho666cd6d2015-04-14 16:27:13 -070093 private DeviceConfiguration config;
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +090094 private final Lock statusLock = new ReentrantLock();
95 private volatile Status populationStatus;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070096 private ScheduledExecutorService executorService
Saurav Dasd2fded02016-12-02 15:43:47 -080097 = newScheduledThreadPool(1, groupedThreads("retryftr", "retry-%d", log));
Saurav Das60ca8d52018-04-23 18:42:12 -070098 private ScheduledExecutorService executorServiceMstChg
99 = newScheduledThreadPool(1, groupedThreads("masterChg", "mstch-%d", log));
Saurav Dasf1027d42018-06-11 17:02:31 -0700100 private ScheduledExecutorService executorServiceFRR
101 = newScheduledThreadPool(1, groupedThreads("fullRR", "fullRR-%d", log));
pier8b4ba992019-04-24 16:12:47 +0200102 // Route populators - 0 will leverage available processors
103 private static final int DEFAULT_THREADS = 0;
104 private ExecutorService routePopulators;
Saurav Das60ca8d52018-04-23 18:42:12 -0700105
Saurav Dasc6dc1772018-04-21 17:19:48 -0700106 private Instant lastRoutingChange = Instant.EPOCH;
Saurav Dasf1027d42018-06-11 17:02:31 -0700107 private Instant lastFullReroute = Instant.EPOCH;
sanghob35a6192015-04-01 13:05:26 -0700108
Saurav Dasc6dc1772018-04-21 17:19:48 -0700109 // Distributed store to keep track of ONOS instance that should program the
110 // device pair. There should be only one instance (the king) that programs the same pair.
Charles Chan2ff1bac2018-03-29 16:03:41 -0700111 Map<Set<DeviceId>, NodeId> shouldProgram;
Charles Chana8487b02018-04-18 18:41:05 -0700112 Map<DeviceId, Boolean> shouldProgramCache;
Charles Chan2ff1bac2018-03-29 16:03:41 -0700113
Saurav Dasc6dc1772018-04-21 17:19:48 -0700114 // Local store to keep track of all devices that this instance was responsible
115 // for programming in the last run. Helps to determine if mastership changed
116 // during a run - only relevant for programming as a result of topo change.
117 Set<DeviceId> lastProgrammed;
118
sanghob35a6192015-04-01 13:05:26 -0700119 /**
120 * Represents the default routing population status.
121 */
122 public enum Status {
123 // population process is not started yet.
124 IDLE,
sanghob35a6192015-04-01 13:05:26 -0700125 // population process started.
126 STARTED,
pier8b4ba992019-04-24 16:12:47 +0200127 // population process was aborted due to errors, mostly for groups not found.
sanghob35a6192015-04-01 13:05:26 -0700128 ABORTED,
sanghob35a6192015-04-01 13:05:26 -0700129 // population process was finished successfully.
130 SUCCEEDED
131 }
132
133 /**
134 * Creates a DefaultRoutingHandler object.
135 *
136 * @param srManager SegmentRoutingManager object
137 */
Charles Chan2ff1bac2018-03-29 16:03:41 -0700138 DefaultRoutingHandler(SegmentRoutingManager srManager) {
Charles Chana8487b02018-04-18 18:41:05 -0700139 this.shouldProgram = srManager.storageService.<Set<DeviceId>, NodeId>consistentMapBuilder()
140 .withName("sr-should-program")
141 .withSerializer(Serializer.using(KryoNamespaces.API))
142 .withRelaxedReadConsistency()
143 .build().asJavaMap();
144 this.shouldProgramCache = Maps.newConcurrentMap();
145 update(srManager);
pier8b4ba992019-04-24 16:12:47 +0200146 this.routePopulators = new PredictableExecutor(DEFAULT_THREADS,
147 groupedThreads("onos/sr", "r-populator-%d", log));
Charles Chana8487b02018-04-18 18:41:05 -0700148 }
149
150 /**
151 * Updates a DefaultRoutingHandler object.
152 *
153 * @param srManager SegmentRoutingManager object
154 */
155 void update(SegmentRoutingManager srManager) {
sanghob35a6192015-04-01 13:05:26 -0700156 this.srManager = srManager;
157 this.rulePopulator = checkNotNull(srManager.routingRulePopulator);
sangho666cd6d2015-04-14 16:27:13 -0700158 this.config = checkNotNull(srManager.deviceConfiguration);
sanghob35a6192015-04-01 13:05:26 -0700159 this.populationStatus = Status.IDLE;
sangho20eff1d2015-04-13 15:15:58 -0700160 this.currentEcmpSpgMap = Maps.newHashMap();
Saurav Dasc6dc1772018-04-21 17:19:48 -0700161 this.lastProgrammed = Sets.newConcurrentHashSet();
sanghob35a6192015-04-01 13:05:26 -0700162 }
163
164 /**
Saurav Dasc88d4662017-05-15 15:34:25 -0700165 * Returns an immutable copy of the current ECMP shortest-path graph as
166 * computed by this controller instance.
167 *
Saurav Das7bcbe702017-06-13 15:35:54 -0700168 * @return immutable copy of the current ECMP graph
Saurav Dasc88d4662017-05-15 15:34:25 -0700169 */
170 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEmcpSpgMap() {
171 Builder<DeviceId, EcmpShortestPathGraph> builder = ImmutableMap.builder();
172 currentEcmpSpgMap.entrySet().forEach(entry -> {
173 if (entry.getValue() != null) {
174 builder.put(entry.getKey(), entry.getValue());
175 }
176 });
177 return builder.build();
178 }
179
Saurav Dasceccf242017-08-03 18:30:35 -0700180 /**
181 * Acquires the lock used when making routing changes.
182 */
183 public void acquireRoutingLock() {
184 statusLock.lock();
185 }
186
187 /**
188 * Releases the lock used when making routing changes.
189 */
190 public void releaseRoutingLock() {
191 statusLock.unlock();
192 }
193
194 /**
195 * Determines if routing in the network has been stable in the last
196 * STABLITY_THRESHOLD seconds, by comparing the current time to the last
197 * routing change timestamp.
198 *
199 * @return true if stable
200 */
201 public boolean isRoutingStable() {
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700202 long last = (long) (lastRoutingChange.toEpochMilli() / 1000.0);
203 long now = (long) (Instant.now().toEpochMilli() / 1000.0);
Saurav Das9df5b7c2017-08-14 16:44:43 -0700204 log.trace("Routing stable since {}s", now - last);
Saurav Dasceccf242017-08-03 18:30:35 -0700205 return (now - last) > STABLITY_THRESHOLD;
206 }
207
Saurav Das60ca8d52018-04-23 18:42:12 -0700208 /**
209 * Gracefully shuts down the defaultRoutingHandler. Typically called when
210 * the app is deactivated
211 */
212 public void shutdown() {
213 executorService.shutdown();
214 executorServiceMstChg.shutdown();
Saurav Dasf1027d42018-06-11 17:02:31 -0700215 executorServiceFRR.shutdown();
pier8b4ba992019-04-24 16:12:47 +0200216 routePopulators.shutdown();
Saurav Das60ca8d52018-04-23 18:42:12 -0700217 }
Saurav Dasceccf242017-08-03 18:30:35 -0700218
Saurav Das7bcbe702017-06-13 15:35:54 -0700219 //////////////////////////////////////
220 // Route path handling
221 //////////////////////////////////////
222
Saurav Das45f48152018-01-18 12:07:33 -0800223 /* The following three methods represent the three major ways in which
224 * route-path handling is triggered in the network
Saurav Das7bcbe702017-06-13 15:35:54 -0700225 * a) due to configuration change
226 * b) due to route-added event
227 * c) due to change in the topology
228 */
229
Saurav Dasc88d4662017-05-15 15:34:25 -0700230 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700231 * Populates all routing rules to all switches. Typically triggered at
232 * startup or after a configuration event.
sanghob35a6192015-04-01 13:05:26 -0700233 */
Saurav Dasc88d4662017-05-15 15:34:25 -0700234 public void populateAllRoutingRules() {
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700235 lastRoutingChange = Instant.now();
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900236 statusLock.lock();
237 try {
Saurav Das7bcbe702017-06-13 15:35:54 -0700238 if (populationStatus == Status.STARTED) {
239 log.warn("Previous rule population is not finished. Cannot"
240 + " proceed with populateAllRoutingRules");
241 return;
242 }
243
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900244 populationStatus = Status.STARTED;
245 rulePopulator.resetCounter();
Saurav Das7bcbe702017-06-13 15:35:54 -0700246 log.info("Starting to populate all routing rules");
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900247 log.debug("populateAllRoutingRules: populationStatus is STARTED");
sanghob35a6192015-04-01 13:05:26 -0700248
Saurav Das7bcbe702017-06-13 15:35:54 -0700249 // take a snapshot of the topology
250 updatedEcmpSpgMap = new HashMap<>();
251 Set<EdgePair> edgePairs = new HashSet<>();
252 Set<ArrayList<DeviceId>> routeChanges = new HashSet<>();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800253 for (DeviceId dstSw : srManager.deviceConfiguration.getRouters()) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700254 EcmpShortestPathGraph ecmpSpgUpdated =
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800255 new EcmpShortestPathGraph(dstSw, srManager);
256 updatedEcmpSpgMap.put(dstSw, ecmpSpgUpdated);
Charles Chanba6c5752018-04-02 11:46:38 -0700257 Optional<DeviceId> pairDev = srManager.getPairDeviceId(dstSw);
258 if (pairDev.isPresent()) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700259 // pairDev may not be available yet, but we still need to add
Charles Chanba6c5752018-04-02 11:46:38 -0700260 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev.get(), srManager);
261 updatedEcmpSpgMap.put(pairDev.get(), ecmpSpgUpdated);
262 edgePairs.add(new EdgePair(dstSw, pairDev.get()));
Saurav Das7bcbe702017-06-13 15:35:54 -0700263 }
Charles Chan2ff1bac2018-03-29 16:03:41 -0700264
265 if (!shouldProgram(dstSw)) {
Saurav Dasc6dc1772018-04-21 17:19:48 -0700266 lastProgrammed.remove(dstSw);
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900267 continue;
Saurav Dasc6dc1772018-04-21 17:19:48 -0700268 } else {
269 lastProgrammed.add(dstSw);
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900270 }
Saurav Dasc6dc1772018-04-21 17:19:48 -0700271 // To do a full reroute, assume all route-paths have changed
Charles Chan2ff1bac2018-03-29 16:03:41 -0700272 for (DeviceId dev : deviceAndItsPair(dstSw)) {
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800273 for (DeviceId targetSw : srManager.deviceConfiguration.getRouters()) {
274 if (targetSw.equals(dev)) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700275 continue;
276 }
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800277 routeChanges.add(Lists.newArrayList(targetSw, dev));
Saurav Das7bcbe702017-06-13 15:35:54 -0700278 }
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900279 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700280 }
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900281
Saurav Das7bcbe702017-06-13 15:35:54 -0700282 if (!redoRouting(routeChanges, edgePairs, null)) {
283 log.debug("populateAllRoutingRules: populationStatus is ABORTED");
284 populationStatus = Status.ABORTED;
285 log.warn("Failed to repopulate all routing rules.");
286 return;
sanghob35a6192015-04-01 13:05:26 -0700287 }
288
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900289 log.debug("populateAllRoutingRules: populationStatus is SUCCEEDED");
290 populationStatus = Status.SUCCEEDED;
Saurav Das7bcbe702017-06-13 15:35:54 -0700291 log.info("Completed all routing rule population. Total # of rules pushed : {}",
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900292 rulePopulator.getCounter());
Saurav Dasc88d4662017-05-15 15:34:25 -0700293 return;
pier4bc3fa92019-04-19 20:55:53 +0200294 } catch (Exception e) {
295 log.error("populateAllRoutingRules thrown an exception: {}",
296 e.getMessage(), e);
297 populationStatus = Status.ABORTED;
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900298 } finally {
299 statusLock.unlock();
sanghob35a6192015-04-01 13:05:26 -0700300 }
sanghob35a6192015-04-01 13:05:26 -0700301 }
302
sangho20eff1d2015-04-13 15:15:58 -0700303 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700304 * Populate rules from all other edge devices to the connect-point(s)
305 * specified for the given subnets.
306 *
307 * @param cpts connect point(s) of the subnets being added
308 * @param subnets subnets being added
Charles Chan2fde6d42017-08-23 14:46:43 -0700309 */
310 // XXX refactor
Saurav Das7bcbe702017-06-13 15:35:54 -0700311 protected void populateSubnet(Set<ConnectPoint> cpts, Set<IpPrefix> subnets) {
Charles Chan71e64f12017-09-11 15:21:57 -0700312 if (cpts == null || cpts.size() < 1 || cpts.size() > 2) {
313 log.warn("Skipping populateSubnet due to illegal size of connect points. {}", cpts);
314 return;
315 }
316
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700317 lastRoutingChange = Instant.now();
Saurav Das7bcbe702017-06-13 15:35:54 -0700318 statusLock.lock();
319 try {
320 if (populationStatus == Status.STARTED) {
321 log.warn("Previous rule population is not finished. Cannot"
322 + " proceed with routing rules for added routes");
323 return;
324 }
325 populationStatus = Status.STARTED;
326 rulePopulator.resetCounter();
Charles Chan2fde6d42017-08-23 14:46:43 -0700327 log.info("Starting to populate routing rules for added routes, subnets={}, cpts={}",
328 subnets, cpts);
Saurav Dasc568c342018-01-25 09:49:01 -0800329 // In principle an update to a subnet/prefix should not require a
330 // new ECMPspg calculation as it is not a topology event. As a
331 // result, we use the current/existing ECMPspg in the updated map
332 // used by the redoRouting method.
Saurav Das15a81782018-02-09 09:15:03 -0800333 if (updatedEcmpSpgMap == null) {
334 updatedEcmpSpgMap = new HashMap<>();
335 }
Saurav Dasc568c342018-01-25 09:49:01 -0800336 currentEcmpSpgMap.entrySet().forEach(entry -> {
337 updatedEcmpSpgMap.put(entry.getKey(), entry.getValue());
Saurav Dase7f51012018-02-09 17:26:45 -0800338 if (log.isTraceEnabled()) {
339 log.trace("Root switch: {}", entry.getKey());
340 log.trace(" Current/Existing SPG: {}", entry.getValue());
Saurav Dasc568c342018-01-25 09:49:01 -0800341 }
342 });
Saurav Das7bcbe702017-06-13 15:35:54 -0700343 Set<EdgePair> edgePairs = new HashSet<>();
344 Set<ArrayList<DeviceId>> routeChanges = new HashSet<>();
345 boolean handleRouting = false;
346
347 if (cpts.size() == 2) {
348 // ensure connect points are edge-pairs
349 Iterator<ConnectPoint> iter = cpts.iterator();
350 DeviceId dev1 = iter.next().deviceId();
Charles Chanba6c5752018-04-02 11:46:38 -0700351 Optional<DeviceId> pairDev = srManager.getPairDeviceId(dev1);
352 if (pairDev.isPresent() && iter.next().deviceId().equals(pairDev.get())) {
353 edgePairs.add(new EdgePair(dev1, pairDev.get()));
Saurav Das7bcbe702017-06-13 15:35:54 -0700354 } else {
355 log.warn("Connectpoints {} for subnets {} not on "
356 + "pair-devices.. aborting populateSubnet", cpts, subnets);
357 populationStatus = Status.ABORTED;
358 return;
359 }
360 for (ConnectPoint cp : cpts) {
Saurav Dasc568c342018-01-25 09:49:01 -0800361 if (updatedEcmpSpgMap.get(cp.deviceId()) == null) {
362 EcmpShortestPathGraph ecmpSpgUpdated =
Saurav Das7bcbe702017-06-13 15:35:54 -0700363 new EcmpShortestPathGraph(cp.deviceId(), srManager);
Saurav Dasc568c342018-01-25 09:49:01 -0800364 updatedEcmpSpgMap.put(cp.deviceId(), ecmpSpgUpdated);
365 log.warn("populateSubnet: no updated graph for dev:{}"
366 + " ... creating", cp.deviceId());
367 }
Charles Chan2ff1bac2018-03-29 16:03:41 -0700368 if (!shouldProgram(cp.deviceId())) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700369 continue;
370 }
371 handleRouting = true;
372 }
373 } else {
374 // single connect point
375 DeviceId dstSw = cpts.iterator().next().deviceId();
Saurav Dasc568c342018-01-25 09:49:01 -0800376 if (updatedEcmpSpgMap.get(dstSw) == null) {
377 EcmpShortestPathGraph ecmpSpgUpdated =
Saurav Das7bcbe702017-06-13 15:35:54 -0700378 new EcmpShortestPathGraph(dstSw, srManager);
Saurav Dasc568c342018-01-25 09:49:01 -0800379 updatedEcmpSpgMap.put(dstSw, ecmpSpgUpdated);
380 log.warn("populateSubnet: no updated graph for dev:{}"
381 + " ... creating", dstSw);
382 }
Charles Chan2ff1bac2018-03-29 16:03:41 -0700383 handleRouting = shouldProgram(dstSw);
Saurav Das7bcbe702017-06-13 15:35:54 -0700384 }
385
386 if (!handleRouting) {
387 log.debug("This instance is not handling ecmp routing to the "
388 + "connectPoint(s) {}", cpts);
389 populationStatus = Status.ABORTED;
390 return;
391 }
392
393 // if it gets here, this instance should handle routing for the
394 // connectpoint(s). Assume all route-paths have to be updated to
395 // the connectpoint(s) with the following exceptions
396 // 1. if target is non-edge no need for routing rules
397 // 2. if target is one of the connectpoints
398 for (ConnectPoint cp : cpts) {
399 DeviceId dstSw = cp.deviceId();
400 for (Device targetSw : srManager.deviceService.getDevices()) {
401 boolean isEdge = false;
402 try {
403 isEdge = config.isEdgeDevice(targetSw.id());
404 } catch (DeviceConfigNotFoundException e) {
Charles Chan92726132018-02-16 17:20:54 -0800405 log.warn(e.getMessage() + "aborting populateSubnet on targetSw {}", targetSw.id());
406 continue;
Saurav Das7bcbe702017-06-13 15:35:54 -0700407 }
Charles Chanba6c5752018-04-02 11:46:38 -0700408 Optional<DeviceId> pairDev = srManager.getPairDeviceId(dstSw);
Saurav Das7bcbe702017-06-13 15:35:54 -0700409 if (dstSw.equals(targetSw.id()) || !isEdge ||
Charles Chanba6c5752018-04-02 11:46:38 -0700410 (cpts.size() == 2 && pairDev.isPresent() && targetSw.id().equals(pairDev.get()))) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700411 continue;
412 }
413 routeChanges.add(Lists.newArrayList(targetSw.id(), dstSw));
414 }
415 }
416
417 if (!redoRouting(routeChanges, edgePairs, subnets)) {
418 log.debug("populateSubnet: populationStatus is ABORTED");
419 populationStatus = Status.ABORTED;
420 log.warn("Failed to repopulate the rules for subnet.");
421 return;
422 }
423
424 log.debug("populateSubnet: populationStatus is SUCCEEDED");
425 populationStatus = Status.SUCCEEDED;
426 log.info("Completed subnet population. Total # of rules pushed : {}",
427 rulePopulator.getCounter());
428 return;
429
pier4bc3fa92019-04-19 20:55:53 +0200430 } catch (Exception e) {
431 log.error("populateSubnet thrown an exception: {}",
432 e.getMessage(), e);
433 populationStatus = Status.ABORTED;
Saurav Das7bcbe702017-06-13 15:35:54 -0700434 } finally {
435 statusLock.unlock();
436 }
437 }
438
439 /**
Saurav Dasc88d4662017-05-15 15:34:25 -0700440 * Populates the routing rules or makes hash group changes according to the
441 * route-path changes due to link failure, switch failure or link up. This
442 * method should only be called for one of these three possible event-types.
Saurav Das604ab3a2018-03-18 21:28:15 -0700443 * Note that when a switch goes away, all of its links fail as well, but
444 * this is handled as a single switch removal event.
sangho20eff1d2015-04-13 15:15:58 -0700445 *
Saurav Das604ab3a2018-03-18 21:28:15 -0700446 * @param linkDown the single failed link, or null for other conditions such
447 * as link-up or a removed switch
Saurav Dasc88d4662017-05-15 15:34:25 -0700448 * @param linkUp the single link up, or null for other conditions such as
Saurav Das604ab3a2018-03-18 21:28:15 -0700449 * link-down or a removed switch
450 * @param switchDown the removed switch, or null for other conditions such
451 * as link-down or link-up
452 * @param seenBefore true if this event is for a linkUp or linkDown for a
453 * seen link
454 */
455 // TODO This method should be refactored into three separated methods
Charles Chan15281332018-06-19 20:56:33 -0700456 public void populateRoutingRulesForLinkStatusChange(Link linkDown, Link linkUp,
457 DeviceId switchDown, boolean seenBefore) {
Saurav Das604ab3a2018-03-18 21:28:15 -0700458 if (Stream.of(linkDown, linkUp, switchDown).filter(Objects::nonNull)
459 .count() != 1) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700460 log.warn("Only one event can be handled for link status change .. aborting");
461 return;
462 }
Saurav Das604ab3a2018-03-18 21:28:15 -0700463
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700464 lastRoutingChange = Instant.now();
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900465 statusLock.lock();
466 try {
sangho20eff1d2015-04-13 15:15:58 -0700467
468 if (populationStatus == Status.STARTED) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700469 log.warn("Previous rule population is not finished. Cannot"
Saurav Dasc568c342018-01-25 09:49:01 -0800470 + " proceeed with routingRules for Topology change");
Saurav Dasc88d4662017-05-15 15:34:25 -0700471 return;
sangho20eff1d2015-04-13 15:15:58 -0700472 }
473
Saurav Das7bcbe702017-06-13 15:35:54 -0700474 // Take snapshots of the topology
sangho45b009c2015-05-07 13:30:57 -0700475 updatedEcmpSpgMap = new HashMap<>();
Saurav Das7bcbe702017-06-13 15:35:54 -0700476 Set<EdgePair> edgePairs = new HashSet<>();
sangho45b009c2015-05-07 13:30:57 -0700477 for (Device sw : srManager.deviceService.getDevices()) {
Shashikanth VH013a7bc2015-12-11 01:32:44 +0530478 EcmpShortestPathGraph ecmpSpgUpdated =
479 new EcmpShortestPathGraph(sw.id(), srManager);
sangho45b009c2015-05-07 13:30:57 -0700480 updatedEcmpSpgMap.put(sw.id(), ecmpSpgUpdated);
Charles Chanba6c5752018-04-02 11:46:38 -0700481 Optional<DeviceId> pairDev = srManager.getPairDeviceId(sw.id());
482 if (pairDev.isPresent()) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700483 // pairDev may not be available yet, but we still need to add
Charles Chanba6c5752018-04-02 11:46:38 -0700484 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev.get(), srManager);
485 updatedEcmpSpgMap.put(pairDev.get(), ecmpSpgUpdated);
486 edgePairs.add(new EdgePair(sw.id(), pairDev.get()));
Saurav Das7bcbe702017-06-13 15:35:54 -0700487 }
sangho45b009c2015-05-07 13:30:57 -0700488 }
489
Saurav Dasc568c342018-01-25 09:49:01 -0800490 log.info("Starting to populate routing rules from Topology change");
sangho52abe3a2015-05-05 14:13:34 -0700491
sangho20eff1d2015-04-13 15:15:58 -0700492 Set<ArrayList<DeviceId>> routeChanges;
Saurav Dasc88d4662017-05-15 15:34:25 -0700493 log.debug("populateRoutingRulesForLinkStatusChange: "
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700494 + "populationStatus is STARTED");
sangho20eff1d2015-04-13 15:15:58 -0700495 populationStatus = Status.STARTED;
Saurav Dasc568c342018-01-25 09:49:01 -0800496 rulePopulator.resetCounter(); //XXX maybe useful to have a rehash ctr
497 boolean hashGroupsChanged = false;
Saurav Das4e3224f2016-11-29 14:27:25 -0800498 // try optimized re-routing
Saurav Dasc88d4662017-05-15 15:34:25 -0700499 if (linkDown == null) {
500 // either a linkUp or a switchDown - compute all route changes by
501 // comparing all routes of existing ECMP SPG to new ECMP SPG
Saurav Dase0d4c872018-03-05 14:37:16 -0800502 routeChanges = computeRouteChange(switchDown);
Saurav Dasc88d4662017-05-15 15:34:25 -0700503
Saurav Das9df5b7c2017-08-14 16:44:43 -0700504 // deal with linkUp of a seen-before link
Saurav Das604ab3a2018-03-18 21:28:15 -0700505 if (linkUp != null && seenBefore) {
Saurav Das9df5b7c2017-08-14 16:44:43 -0700506 // link previously seen before
507 // do hash-bucket changes instead of a re-route
508 processHashGroupChange(routeChanges, false, null);
509 // clear out routesChanges so a re-route is not attempted
510 routeChanges = ImmutableSet.of();
Saurav Dasc568c342018-01-25 09:49:01 -0800511 hashGroupsChanged = true;
Saurav Dasc88d4662017-05-15 15:34:25 -0700512 }
Saurav Das9df5b7c2017-08-14 16:44:43 -0700513 // for a linkUp of a never-seen-before link
514 // let it fall through to a reroute of the routeChanges
Saurav Dasc88d4662017-05-15 15:34:25 -0700515
Saurav Das9df5b7c2017-08-14 16:44:43 -0700516 //deal with switchDown
517 if (switchDown != null) {
518 processHashGroupChange(routeChanges, true, switchDown);
519 // clear out routesChanges so a re-route is not attempted
520 routeChanges = ImmutableSet.of();
Saurav Dasc568c342018-01-25 09:49:01 -0800521 hashGroupsChanged = true;
Saurav Das9df5b7c2017-08-14 16:44:43 -0700522 }
sangho20eff1d2015-04-13 15:15:58 -0700523 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -0700524 // link has gone down
525 // Compare existing ECMP SPG only with the link that went down
526 routeChanges = computeDamagedRoutes(linkDown);
Saurav Dasf1027d42018-06-11 17:02:31 -0700527 processHashGroupChange(routeChanges, true, null);
528 // clear out routesChanges so a re-route is not attempted
529 routeChanges = ImmutableSet.of();
530 hashGroupsChanged = true;
Saurav Dasb5c236e2016-06-07 10:08:06 -0700531 }
532
sangho20eff1d2015-04-13 15:15:58 -0700533 if (routeChanges.isEmpty()) {
Saurav Dasc568c342018-01-25 09:49:01 -0800534 if (hashGroupsChanged) {
535 log.info("Hash-groups changed for link status change");
536 } else {
537 log.info("No re-route or re-hash attempted for the link"
538 + " status change");
539 updatedEcmpSpgMap.keySet().forEach(devId -> {
540 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
541 log.debug("Updating ECMPspg for remaining dev:{}", devId);
542 });
543 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700544 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sangho20eff1d2015-04-13 15:15:58 -0700545 populationStatus = Status.SUCCEEDED;
Saurav Dasc88d4662017-05-15 15:34:25 -0700546 return;
sangho20eff1d2015-04-13 15:15:58 -0700547 }
548
Saurav Dasc88d4662017-05-15 15:34:25 -0700549 // reroute of routeChanges
Saurav Das7bcbe702017-06-13 15:35:54 -0700550 if (redoRouting(routeChanges, edgePairs, null)) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700551 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sangho20eff1d2015-04-13 15:15:58 -0700552 populationStatus = Status.SUCCEEDED;
Saurav Das7bcbe702017-06-13 15:35:54 -0700553 log.info("Completed repopulation of rules for link-status change."
554 + " # of rules populated : {}", rulePopulator.getCounter());
Saurav Dasc88d4662017-05-15 15:34:25 -0700555 return;
sangho20eff1d2015-04-13 15:15:58 -0700556 } else {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700557 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is ABORTED");
sangho20eff1d2015-04-13 15:15:58 -0700558 populationStatus = Status.ABORTED;
Saurav Das7bcbe702017-06-13 15:35:54 -0700559 log.warn("Failed to repopulate the rules for link status change.");
Saurav Dasc88d4662017-05-15 15:34:25 -0700560 return;
sangho20eff1d2015-04-13 15:15:58 -0700561 }
pier4bc3fa92019-04-19 20:55:53 +0200562 } catch (Exception e) {
563 log.error("populateRoutingRulesForLinkStatusChange thrown an exception: {}",
564 e.getMessage(), e);
565 populationStatus = Status.ABORTED;
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900566 } finally {
567 statusLock.unlock();
sangho20eff1d2015-04-13 15:15:58 -0700568 }
569 }
570
Saurav Dasc88d4662017-05-15 15:34:25 -0700571 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700572 * Processes a set a route-path changes by reprogramming routing rules and
573 * creating new hash-groups or editing them if necessary. This method also
574 * determines the next-hops for the route-path from the src-switch (target)
575 * of the path towards the dst-switch of the path.
Saurav Dasc88d4662017-05-15 15:34:25 -0700576 *
Saurav Das7bcbe702017-06-13 15:35:54 -0700577 * @param routeChanges a set of route-path changes, where each route-path is
578 * a list with its first element the src-switch (target)
579 * of the path, and the second element the dst-switch of
580 * the path.
581 * @param edgePairs a set of edge-switches that are paired by configuration
582 * @param subnets a set of prefixes that need to be populated in the routing
583 * table of the target switch in the route-path. Can be null,
584 * in which case all the prefixes belonging to the dst-switch
585 * will be populated in the target switch
586 * @return true if successful in repopulating all routes
Saurav Dasc88d4662017-05-15 15:34:25 -0700587 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700588 private boolean redoRouting(Set<ArrayList<DeviceId>> routeChanges,
589 Set<EdgePair> edgePairs, Set<IpPrefix> subnets) {
590 // first make every entry two-elements
591 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
592 for (ArrayList<DeviceId> route : routeChanges) {
593 if (route.size() == 1) {
594 DeviceId dstSw = route.get(0);
595 EcmpShortestPathGraph ec = updatedEcmpSpgMap.get(dstSw);
596 if (ec == null) {
597 log.warn("No graph found for {} .. aborting redoRouting", dstSw);
598 return false;
599 }
600 ec.getAllLearnedSwitchesAndVia().keySet().forEach(key -> {
601 ec.getAllLearnedSwitchesAndVia().get(key).keySet().forEach(target -> {
602 changedRoutes.add(Lists.newArrayList(target, dstSw));
603 });
604 });
605 } else {
606 DeviceId targetSw = route.get(0);
607 DeviceId dstSw = route.get(1);
608 changedRoutes.add(Lists.newArrayList(targetSw, dstSw));
609 }
610 }
611
612 // now process changedRoutes according to edgePairs
613 if (!redoRoutingEdgePairs(edgePairs, subnets, changedRoutes)) {
614 return false; //abort routing and fail fast
615 }
616
617 // whatever is left in changedRoutes is now processed for individual dsts.
Saurav Dasc568c342018-01-25 09:49:01 -0800618 Set<DeviceId> updatedDevices = Sets.newHashSet();
619 if (!redoRoutingIndividualDests(subnets, changedRoutes,
620 updatedDevices)) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700621 return false; //abort routing and fail fast
622 }
623
Saurav Das7bcbe702017-06-13 15:35:54 -0700624 // update ecmpSPG for all edge-pairs
625 for (EdgePair ep : edgePairs) {
626 currentEcmpSpgMap.put(ep.dev1, updatedEcmpSpgMap.get(ep.dev1));
627 currentEcmpSpgMap.put(ep.dev2, updatedEcmpSpgMap.get(ep.dev2));
628 log.debug("Updating ECMPspg for edge-pair:{}-{}", ep.dev1, ep.dev2);
629 }
Saurav Dasc568c342018-01-25 09:49:01 -0800630
631 // here is where we update all devices not touched by this instance
632 updatedEcmpSpgMap.keySet().stream()
633 .filter(devId -> !edgePairs.stream().anyMatch(ep -> ep.includes(devId)))
634 .filter(devId -> !updatedDevices.contains(devId))
635 .forEach(devId -> {
636 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
637 log.debug("Updating ECMPspg for remaining dev:{}", devId);
638 });
Saurav Das7bcbe702017-06-13 15:35:54 -0700639 return true;
640 }
641
642 /**
643 * Programs targetSw in the changedRoutes for given prefixes reachable by
644 * an edgePair. If no prefixes are given, the method will use configured
645 * subnets/prefixes. If some configured subnets belong only to a specific
646 * destination in the edgePair, then the target switch will be programmed
647 * only to that destination.
648 *
649 * @param edgePairs set of edge-pairs for which target will be programmed
650 * @param subnets a set of prefixes that need to be populated in the routing
651 * table of the target switch in the changedRoutes. Can be null,
652 * in which case all the configured prefixes belonging to the
653 * paired switches will be populated in the target switch
654 * @param changedRoutes a set of route-path changes, where each route-path is
655 * a list with its first element the src-switch (target)
656 * of the path, and the second element the dst-switch of
657 * the path.
658 * @return true if successful
659 */
pier8b4ba992019-04-24 16:12:47 +0200660 private boolean redoRoutingEdgePairs(Set<EdgePair> edgePairs, Set<IpPrefix> subnets,
661 Set<ArrayList<DeviceId>> changedRoutes) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700662 for (EdgePair ep : edgePairs) {
663 // temp store for a target's changedRoutes to this edge-pair
664 Map<DeviceId, Set<ArrayList<DeviceId>>> targetRoutes = new HashMap<>();
665 Iterator<ArrayList<DeviceId>> i = changedRoutes.iterator();
666 while (i.hasNext()) {
667 ArrayList<DeviceId> route = i.next();
668 DeviceId dstSw = route.get(1);
669 if (ep.includes(dstSw)) {
670 // routeChange for edge pair found
671 // sort by target iff target is edge and remove from changedRoutes
672 DeviceId targetSw = route.get(0);
673 try {
674 if (!srManager.deviceConfiguration.isEdgeDevice(targetSw)) {
675 continue;
676 }
677 } catch (DeviceConfigNotFoundException e) {
678 log.warn(e.getMessage() + "aborting redoRouting");
679 return false;
680 }
681 // route is from another edge to this edge-pair
682 if (targetRoutes.containsKey(targetSw)) {
683 targetRoutes.get(targetSw).add(route);
684 } else {
685 Set<ArrayList<DeviceId>> temp = new HashSet<>();
686 temp.add(route);
687 targetRoutes.put(targetSw, temp);
688 }
689 i.remove();
690 }
691 }
692 // so now for this edgepair we have a per target set of routechanges
693 // process target->edgePair route
pier8b4ba992019-04-24 16:12:47 +0200694 List<Future<Boolean>> futures = Lists.newArrayList();
Saurav Das7bcbe702017-06-13 15:35:54 -0700695 for (Map.Entry<DeviceId, Set<ArrayList<DeviceId>>> entry :
696 targetRoutes.entrySet()) {
697 log.debug("* redoRoutingDstPair Target:{} -> edge-pair {}",
698 entry.getKey(), ep);
pier8b4ba992019-04-24 16:12:47 +0200699 futures.add(routePopulators.submit(new RedoRoutingEdgePair(entry.getKey(), entry.getValue(),
700 subnets, ep)));
701 }
702 if (!checkJobs(futures)) {
703 return false;
Saurav Das7bcbe702017-06-13 15:35:54 -0700704 }
705 // if it gets here it has succeeded for all targets to this edge-pair
706 }
707 return true;
708 }
709
pier8b4ba992019-04-24 16:12:47 +0200710 private final class RedoRoutingEdgePair implements PickyCallable<Boolean> {
711 private DeviceId targetSw;
712 private Set<ArrayList<DeviceId>> routes;
713 private Set<IpPrefix> subnets;
714 private EdgePair ep;
715
716 /**
717 * Builds a RedoRoutingEdgePair task which provides a result.
718 *
719 * @param targetSw the target switch
720 * @param routes the changed routes
721 * @param subnets the subnets
722 * @param ep the edge pair
723 */
724 RedoRoutingEdgePair(DeviceId targetSw, Set<ArrayList<DeviceId>> routes,
725 Set<IpPrefix> subnets, EdgePair ep) {
726 this.targetSw = targetSw;
727 this.routes = routes;
728 this.subnets = subnets;
729 this.ep = ep;
730 }
731
732 @Override
733 public Boolean call() throws Exception {
734 return redoRoutingEdgePair();
735 }
736
737 @Override
738 public int hint() {
739 return targetSw.hashCode();
740 }
741
742 private boolean redoRoutingEdgePair() {
743 Map<DeviceId, Set<DeviceId>> perDstNextHops = new HashMap<>();
744 routes.forEach(route -> {
745 Set<DeviceId> nhops = getNextHops(route.get(0), route.get(1));
746 log.debug("route: target {} -> dst {} found with next-hops {}",
747 route.get(0), route.get(1), nhops);
748 perDstNextHops.put(route.get(1), nhops);
749 });
750
751 List<Set<IpPrefix>> batchedSubnetDev1, batchedSubnetDev2;
752 if (subnets != null) {
753 batchedSubnetDev1 = Lists.<Set<IpPrefix>>newArrayList(Sets.newHashSet(subnets));
754 batchedSubnetDev2 = Lists.<Set<IpPrefix>>newArrayList(Sets.newHashSet(subnets));
755 } else {
756 batchedSubnetDev1 = config.getBatchedSubnets(ep.dev1);
757 batchedSubnetDev2 = config.getBatchedSubnets(ep.dev2);
758 }
759 List<Set<IpPrefix>> batchedSubnetBoth = Streams
760 .zip(batchedSubnetDev1.stream(), batchedSubnetDev2.stream(), (a, b) -> Sets.intersection(a, b))
761 .filter(set -> !set.isEmpty())
762 .collect(Collectors.toList());
763 List<Set<IpPrefix>> batchedSubnetDev1Only = Streams
764 .zip(batchedSubnetDev1.stream(), batchedSubnetDev2.stream(), (a, b) -> Sets.difference(a, b))
765 .filter(set -> !set.isEmpty())
766 .collect(Collectors.toList());
767 List<Set<IpPrefix>> batchedSubnetDev2Only = Streams
768 .zip(batchedSubnetDev1.stream(), batchedSubnetDev2.stream(), (a, b) -> Sets.difference(b, a))
769 .filter(set -> !set.isEmpty())
770 .collect(Collectors.toList());
771
772 Set<DeviceId> nhDev1 = perDstNextHops.get(ep.dev1);
773 Set<DeviceId> nhDev2 = perDstNextHops.get(ep.dev2);
774
775 // handle routing to subnets common to edge-pair
776 // only if the targetSw is not part of the edge-pair and there
777 // exists a next hop to at least one of the devices in the edge-pair
778 if (!ep.includes(targetSw)
779 && ((nhDev1 != null && !nhDev1.isEmpty()) || (nhDev2 != null && !nhDev2.isEmpty()))) {
780 log.trace("getSubnets on both {} and {}: {}", ep.dev1, ep.dev2, batchedSubnetBoth);
781 for (Set<IpPrefix> prefixes : batchedSubnetBoth) {
782 if (!populateEcmpRoutingRulePartial(targetSw, ep.dev1, ep.dev2,
783 perDstNextHops, prefixes)) {
784 return false; // abort everything and fail fast
785 }
786 }
787
788 }
789 // handle routing to subnets that only belong to dev1 only if
790 // a next-hop exists from the target to dev1
791 if (!batchedSubnetDev1Only.isEmpty() &&
792 batchedSubnetDev1Only.stream().anyMatch(subnet -> !subnet.isEmpty()) &&
793 nhDev1 != null && !nhDev1.isEmpty()) {
794 Map<DeviceId, Set<DeviceId>> onlyDev1NextHops = new HashMap<>();
795 onlyDev1NextHops.put(ep.dev1, nhDev1);
796 log.trace("getSubnets on {} only: {}", ep.dev1, batchedSubnetDev1Only);
797 for (Set<IpPrefix> prefixes : batchedSubnetDev1Only) {
798 if (!populateEcmpRoutingRulePartial(targetSw, ep.dev1, null,
799 onlyDev1NextHops, prefixes)) {
800 return false; // abort everything and fail fast
801 }
802 }
803 }
804 // handle routing to subnets that only belong to dev2 only if
805 // a next-hop exists from the target to dev2
806 if (!batchedSubnetDev2Only.isEmpty() &&
807 batchedSubnetDev2Only.stream().anyMatch(subnet -> !subnet.isEmpty()) &&
808 nhDev2 != null && !nhDev2.isEmpty()) {
809 Map<DeviceId, Set<DeviceId>> onlyDev2NextHops = new HashMap<>();
810 onlyDev2NextHops.put(ep.dev2, nhDev2);
811 log.trace("getSubnets on {} only: {}", ep.dev2, batchedSubnetDev2Only);
812 for (Set<IpPrefix> prefixes : batchedSubnetDev2Only) {
813 if (!populateEcmpRoutingRulePartial(targetSw, ep.dev2, null,
814 onlyDev2NextHops, prefixes)) {
815 return false; // abort everything and fail fast
816 }
817 }
818 }
819 return true;
820 }
821 }
822
Saurav Das7bcbe702017-06-13 15:35:54 -0700823 /**
824 * Programs targetSw in the changedRoutes for given prefixes reachable by
825 * a destination switch that is not part of an edge-pair.
826 * If no prefixes are given, the method will use configured subnets/prefixes.
827 *
828 * @param subnets a set of prefixes that need to be populated in the routing
829 * table of the target switch in the changedRoutes. Can be null,
830 * in which case all the configured prefixes belonging to the
831 * paired switches will be populated in the target switch
832 * @param changedRoutes a set of route-path changes, where each route-path is
833 * a list with its first element the src-switch (target)
834 * of the path, and the second element the dst-switch of
835 * the path.
836 * @return true if successful
837 */
pier8b4ba992019-04-24 16:12:47 +0200838 private boolean redoRoutingIndividualDests(Set<IpPrefix> subnets, Set<ArrayList<DeviceId>> changedRoutes,
Saurav Dasc568c342018-01-25 09:49:01 -0800839 Set<DeviceId> updatedDevices) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700840 // aggregate route-path changes for each dst device
841 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> routesBydevice =
842 new HashMap<>();
843 for (ArrayList<DeviceId> route: changedRoutes) {
844 DeviceId dstSw = route.get(1);
845 ArrayList<ArrayList<DeviceId>> deviceRoutes =
846 routesBydevice.get(dstSw);
847 if (deviceRoutes == null) {
848 deviceRoutes = new ArrayList<>();
849 routesBydevice.put(dstSw, deviceRoutes);
850 }
851 deviceRoutes.add(route);
852 }
pier8b4ba992019-04-24 16:12:47 +0200853 // iterate over the impacted devices
Saurav Das7bcbe702017-06-13 15:35:54 -0700854 for (DeviceId impactedDstDevice : routesBydevice.keySet()) {
855 ArrayList<ArrayList<DeviceId>> deviceRoutes =
856 routesBydevice.get(impactedDstDevice);
pier8b4ba992019-04-24 16:12:47 +0200857 List<Future<Boolean>> futures = Lists.newArrayList();
Saurav Das7bcbe702017-06-13 15:35:54 -0700858 for (ArrayList<DeviceId> route: deviceRoutes) {
859 log.debug("* redoRoutingIndiDst Target: {} -> dst: {}",
860 route.get(0), route.get(1));
pier8b4ba992019-04-24 16:12:47 +0200861 futures.add(routePopulators.submit(new RedoRoutingIndividualDest(subnets, route)));
862 }
863 // check the execution of each job
864 if (!checkJobs(futures)) {
865 return false;
Saurav Das7bcbe702017-06-13 15:35:54 -0700866 }
867 //Only if all the flows for all impacted routes to a
868 //specific target are pushed successfully, update the
869 //ECMP graph for that target. Or else the next event
870 //would not see any changes in the ECMP graphs.
871 //In another case, the target switch has gone away, so
872 //routes can't be installed. In that case, the current map
873 //is updated here, without any flows being pushed.
874 currentEcmpSpgMap.put(impactedDstDevice,
875 updatedEcmpSpgMap.get(impactedDstDevice));
Saurav Dasc568c342018-01-25 09:49:01 -0800876 updatedDevices.add(impactedDstDevice);
Saurav Das7bcbe702017-06-13 15:35:54 -0700877 log.debug("Updating ECMPspg for impacted dev:{}", impactedDstDevice);
878 }
879 return true;
880 }
881
pier8b4ba992019-04-24 16:12:47 +0200882 private final class RedoRoutingIndividualDest implements PickyCallable<Boolean> {
883 private DeviceId targetSw;
884 private ArrayList<DeviceId> route;
885 private Set<IpPrefix> subnets;
886
887 /**
888 * Builds a RedoRoutingIndividualDest task, which provides a result.
889 *
890 * @param subnets a set of prefixes
891 * @param route a route-path change
892 */
893 RedoRoutingIndividualDest(Set<IpPrefix> subnets, ArrayList<DeviceId> route) {
894 this.targetSw = route.get(0);
895 this.route = route;
896 this.subnets = subnets;
897 }
898
899 @Override
900 public Boolean call() throws Exception {
901 DeviceId dstSw = route.get(1); // same as impactedDstDevice
902 Set<DeviceId> nextHops = getNextHops(targetSw, dstSw);
903 if (nextHops.isEmpty()) {
904 log.debug("Could not find next hop from target:{} --> dst {} "
905 + "skipping this route", targetSw, dstSw);
906 return true;
907 }
908 Map<DeviceId, Set<DeviceId>> nhops = new HashMap<>();
909 nhops.put(dstSw, nextHops);
910 if (!populateEcmpRoutingRulePartial(targetSw, dstSw, null, nhops,
911 (subnets == null) ? Sets.newHashSet() : subnets)) {
912 return false; // abort routing and fail fast
913 }
914 log.debug("Populating flow rules from target: {} to dst: {}"
915 + " is successful", targetSw, dstSw);
916 return true;
917 }
918
919 @Override
920 public int hint() {
921 return targetSw.hashCode();
922 }
923 }
924
Saurav Das7bcbe702017-06-13 15:35:54 -0700925 /**
926 * Populate ECMP rules for subnets from target to destination via nexthops.
927 *
928 * @param targetSw Device ID of target switch in which rules will be programmed
929 * @param destSw1 Device ID of final destination switch to which the rules will forward
930 * @param destSw2 Device ID of paired destination switch to which the rules will forward
931 * A null deviceId indicates packets should only be sent to destSw1
Saurav Dasa4020382018-02-14 14:14:54 -0800932 * @param nextHops Map of a set of next hops per destSw
Saurav Das7bcbe702017-06-13 15:35:54 -0700933 * @param subnets Subnets to be populated. If empty, populate all configured subnets.
934 * @return true if it succeeds in populating rules
935 */ // refactor
pier8b4ba992019-04-24 16:12:47 +0200936 private boolean populateEcmpRoutingRulePartial(DeviceId targetSw, DeviceId destSw1, DeviceId destSw2,
937 Map<DeviceId, Set<DeviceId>> nextHops, Set<IpPrefix> subnets) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700938 boolean result;
939 // If both target switch and dest switch are edge routers, then set IP
940 // rule for both subnet and router IP.
941 boolean targetIsEdge;
942 boolean dest1IsEdge;
943 Ip4Address dest1RouterIpv4, dest2RouterIpv4 = null;
944 Ip6Address dest1RouterIpv6, dest2RouterIpv6 = null;
945
946 try {
947 targetIsEdge = config.isEdgeDevice(targetSw);
948 dest1IsEdge = config.isEdgeDevice(destSw1);
949 dest1RouterIpv4 = config.getRouterIpv4(destSw1);
950 dest1RouterIpv6 = config.getRouterIpv6(destSw1);
951 if (destSw2 != null) {
952 dest2RouterIpv4 = config.getRouterIpv4(destSw2);
953 dest2RouterIpv6 = config.getRouterIpv6(destSw2);
954 }
955 } catch (DeviceConfigNotFoundException e) {
956 log.warn(e.getMessage() + " Aborting populateEcmpRoutingRulePartial.");
Saurav Dasc88d4662017-05-15 15:34:25 -0700957 return false;
958 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700959
960 if (targetIsEdge && dest1IsEdge) {
Charles Chan022d6672019-04-17 14:20:26 -0700961 List<Set<IpPrefix>> batchedSubnets;
962 if (subnets != null && !subnets.isEmpty()) {
963 batchedSubnets = Lists.<Set<IpPrefix>>newArrayList(Sets.newHashSet(subnets));
964 } else {
965 batchedSubnets = config.getBatchedSubnets(destSw1);
966 }
Saurav Dasa4020382018-02-14 14:14:54 -0800967 // XXX - Rethink this - ignoring routerIPs in all other switches
968 // even edge to edge switches
Saurav Das7bcbe702017-06-13 15:35:54 -0700969 /*subnets.add(dest1RouterIpv4.toIpPrefix());
970 if (dest1RouterIpv6 != null) {
971 subnets.add(dest1RouterIpv6.toIpPrefix());
972 }
973 if (destSw2 != null && dest2RouterIpv4 != null) {
974 subnets.add(dest2RouterIpv4.toIpPrefix());
975 if (dest2RouterIpv6 != null) {
976 subnets.add(dest2RouterIpv6.toIpPrefix());
977 }
978 }*/
Charles Chan022d6672019-04-17 14:20:26 -0700979 log.trace("getSubnets on {}: {}", destSw1, batchedSubnets);
980 for (Set<IpPrefix> prefixes : batchedSubnets) {
981 log.debug(". populateEcmpRoutingRulePartial in device {} towards {} {} "
982 + "for subnets {}", targetSw, destSw1,
983 (destSw2 != null) ? ("& " + destSw2) : "",
984 prefixes);
985 if (!rulePopulator.populateIpRuleForSubnet(targetSw, prefixes, destSw1, destSw2, nextHops)) {
986 return false;
987 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700988 }
Saurav Dasc88d4662017-05-15 15:34:25 -0700989 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700990
991 if (!targetIsEdge && dest1IsEdge) {
992 // MPLS rules in all non-edge target devices. These rules are for
993 // individual destinations, even if the dsts are part of edge-pairs.
994 log.debug(". populateEcmpRoutingRulePartial in device{} towards {} for "
995 + "all MPLS rules", targetSw, destSw1);
pier8b4ba992019-04-24 16:12:47 +0200996 result = rulePopulator.populateMplsRule(targetSw, destSw1, nextHops.get(destSw1), dest1RouterIpv4);
Saurav Das7bcbe702017-06-13 15:35:54 -0700997 if (!result) {
998 return false;
999 }
1000 if (dest1RouterIpv6 != null) {
Saurav Dasa4020382018-02-14 14:14:54 -08001001 int v4sid = 0, v6sid = 0;
1002 try {
1003 v4sid = config.getIPv4SegmentId(destSw1);
1004 v6sid = config.getIPv6SegmentId(destSw1);
1005 } catch (DeviceConfigNotFoundException e) {
1006 log.warn(e.getMessage());
1007 }
1008 if (v4sid != v6sid) {
pier8b4ba992019-04-24 16:12:47 +02001009 result = rulePopulator.populateMplsRule(targetSw, destSw1, nextHops.get(destSw1),
Saurav Dasa4020382018-02-14 14:14:54 -08001010 dest1RouterIpv6);
1011 if (!result) {
1012 return false;
1013 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001014 }
1015 }
1016 }
1017
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -07001018 if (!targetIsEdge && !dest1IsEdge) {
1019 // MPLS rules for inter-connected spines
1020 // can be merged with above if, left it here for clarity
1021 log.debug(". populateEcmpRoutingRulePartial in device{} towards {} for "
1022 + "all MPLS rules", targetSw, destSw1);
1023
pier8b4ba992019-04-24 16:12:47 +02001024 result = rulePopulator.populateMplsRule(targetSw, destSw1, nextHops.get(destSw1), dest1RouterIpv4);
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -07001025 if (!result) {
1026 return false;
1027 }
1028
1029 if (dest1RouterIpv6 != null) {
1030 int v4sid = 0, v6sid = 0;
1031 try {
1032 v4sid = config.getIPv4SegmentId(destSw1);
1033 v6sid = config.getIPv6SegmentId(destSw1);
1034 } catch (DeviceConfigNotFoundException e) {
1035 log.warn(e.getMessage());
1036 }
1037 if (v4sid != v6sid) {
pier8b4ba992019-04-24 16:12:47 +02001038 result = rulePopulator.populateMplsRule(targetSw, destSw1, nextHops.get(destSw1),
Andreas Pantelopoulosff691b72018-03-12 16:30:20 -07001039 dest1RouterIpv6);
1040 if (!result) {
1041 return false;
1042 }
1043 }
1044 }
1045 }
1046
Saurav Das7bcbe702017-06-13 15:35:54 -07001047 // To save on ECMP groups
1048 // avoid MPLS rules in non-edge-devices to non-edge-devices
1049 // avoid MPLS transit rules in edge-devices
1050 // avoid loopback IP rules in edge-devices to non-edge-devices
1051 return true;
Saurav Dasc88d4662017-05-15 15:34:25 -07001052 }
1053
1054 /**
1055 * Processes a set a route-path changes by editing hash groups.
1056 *
1057 * @param routeChanges a set of route-path changes, where each route-path is
1058 * a list with its first element the src-switch of the path
1059 * and the second element the dst-switch of the path.
1060 * @param linkOrSwitchFailed true if the route changes are for a failed
1061 * switch or linkDown event
1062 * @param failedSwitch the switchId if the route changes are for a failed switch,
1063 * otherwise null
1064 */
1065 private void processHashGroupChange(Set<ArrayList<DeviceId>> routeChanges,
1066 boolean linkOrSwitchFailed,
1067 DeviceId failedSwitch) {
Saurav Das9df5b7c2017-08-14 16:44:43 -07001068 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
1069 // first, ensure each routeChanges entry has two elements
Saurav Dasc88d4662017-05-15 15:34:25 -07001070 for (ArrayList<DeviceId> route : routeChanges) {
Saurav Das9df5b7c2017-08-14 16:44:43 -07001071 if (route.size() == 1) {
1072 // route-path changes are from everyone else to this switch
1073 DeviceId dstSw = route.get(0);
1074 srManager.deviceService.getAvailableDevices().forEach(sw -> {
1075 if (!sw.id().equals(dstSw)) {
1076 changedRoutes.add(Lists.newArrayList(sw.id(), dstSw));
1077 }
1078 });
1079 } else {
1080 changedRoutes.add(route);
Saurav Dasc88d4662017-05-15 15:34:25 -07001081 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001082 }
Saurav Dasc568c342018-01-25 09:49:01 -08001083 boolean someFailed = false;
1084 Set<DeviceId> updatedDevices = Sets.newHashSet();
Saurav Das9df5b7c2017-08-14 16:44:43 -07001085 for (ArrayList<DeviceId> route : changedRoutes) {
1086 DeviceId targetSw = route.get(0);
1087 DeviceId dstSw = route.get(1);
Saurav Dasc88d4662017-05-15 15:34:25 -07001088 if (linkOrSwitchFailed) {
Saurav Das9df5b7c2017-08-14 16:44:43 -07001089 boolean success = fixHashGroupsForRoute(route, true);
Saurav Dasc88d4662017-05-15 15:34:25 -07001090 // it's possible that we cannot fix hash groups for a route
1091 // if the target switch has failed. Nevertheless the ecmp graph
1092 // for the impacted switch must still be updated.
Saurav Das9df5b7c2017-08-14 16:44:43 -07001093 if (!success && failedSwitch != null && targetSw.equals(failedSwitch)) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001094 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
1095 currentEcmpSpgMap.remove(targetSw);
Saurav Das9df5b7c2017-08-14 16:44:43 -07001096 log.debug("Updating ECMPspg for dst:{} removing failed switch "
Saurav Dasc88d4662017-05-15 15:34:25 -07001097 + "target:{}", dstSw, targetSw);
Saurav Dasc568c342018-01-25 09:49:01 -08001098 updatedDevices.add(targetSw);
1099 updatedDevices.add(dstSw);
Saurav Das9df5b7c2017-08-14 16:44:43 -07001100 continue;
Saurav Dasc88d4662017-05-15 15:34:25 -07001101 }
1102 //linkfailed - update both sides
Saurav Dasc88d4662017-05-15 15:34:25 -07001103 if (success) {
1104 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
Saurav Das9df5b7c2017-08-14 16:44:43 -07001105 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
Saurav Dasc568c342018-01-25 09:49:01 -08001106 log.debug("Updating ECMPspg for dst:{} and target:{} for linkdown"
1107 + " or switchdown", dstSw, targetSw);
1108 updatedDevices.add(targetSw);
1109 updatedDevices.add(dstSw);
1110 } else {
1111 someFailed = true;
Saurav Das9df5b7c2017-08-14 16:44:43 -07001112 }
1113 } else {
1114 //linkup of seen before link
1115 boolean success = fixHashGroupsForRoute(route, false);
1116 if (success) {
1117 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
1118 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
1119 log.debug("Updating ECMPspg for target:{} and dst:{} for linkup",
Saurav Dasc88d4662017-05-15 15:34:25 -07001120 targetSw, dstSw);
Saurav Dasc568c342018-01-25 09:49:01 -08001121 updatedDevices.add(targetSw);
1122 updatedDevices.add(dstSw);
1123 } else {
1124 someFailed = true;
Saurav Dasc88d4662017-05-15 15:34:25 -07001125 }
1126 }
1127 }
Saurav Dasc568c342018-01-25 09:49:01 -08001128 if (!someFailed) {
1129 // here is where we update all devices not touched by this instance
1130 updatedEcmpSpgMap.keySet().stream()
1131 .filter(devId -> !updatedDevices.contains(devId))
1132 .forEach(devId -> {
1133 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
1134 log.debug("Updating ECMPspg for remaining dev:{}", devId);
1135 });
1136 }
Saurav Dasc88d4662017-05-15 15:34:25 -07001137 }
1138
1139 /**
1140 * Edits hash groups in the src-switch (targetSw) of a route-path by
1141 * calling the groupHandler to either add or remove buckets in an existing
1142 * hash group.
1143 *
1144 * @param route a single list representing a route-path where the first element
1145 * is the src-switch (targetSw) of the route-path and the
1146 * second element is the dst-switch
1147 * @param revoke true if buckets in the hash-groups need to be removed;
1148 * false if buckets in the hash-groups need to be added
1149 * @return true if the hash group editing is successful
1150 */
1151 private boolean fixHashGroupsForRoute(ArrayList<DeviceId> route,
1152 boolean revoke) {
1153 DeviceId targetSw = route.get(0);
1154 if (route.size() < 2) {
1155 log.warn("Cannot fixHashGroupsForRoute - no dstSw in route {}", route);
1156 return false;
1157 }
1158 DeviceId destSw = route.get(1);
Saurav Das9df5b7c2017-08-14 16:44:43 -07001159 log.debug("* processing fixHashGroupsForRoute: Target {} -> Dest {}",
Saurav Dasc88d4662017-05-15 15:34:25 -07001160 targetSw, destSw);
Saurav Dasc88d4662017-05-15 15:34:25 -07001161 // figure out the new next hops at the targetSw towards the destSw
Saurav Das9df5b7c2017-08-14 16:44:43 -07001162 Set<DeviceId> nextHops = getNextHops(targetSw, destSw);
Saurav Dasc88d4662017-05-15 15:34:25 -07001163 // call group handler to change hash group at targetSw
1164 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
1165 if (grpHandler == null) {
1166 log.warn("Cannot find grouphandler for dev:{} .. aborting"
1167 + " {} hash group buckets for route:{} ", targetSw,
1168 (revoke) ? "revoke" : "repopulate", route);
1169 return false;
1170 }
Saurav Dasf1027d42018-06-11 17:02:31 -07001171 log.debug("{} hash-groups buckets For Route {} -> {} to new next-hops {}",
Saurav Dasc88d4662017-05-15 15:34:25 -07001172 (revoke) ? "revoke" : "repopulating",
1173 targetSw, destSw, nextHops);
1174 return (revoke) ? grpHandler.fixHashGroups(targetSw, nextHops,
1175 destSw, true)
1176 : grpHandler.fixHashGroups(targetSw, nextHops,
1177 destSw, false);
1178 }
1179
1180 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001181 * Start the flow rule population process if it was never started. The
1182 * process finishes successfully when all flow rules are set and stops with
1183 * ABORTED status when any groups required for flows is not set yet.
Saurav Dasc88d4662017-05-15 15:34:25 -07001184 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001185 public void startPopulationProcess() {
1186 statusLock.lock();
1187 try {
1188 if (populationStatus == Status.IDLE
1189 || populationStatus == Status.SUCCEEDED
1190 || populationStatus == Status.ABORTED) {
1191 populateAllRoutingRules();
sangho45b009c2015-05-07 13:30:57 -07001192 } else {
Saurav Das7bcbe702017-06-13 15:35:54 -07001193 log.warn("Not initiating startPopulationProcess as populationStatus is {}",
1194 populationStatus);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001195 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001196 } finally {
1197 statusLock.unlock();
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001198 }
sangho20eff1d2015-04-13 15:15:58 -07001199 }
1200
Saurav Dasb5c236e2016-06-07 10:08:06 -07001201 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001202 * Revoke rules of given subnet in all edge switches.
1203 *
1204 * @param subnets subnet being removed
1205 * @return true if succeed
1206 */
1207 protected boolean revokeSubnet(Set<IpPrefix> subnets) {
pier8b4ba992019-04-24 16:12:47 +02001208 DeviceId targetSw;
1209 List<Future<Boolean>> futures = Lists.newArrayList();
1210 for (Device sw : srManager.deviceService.getAvailableDevices()) {
1211 targetSw = sw.id();
1212 if (shouldProgram(targetSw)) {
1213 futures.add(routePopulators.submit(new RevokeSubnet(targetSw, subnets)));
1214 } else {
1215 futures.add(CompletableFuture.completedFuture(true));
1216 }
1217 }
1218 // check the execution of each job
1219 return checkJobs(futures);
1220 }
1221
1222 private final class RevokeSubnet implements PickyCallable<Boolean> {
1223 private DeviceId targetSw;
1224 private Set<IpPrefix> subnets;
1225
1226 /**
1227 * Builds a RevokeSubnet task, which provides a result.
1228 *
1229 * @param subnets a set of prefixes
1230 * @param targetSw target switch
1231 */
1232 RevokeSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
1233 this.targetSw = targetSw;
1234 this.subnets = subnets;
1235 }
1236
1237 @Override
1238 public Boolean call() throws Exception {
1239 return srManager.routingRulePopulator.revokeIpRuleForSubnet(targetSw, subnets);
1240 }
1241
1242 @Override
1243 public int hint() {
1244 return targetSw.hashCode();
Saurav Das7bcbe702017-06-13 15:35:54 -07001245 }
1246 }
1247
1248 /**
Charles Chan2fde6d42017-08-23 14:46:43 -07001249 * Populates IP rules for a route that has direct connection to the switch
1250 * if the current instance is the master of the switch.
1251 *
1252 * @param deviceId device ID of the device that next hop attaches to
1253 * @param prefix IP prefix of the route
1254 * @param hostMac MAC address of the next hop
1255 * @param hostVlanId Vlan ID of the nexthop
1256 * @param outPort port where the next hop attaches to
Ruchi Sahota5d800282019-01-28 01:08:18 +00001257 * @param directHost host is of type direct or indirect
Charles Chan2fde6d42017-08-23 14:46:43 -07001258 */
1259 void populateRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota5d800282019-01-28 01:08:18 +00001260 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Charles Chan2ff1bac2018-03-29 16:03:41 -07001261 if (shouldProgram(deviceId)) {
Ruchi Sahota5d800282019-01-28 01:08:18 +00001262 srManager.routingRulePopulator.populateRoute(deviceId, prefix, hostMac, hostVlanId, outPort, directHost);
Charles Chan2fde6d42017-08-23 14:46:43 -07001263 }
1264 }
1265
1266 /**
1267 * Removes IP rules for a route when the next hop is gone.
1268 * if the current instance is the master of the switch.
1269 *
1270 * @param deviceId device ID of the device that next hop attaches to
1271 * @param prefix IP prefix of the route
1272 * @param hostMac MAC address of the next hop
1273 * @param hostVlanId Vlan ID of the nexthop
1274 * @param outPort port that next hop attaches to
Ruchi Sahota5d800282019-01-28 01:08:18 +00001275 * @param directHost host is of type direct or indirect
Charles Chan2fde6d42017-08-23 14:46:43 -07001276 */
1277 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota5d800282019-01-28 01:08:18 +00001278 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Charles Chan2ff1bac2018-03-29 16:03:41 -07001279 if (shouldProgram(deviceId)) {
Ruchi Sahota5d800282019-01-28 01:08:18 +00001280 srManager.routingRulePopulator.revokeRoute(deviceId, prefix, hostMac, hostVlanId, outPort, directHost);
Charles Chan2fde6d42017-08-23 14:46:43 -07001281 }
1282 }
1283
Charles Chan2ff1bac2018-03-29 16:03:41 -07001284 void populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
1285 if (shouldProgram(deviceId)) {
1286 srManager.routingRulePopulator.populateBridging(deviceId, port, mac, vlanId);
1287 }
1288 }
1289
1290 void revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
1291 if (shouldProgram(deviceId)) {
1292 srManager.routingRulePopulator.revokeBridging(deviceId, port, mac, vlanId);
1293 }
1294 }
1295
1296 void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
1297 VlanId vlanId, boolean popVlan, boolean install) {
1298 if (shouldProgram(deviceId)) {
1299 srManager.routingRulePopulator.updateBridging(deviceId, portNum, hostMac, vlanId, popVlan, install);
1300 }
1301 }
1302
1303 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1304 VlanId vlanId, boolean popVlan, boolean install) {
1305 if (shouldProgram(deviceId)) {
1306 srManager.routingRulePopulator.updateFwdObj(deviceId, portNumber, prefix, hostMac,
1307 vlanId, popVlan, install);
1308 }
1309 }
1310
Charles Chan2fde6d42017-08-23 14:46:43 -07001311 /**
Jonghwan Hyuna76bf032018-04-09 09:40:50 -07001312 * Populates IP rules for a route when the next hop is double-tagged.
1313 *
1314 * @param deviceId device ID that next hop attaches to
1315 * @param prefix IP prefix of the route
1316 * @param hostMac MAC address of the next hop
1317 * @param innerVlan Inner Vlan ID of the next hop
1318 * @param outerVlan Outer Vlan ID of the next hop
1319 * @param outerTpid Outer TPID of the next hop
1320 * @param outPort port that the next hop attaches to
1321 */
1322 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId innerVlan,
1323 VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1324 if (srManager.mastershipService.isLocalMaster(deviceId)) {
1325 VlanId dummyVlan = srManager.allocateDummyVlanId(
1326 new ConnectPoint(deviceId, outPort), prefix.address());
1327 if (!dummyVlan.equals(VlanId.NONE)) {
1328 srManager.routingRulePopulator.populateDoubleTaggedRoute(
1329 deviceId, prefix, hostMac, dummyVlan, innerVlan, outerVlan, outerTpid, outPort);
1330 srManager.routingRulePopulator.processDoubleTaggedFilter(
1331 deviceId, outPort, outerVlan, innerVlan, true);
1332 } else {
1333 log.error("Failed to allocate dummy VLAN ID for host {} at {}/{}",
1334 prefix.address(), deviceId, outPort);
1335 }
1336 }
1337 }
1338
1339 /**
1340 * Revokes IP rules for a route when the next hop is double-tagged.
1341 *
1342 * @param deviceId device ID that next hop attaches to
1343 * @param prefix IP prefix of the route
1344 * @param hostMac MAC address of the next hop
1345 * @param innerVlan Inner Vlan ID of the next hop
1346 * @param outerVlan Outer Vlan ID of the next hop
1347 * @param outerTpid Outer TPID of the next hop
1348 * @param outPort port that the next hop attaches to
1349 */
1350 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId innerVlan,
1351 VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1352 // Revoke route either if this node have the mastership (when device is available) or
1353 // if this node is the leader (even when device is unavailable)
1354 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1355 if (srManager.deviceService.isAvailable(deviceId)) {
1356 // Master node will revoke specified rule.
1357 log.debug("This node is not a master for {}, stop revoking route.", deviceId);
1358 return;
1359 }
1360
1361 // isLocalMaster will return false when the device is unavailable.
1362 // Verify if this node is the leader in that case.
1363 NodeId leader = srManager.leadershipService.runForLeadership(
1364 deviceId.toString()).leaderNodeId();
1365 if (!srManager.clusterService.getLocalNode().id().equals(leader)) {
1366 // Leader node will revoke specified rule.
1367 log.debug("This node is not a master for {}, stop revoking route.", deviceId);
1368 return;
1369 }
1370 }
1371
1372 VlanId dummyVlan = srManager.dummyVlanIdStore().get(new DummyVlanIdStoreKey(
1373 new ConnectPoint(deviceId, outPort), prefix.address()));
1374 if (dummyVlan == null) {
1375 log.error("Failed to get dummyVlanId for host {} at {}/{}.",
1376 prefix.address(), deviceId, outPort);
1377 } else {
1378 srManager.routingRulePopulator.revokeDoubleTaggedRoute(
1379 deviceId, prefix, hostMac, dummyVlan, innerVlan, outerVlan, outerTpid, outPort);
1380 srManager.routingRulePopulator.processDoubleTaggedFilter(
1381 deviceId, outPort, outerVlan, innerVlan, false);
1382 }
1383 }
1384
1385
1386 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001387 * Remove ECMP graph entry for the given device. Typically called when
1388 * device is no longer available.
1389 *
1390 * @param deviceId the device for which graphs need to be purged
1391 */
Charles Chana8487b02018-04-18 18:41:05 -07001392 void purgeEcmpGraph(DeviceId deviceId) {
Saurav Dasc568c342018-01-25 09:49:01 -08001393 statusLock.lock();
1394 try {
Saurav Dasc568c342018-01-25 09:49:01 -08001395 if (populationStatus == Status.STARTED) {
1396 log.warn("Previous rule population is not finished. Cannot"
1397 + " proceeed with purgeEcmpGraph for {}", deviceId);
1398 return;
1399 }
1400 log.debug("Updating ECMPspg for unavailable dev:{}", deviceId);
1401 currentEcmpSpgMap.remove(deviceId);
1402 if (updatedEcmpSpgMap != null) {
1403 updatedEcmpSpgMap.remove(deviceId);
1404 }
1405 } finally {
1406 statusLock.unlock();
Saurav Das7bcbe702017-06-13 15:35:54 -07001407 }
1408 }
1409
Saurav Dasc6dc1772018-04-21 17:19:48 -07001410 /**
1411 * Attempts a full reroute of route-paths if topology has changed relatively
1412 * close to a mastership change event. Does not do a reroute if mastership
1413 * change is due to reasons other than a ONOS cluster event - for example a
1414 * call to balance-masters, or a switch up/down event.
1415 *
1416 * @param devId the device identifier for which mastership has changed
1417 * @param me the mastership event
1418 */
1419 void checkFullRerouteForMasterChange(DeviceId devId, MastershipEvent me) {
1420 // give small delay to absorb mastership events that are caused by
1421 // device that has disconnected from cluster
Saurav Das60ca8d52018-04-23 18:42:12 -07001422 executorServiceMstChg.schedule(new MasterChange(devId, me),
1423 MASTER_CHANGE_DELAY, TimeUnit.MILLISECONDS);
Saurav Dasc6dc1772018-04-21 17:19:48 -07001424 }
1425
1426 protected final class MasterChange implements Runnable {
1427 private DeviceId devId;
1428 private MastershipEvent me;
1429 private static final long CLUSTER_EVENT_THRESHOLD = 4500; // ms
1430 private static final long DEVICE_EVENT_THRESHOLD = 2000; // ms
Saurav Das41b49a92018-04-27 18:42:30 -07001431 private static final long EDGE_PORT_EVENT_THRESHOLD = 10000; //ms
Saurav Dasf1027d42018-06-11 17:02:31 -07001432 private static final long FULL_REROUTE_THRESHOLD = 10000; // ms
Saurav Dasc6dc1772018-04-21 17:19:48 -07001433
1434 MasterChange(DeviceId devId, MastershipEvent me) {
1435 this.devId = devId;
1436 this.me = me;
1437 }
1438
1439 @Override
1440 public void run() {
1441 long lce = srManager.clusterListener.timeSinceLastClusterEvent();
1442 boolean clusterEvent = lce < CLUSTER_EVENT_THRESHOLD;
1443
1444 // ignore event for lost switch if cluster event hasn't happened -
1445 // device down event will handle it
1446 if ((me.roleInfo().master() == null
1447 || !srManager.deviceService.isAvailable(devId))
1448 && !clusterEvent) {
1449 log.debug("Full reroute not required for lost device: {}/{} "
1450 + "clusterEvent/timeSince: {}/{}",
1451 devId, me.roleInfo(), clusterEvent, lce);
1452 return;
1453 }
1454
1455 long update = srManager.deviceService.getLastUpdatedInstant(devId);
1456 long lde = Instant.now().toEpochMilli() - update;
1457 boolean deviceEvent = lde < DEVICE_EVENT_THRESHOLD;
1458
1459 // ignore event for recently connected switch if cluster event hasn't
1460 // happened - link up events will handle it
1461 if (srManager.deviceService.isAvailable(devId) && deviceEvent
1462 && !clusterEvent) {
1463 log.debug("Full reroute not required for recently available"
1464 + " device: {}/{} deviceEvent/timeSince: {}/{} "
1465 + "clusterEvent/timeSince: {}/{}",
1466 devId, me.roleInfo(), deviceEvent, lde, clusterEvent, lce);
1467 return;
1468 }
1469
Saurav Das41b49a92018-04-27 18:42:30 -07001470 long lepe = Instant.now().toEpochMilli()
1471 - srManager.lastEdgePortEvent.toEpochMilli();
1472 boolean edgePortEvent = lepe < EDGE_PORT_EVENT_THRESHOLD;
1473
Saurav Dasc6dc1772018-04-21 17:19:48 -07001474 // if it gets here, then mastership change is likely due to onos
1475 // instance failure, or network partition in onos cluster
1476 // normally a mastership change like this does not require re-programming
1477 // but if topology changes happen at the same time then we may miss events
1478 if (!isRoutingStable() && clusterEvent) {
Saurav Das41b49a92018-04-27 18:42:30 -07001479 log.warn("Mastership changed for dev: {}/{} while programming route-paths "
Saurav Dasc6dc1772018-04-21 17:19:48 -07001480 + "due to clusterEvent {} ms ago .. attempting full reroute",
1481 devId, me.roleInfo(), lce);
1482 if (srManager.mastershipService.isLocalMaster(devId)) {
1483 // old master could have died when populating filters
1484 populatePortAddressingRules(devId);
1485 }
Saurav Dasf1027d42018-06-11 17:02:31 -07001486 // old master could have died when creating groups
Saurav Dasc6dc1772018-04-21 17:19:48 -07001487 // XXX right now we have no fine-grained way to only make changes
Saurav Dasf1027d42018-06-11 17:02:31 -07001488 // for the route paths affected by this device. Thus we do a
1489 // full reroute after purging all hash groups. We also try to do
1490 // it only once, irrespective of the number of devices
1491 // that changed mastership when their master instance died.
1492 long lfrr = Instant.now().toEpochMilli() - lastFullReroute.toEpochMilli();
1493 boolean doFullReroute = lfrr > FULL_REROUTE_THRESHOLD;
1494 if (doFullReroute) {
1495 lastFullReroute = Instant.now();
1496 for (Device dev : srManager.deviceService.getDevices()) {
1497 if (shouldProgram(dev.id())) {
1498 srManager.purgeHashedNextObjectiveStore(dev.id());
1499 }
1500 }
1501 // give small delay to ensure entire store is purged
1502 executorServiceFRR.schedule(new FullRerouteAfterPurge(),
1503 PURGE_DELAY,
1504 TimeUnit.MILLISECONDS);
1505 } else {
1506 log.warn("Full reroute attempted {} ms ago .. skipping", lfrr);
1507 }
Saurav Das41b49a92018-04-27 18:42:30 -07001508
1509 } else if (edgePortEvent && clusterEvent) {
1510 log.warn("Mastership changed for dev: {}/{} due to clusterEvent {} ms ago "
1511 + "while edge-port event happened {} ms ago "
1512 + " .. reprogramming all edge-ports",
1513 devId, me.roleInfo(), lce, lepe);
1514 if (shouldProgram(devId)) {
1515 srManager.deviceService.getPorts(devId).stream()
1516 .filter(p -> srManager.interfaceService
1517 .isConfigured(new ConnectPoint(devId, p.number())))
1518 .forEach(p -> srManager.processPortUpdated(devId, p));
1519 }
1520
Saurav Dasc6dc1772018-04-21 17:19:48 -07001521 } else {
1522 log.debug("Stable route-paths .. full reroute not attempted for "
1523 + "mastership change {}/{} deviceEvent/timeSince: {}/{} "
1524 + "clusterEvent/timeSince: {}/{}", devId, me.roleInfo(),
1525 deviceEvent, lde, clusterEvent, lce);
1526 }
1527 }
1528 }
1529
Saurav Dasf1027d42018-06-11 17:02:31 -07001530 /**
1531 * Performs a full reroute of routing rules in all the switches. Assumes
1532 * caller has purged hash groups from the nextObjective store, otherwise
1533 * re-uses ones available in the store.
1534 */
1535 protected final class FullRerouteAfterPurge implements Runnable {
1536 @Override
1537 public void run() {
1538 populateAllRoutingRules();
1539 }
1540 }
1541
1542
Saurav Das7bcbe702017-06-13 15:35:54 -07001543 //////////////////////////////////////
1544 // Routing helper methods and classes
1545 //////////////////////////////////////
1546
1547 /**
Saurav Dasf1027d42018-06-11 17:02:31 -07001548 * Computes set of affected routes due to failed link. Assumes previous ecmp
1549 * shortest-path graph exists for a switch in order to compute affected
1550 * routes. If such a graph does not exist, the method returns null.
Saurav Dasb5c236e2016-06-07 10:08:06 -07001551 *
1552 * @param linkFail the failed link
1553 * @return the set of affected routes which may be empty if no routes were
Saurav Dasf1027d42018-06-11 17:02:31 -07001554 * affected
Saurav Dasb5c236e2016-06-07 10:08:06 -07001555 */
sangho20eff1d2015-04-13 15:15:58 -07001556 private Set<ArrayList<DeviceId>> computeDamagedRoutes(Link linkFail) {
sangho20eff1d2015-04-13 15:15:58 -07001557 Set<ArrayList<DeviceId>> routes = new HashSet<>();
1558
1559 for (Device sw : srManager.deviceService.getDevices()) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001560 log.debug("Computing the impacted routes for device {} due to link fail",
1561 sw.id());
Charles Chan2ff1bac2018-03-29 16:03:41 -07001562 if (!shouldProgram(sw.id())) {
Saurav Dasc6dc1772018-04-21 17:19:48 -07001563 lastProgrammed.remove(sw.id());
sangho20eff1d2015-04-13 15:15:58 -07001564 continue;
1565 }
Charles Chan2ff1bac2018-03-29 16:03:41 -07001566 for (DeviceId rootSw : deviceAndItsPair(sw.id())) {
Saurav Dasc6dc1772018-04-21 17:19:48 -07001567 // check for mastership change since last run
1568 if (!lastProgrammed.contains(sw.id())) {
Saurav Dasf1027d42018-06-11 17:02:31 -07001569 log.warn("New responsibility for this node to program dev:{}"
Saurav Dasc6dc1772018-04-21 17:19:48 -07001570 + " ... nuking current ECMPspg", sw.id());
1571 currentEcmpSpgMap.remove(sw.id());
1572 }
Saurav Dasf1027d42018-06-11 17:02:31 -07001573 lastProgrammed.add(sw.id());
1574
Saurav Das9df5b7c2017-08-14 16:44:43 -07001575 EcmpShortestPathGraph ecmpSpg = currentEcmpSpgMap.get(rootSw);
1576 if (ecmpSpg == null) {
Saurav Dasf1027d42018-06-11 17:02:31 -07001577 log.warn("No existing ECMP graph for switch {}. Assuming "
1578 + "all route-paths have changed towards it.", rootSw);
1579 for (DeviceId targetSw : srManager.deviceConfiguration.getRouters()) {
1580 if (targetSw.equals(rootSw)) {
1581 continue;
1582 }
1583 routes.add(Lists.newArrayList(targetSw, rootSw));
1584 log.debug("Impacted route:{}->{}", targetSw, rootSw);
1585 }
1586 continue;
Saurav Das9df5b7c2017-08-14 16:44:43 -07001587 }
Saurav Dasf1027d42018-06-11 17:02:31 -07001588
Saurav Das9df5b7c2017-08-14 16:44:43 -07001589 if (log.isDebugEnabled()) {
1590 log.debug("Root switch: {}", rootSw);
1591 log.debug(" Current/Existing SPG: {}", ecmpSpg);
1592 log.debug(" New/Updated SPG: {}", updatedEcmpSpgMap.get(rootSw));
1593 }
1594 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>>
1595 switchVia = ecmpSpg.getAllLearnedSwitchesAndVia();
1596 // figure out if the broken link affected any route-paths in this graph
1597 for (Integer itrIdx : switchVia.keySet()) {
1598 log.trace("Current/Exiting SPG Iterindex# {}", itrIdx);
1599 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1600 switchVia.get(itrIdx);
1601 for (DeviceId targetSw : swViaMap.keySet()) {
1602 log.trace("TargetSwitch {} --> RootSwitch {}",
1603 targetSw, rootSw);
Saurav Dasb5c236e2016-06-07 10:08:06 -07001604 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1605 log.trace(" Via:");
Pier Ventree0ae7a32016-11-23 09:57:42 -08001606 via.forEach(e -> log.trace(" {}", e));
Saurav Dasb5c236e2016-06-07 10:08:06 -07001607 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001608 Set<ArrayList<DeviceId>> subLinks =
1609 computeLinks(targetSw, rootSw, swViaMap);
1610 for (ArrayList<DeviceId> alink: subLinks) {
1611 if ((alink.get(0).equals(linkFail.src().deviceId()) &&
1612 alink.get(1).equals(linkFail.dst().deviceId()))
1613 ||
1614 (alink.get(0).equals(linkFail.dst().deviceId()) &&
1615 alink.get(1).equals(linkFail.src().deviceId()))) {
1616 log.debug("Impacted route:{}->{}", targetSw, rootSw);
1617 ArrayList<DeviceId> aRoute = new ArrayList<>();
1618 aRoute.add(targetSw); // switch with rules to populate
1619 aRoute.add(rootSw); // towards this destination
1620 routes.add(aRoute);
1621 break;
1622 }
sangho20eff1d2015-04-13 15:15:58 -07001623 }
1624 }
1625 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001626
sangho20eff1d2015-04-13 15:15:58 -07001627 }
sangho45b009c2015-05-07 13:30:57 -07001628
sangho20eff1d2015-04-13 15:15:58 -07001629 }
sangho20eff1d2015-04-13 15:15:58 -07001630 return routes;
1631 }
1632
Saurav Das4e3224f2016-11-29 14:27:25 -08001633 /**
1634 * Computes set of affected routes due to new links or failed switches.
1635 *
Saurav Das604ab3a2018-03-18 21:28:15 -07001636 * @param failedSwitch deviceId of failed switch if any
Saurav Das4e3224f2016-11-29 14:27:25 -08001637 * @return the set of affected routes which may be empty if no routes were
1638 * affected
1639 */
Saurav Dase0d4c872018-03-05 14:37:16 -08001640 private Set<ArrayList<DeviceId>> computeRouteChange(DeviceId failedSwitch) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001641 ImmutableSet.Builder<ArrayList<DeviceId>> changedRtBldr =
Saurav Das4e3224f2016-11-29 14:27:25 -08001642 ImmutableSet.builder();
sangho20eff1d2015-04-13 15:15:58 -07001643
1644 for (Device sw : srManager.deviceService.getDevices()) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001645 log.debug("Computing the impacted routes for device {}", sw.id());
Charles Chan2ff1bac2018-03-29 16:03:41 -07001646 if (!shouldProgram(sw.id())) {
Saurav Dasc6dc1772018-04-21 17:19:48 -07001647 lastProgrammed.remove(sw.id());
sangho20eff1d2015-04-13 15:15:58 -07001648 continue;
1649 }
Charles Chan2ff1bac2018-03-29 16:03:41 -07001650 for (DeviceId rootSw : deviceAndItsPair(sw.id())) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001651 if (log.isTraceEnabled()) {
1652 log.trace("Device links for dev: {}", rootSw);
1653 for (Link link: srManager.linkService.getDeviceLinks(rootSw)) {
1654 log.trace("{} -> {} ", link.src().deviceId(),
1655 link.dst().deviceId());
1656 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001657 }
Saurav Dasc6dc1772018-04-21 17:19:48 -07001658 // check for mastership change since last run
1659 if (!lastProgrammed.contains(sw.id())) {
Saurav Dasf1027d42018-06-11 17:02:31 -07001660 log.warn("New responsibility for this node to program dev:{}"
Saurav Dasc6dc1772018-04-21 17:19:48 -07001661 + " ... nuking current ECMPspg", sw.id());
1662 currentEcmpSpgMap.remove(sw.id());
1663 }
Saurav Dasf1027d42018-06-11 17:02:31 -07001664 lastProgrammed.add(sw.id());
Saurav Das7bcbe702017-06-13 15:35:54 -07001665 EcmpShortestPathGraph currEcmpSpg = currentEcmpSpgMap.get(rootSw);
1666 if (currEcmpSpg == null) {
1667 log.debug("No existing ECMP graph for device {}.. adding self as "
1668 + "changed route", rootSw);
1669 changedRtBldr.add(Lists.newArrayList(rootSw));
1670 continue;
1671 }
1672 EcmpShortestPathGraph newEcmpSpg = updatedEcmpSpgMap.get(rootSw);
Saurav Das5a356042018-04-06 20:16:01 -07001673 if (newEcmpSpg == null) {
1674 log.warn("Cannot find updated ECMP graph for dev:{}", rootSw);
1675 continue;
1676 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001677 if (log.isDebugEnabled()) {
1678 log.debug("Root switch: {}", rootSw);
1679 log.debug(" Current/Existing SPG: {}", currEcmpSpg);
1680 log.debug(" New/Updated SPG: {}", newEcmpSpg);
1681 }
1682 // first use the updated/new map to compare to current/existing map
1683 // as new links may have come up
1684 changedRtBldr.addAll(compareGraphs(newEcmpSpg, currEcmpSpg, rootSw));
1685 // then use the current/existing map to compare to updated/new map
1686 // as switch may have been removed
1687 changedRtBldr.addAll(compareGraphs(currEcmpSpg, newEcmpSpg, rootSw));
sangho45b009c2015-05-07 13:30:57 -07001688 }
Saurav Das4e3224f2016-11-29 14:27:25 -08001689 }
sangho20eff1d2015-04-13 15:15:58 -07001690
Saurav Dase0d4c872018-03-05 14:37:16 -08001691 // handle clearing state for a failed switch in case the switch does
1692 // not have a pair, or the pair is not available
1693 if (failedSwitch != null) {
Charles Chanba6c5752018-04-02 11:46:38 -07001694 Optional<DeviceId> pairDev = srManager.getPairDeviceId(failedSwitch);
1695 if (!pairDev.isPresent() || !srManager.deviceService.isAvailable(pairDev.get())) {
Saurav Dase0d4c872018-03-05 14:37:16 -08001696 log.debug("Proxy Route changes to downed Sw:{}", failedSwitch);
1697 srManager.deviceService.getDevices().forEach(dev -> {
1698 if (!dev.id().equals(failedSwitch) &&
1699 srManager.mastershipService.isLocalMaster(dev.id())) {
1700 log.debug(" : {}", dev.id());
1701 changedRtBldr.add(Lists.newArrayList(dev.id(), failedSwitch));
1702 }
1703 });
1704 }
1705 }
1706
Saurav Das7bcbe702017-06-13 15:35:54 -07001707 Set<ArrayList<DeviceId>> changedRoutes = changedRtBldr.build();
Saurav Das4e3224f2016-11-29 14:27:25 -08001708 for (ArrayList<DeviceId> route: changedRoutes) {
1709 log.debug("Route changes Target -> Root");
1710 if (route.size() == 1) {
1711 log.debug(" : all -> {}", route.get(0));
1712 } else {
1713 log.debug(" : {} -> {}", route.get(0), route.get(1));
1714 }
1715 }
1716 return changedRoutes;
1717 }
1718
1719 /**
1720 * For the root switch, searches all the target nodes reachable in the base
1721 * graph, and compares paths to the ones in the comp graph.
1722 *
1723 * @param base the graph that is indexed for all reachable target nodes
1724 * from the root node
1725 * @param comp the graph that the base graph is compared to
1726 * @param rootSw both ecmp graphs are calculated for the root node
1727 * @return all the routes that have changed in the base graph
1728 */
1729 private Set<ArrayList<DeviceId>> compareGraphs(EcmpShortestPathGraph base,
1730 EcmpShortestPathGraph comp,
1731 DeviceId rootSw) {
1732 ImmutableSet.Builder<ArrayList<DeviceId>> changedRoutesBuilder =
1733 ImmutableSet.builder();
1734 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> baseMap =
1735 base.getAllLearnedSwitchesAndVia();
1736 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> compMap =
1737 comp.getAllLearnedSwitchesAndVia();
1738 for (Integer itrIdx : baseMap.keySet()) {
1739 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> baseViaMap =
1740 baseMap.get(itrIdx);
1741 for (DeviceId targetSw : baseViaMap.keySet()) {
1742 ArrayList<ArrayList<DeviceId>> basePath = baseViaMap.get(targetSw);
1743 ArrayList<ArrayList<DeviceId>> compPath = getVia(compMap, targetSw);
1744 if ((compPath == null) || !basePath.equals(compPath)) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001745 log.trace("Impacted route:{} -> {}", targetSw, rootSw);
Saurav Das4e3224f2016-11-29 14:27:25 -08001746 ArrayList<DeviceId> route = new ArrayList<>();
Saurav Das7bcbe702017-06-13 15:35:54 -07001747 route.add(targetSw); // switch with rules to populate
1748 route.add(rootSw); // towards this destination
Saurav Das4e3224f2016-11-29 14:27:25 -08001749 changedRoutesBuilder.add(route);
sangho20eff1d2015-04-13 15:15:58 -07001750 }
1751 }
sangho45b009c2015-05-07 13:30:57 -07001752 }
Saurav Das4e3224f2016-11-29 14:27:25 -08001753 return changedRoutesBuilder.build();
sangho20eff1d2015-04-13 15:15:58 -07001754 }
1755
Saurav Das7bcbe702017-06-13 15:35:54 -07001756 /**
1757 * Returns the ECMP paths traversed to reach the target switch.
1758 *
1759 * @param switchVia a per-iteration view of the ECMP graph for a root switch
1760 * @param targetSw the switch to reach from the root switch
1761 * @return the nodes traversed on ECMP paths to the target switch
1762 */
sangho20eff1d2015-04-13 15:15:58 -07001763 private ArrayList<ArrayList<DeviceId>> getVia(HashMap<Integer, HashMap<DeviceId,
Saurav Das4e3224f2016-11-29 14:27:25 -08001764 ArrayList<ArrayList<DeviceId>>>> switchVia, DeviceId targetSw) {
sangho20eff1d2015-04-13 15:15:58 -07001765 for (Integer itrIdx : switchVia.keySet()) {
1766 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1767 switchVia.get(itrIdx);
Saurav Das4e3224f2016-11-29 14:27:25 -08001768 if (swViaMap.get(targetSw) == null) {
sangho20eff1d2015-04-13 15:15:58 -07001769 continue;
1770 } else {
Saurav Das4e3224f2016-11-29 14:27:25 -08001771 return swViaMap.get(targetSw);
sangho20eff1d2015-04-13 15:15:58 -07001772 }
1773 }
1774
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001775 return null;
sangho20eff1d2015-04-13 15:15:58 -07001776 }
1777
Saurav Das7bcbe702017-06-13 15:35:54 -07001778 /**
1779 * Utility method to break down a path from src to dst device into a collection
1780 * of links.
1781 *
1782 * @param src src device of the path
1783 * @param dst dst device of the path
1784 * @param viaMap path taken from src to dst device
1785 * @return collection of links in the path
1786 */
sangho20eff1d2015-04-13 15:15:58 -07001787 private Set<ArrayList<DeviceId>> computeLinks(DeviceId src,
1788 DeviceId dst,
1789 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> viaMap) {
1790 Set<ArrayList<DeviceId>> subLinks = Sets.newHashSet();
1791 for (ArrayList<DeviceId> via : viaMap.get(src)) {
1792 DeviceId linkSrc = src;
1793 DeviceId linkDst = dst;
1794 for (DeviceId viaDevice: via) {
1795 ArrayList<DeviceId> link = new ArrayList<>();
1796 linkDst = viaDevice;
1797 link.add(linkSrc);
1798 link.add(linkDst);
1799 subLinks.add(link);
1800 linkSrc = viaDevice;
1801 }
1802 ArrayList<DeviceId> link = new ArrayList<>();
1803 link.add(linkSrc);
1804 link.add(dst);
1805 subLinks.add(link);
1806 }
1807
1808 return subLinks;
1809 }
1810
Charles Chan93e71ba2016-04-29 14:38:22 -07001811 /**
Charles Chan2ff1bac2018-03-29 16:03:41 -07001812 * Determines whether this controller instance should program the
Saurav Das7bcbe702017-06-13 15:35:54 -07001813 * given {@code deviceId}, based on mastership and pairDeviceId if one exists.
Charles Chan2ff1bac2018-03-29 16:03:41 -07001814 * <p>
1815 * Once an instance is elected, it will be the only instance responsible for programming
1816 * both devices in the pair until it goes down.
Charles Chan93e71ba2016-04-29 14:38:22 -07001817 *
Saurav Das7bcbe702017-06-13 15:35:54 -07001818 * @param deviceId device identifier to consider for routing
Charles Chan2ff1bac2018-03-29 16:03:41 -07001819 * @return true if current instance should handle the routing for given device
Charles Chan93e71ba2016-04-29 14:38:22 -07001820 */
Charles Chan2ff1bac2018-03-29 16:03:41 -07001821 boolean shouldProgram(DeviceId deviceId) {
Charles Chana8487b02018-04-18 18:41:05 -07001822 Boolean cached = shouldProgramCache.get(deviceId);
1823 if (cached != null) {
Saurav Dasc6dc1772018-04-21 17:19:48 -07001824 log.debug("shouldProgram dev:{} cached:{}", deviceId, cached);
Charles Chana8487b02018-04-18 18:41:05 -07001825 return cached;
1826 }
1827
Charles Chan2ff1bac2018-03-29 16:03:41 -07001828 Optional<DeviceId> pairDeviceId = srManager.getPairDeviceId(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001829
Charles Chan2ff1bac2018-03-29 16:03:41 -07001830 NodeId currentNodeId = srManager.clusterService.getLocalNode().id();
1831 NodeId masterNodeId = srManager.mastershipService.getMasterFor(deviceId);
1832 Optional<NodeId> pairMasterNodeId = pairDeviceId.map(srManager.mastershipService::getMasterFor);
Saurav Dasf1027d42018-06-11 17:02:31 -07001833 log.debug("Evaluate shouldProgram {}/pair={}. currentNodeId={}, master={}, pairMaster={}",
Charles Chan2ff1bac2018-03-29 16:03:41 -07001834 deviceId, pairDeviceId, currentNodeId, masterNodeId, pairMasterNodeId);
1835
1836 // No pair device configured. Only handle when current instance is the master of the device
1837 if (!pairDeviceId.isPresent()) {
Saurav Dasf1027d42018-06-11 17:02:31 -07001838 log.debug("No pair device. currentNodeId={}, master={}", currentNodeId, masterNodeId);
Charles Chan2ff1bac2018-03-29 16:03:41 -07001839 return currentNodeId.equals(masterNodeId);
sanghob35a6192015-04-01 13:05:26 -07001840 }
Charles Chan2ff1bac2018-03-29 16:03:41 -07001841
1842 // Should not handle if current instance is not the master of either switch
1843 if (!currentNodeId.equals(masterNodeId) &&
1844 !(pairMasterNodeId.isPresent() && currentNodeId.equals(pairMasterNodeId.get()))) {
Saurav Dasf1027d42018-06-11 17:02:31 -07001845 log.debug("Current nodeId {} is neither the master of target device {} nor pair device {}",
Charles Chan2ff1bac2018-03-29 16:03:41 -07001846 currentNodeId, deviceId, pairDeviceId);
1847 return false;
1848 }
1849
1850 Set<DeviceId> key = Sets.newHashSet(deviceId, pairDeviceId.get());
1851
1852 NodeId king = shouldProgram.compute(key, ((k, v) -> {
1853 if (v == null) {
1854 // There is no value in the map. Elect a node
1855 return elect(Lists.newArrayList(masterNodeId, pairMasterNodeId.orElse(null)));
1856 } else {
1857 if (v.equals(masterNodeId) || v.equals(pairMasterNodeId.orElse(null))) {
1858 // Use the node in the map if it is still alive and is a master of any of the two switches
1859 return v;
1860 } else {
1861 // Previously elected node is no longer the master of either switch. Re-elect a node.
1862 return elect(Lists.newArrayList(masterNodeId, pairMasterNodeId.orElse(null)));
1863 }
1864 }
1865 }));
1866
1867 if (king != null) {
Saurav Dasf1027d42018-06-11 17:02:31 -07001868 log.debug("{} is king, should handle routing for {}/pair={}", king, deviceId, pairDeviceId);
Charles Chana8487b02018-04-18 18:41:05 -07001869 shouldProgramCache.put(deviceId, king.equals(currentNodeId));
Charles Chan2ff1bac2018-03-29 16:03:41 -07001870 return king.equals(currentNodeId);
1871 } else {
1872 log.error("Fail to elect a king for {}/pair={}. Abort.", deviceId, pairDeviceId);
Charles Chana8487b02018-04-18 18:41:05 -07001873 shouldProgramCache.remove(deviceId);
Charles Chan2ff1bac2018-03-29 16:03:41 -07001874 return false;
1875 }
1876 }
1877
1878 /**
1879 * Elects a node who should take responsibility of programming devices.
1880 * @param nodeIds list of candidate node ID
1881 *
1882 * @return NodeId of the node that gets elected, or null if none of the node can be elected
1883 */
1884 private NodeId elect(List<NodeId> nodeIds) {
1885 // Remove all null elements. This could happen when some device has no master
1886 nodeIds.removeAll(Collections.singleton(null));
1887 nodeIds.sort(null);
1888 return nodeIds.size() == 0 ? null : nodeIds.get(0);
1889 }
1890
Charles Chana8487b02018-04-18 18:41:05 -07001891 void invalidateShouldProgramCache(DeviceId deviceId) {
1892 shouldProgramCache.remove(deviceId);
1893 }
1894
Charles Chan2ff1bac2018-03-29 16:03:41 -07001895 /**
1896 * Returns a set of device ID, containing given device and its pair device if exist.
1897 *
1898 * @param deviceId Device ID
1899 * @return a set of device ID, containing given device and its pair device if exist.
1900 */
1901 private Set<DeviceId> deviceAndItsPair(DeviceId deviceId) {
1902 Set<DeviceId> ret = Sets.newHashSet(deviceId);
1903 srManager.getPairDeviceId(deviceId).ifPresent(ret::add);
1904 return ret;
sanghob35a6192015-04-01 13:05:26 -07001905 }
1906
Charles Chan93e71ba2016-04-29 14:38:22 -07001907 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001908 * Returns the set of deviceIds which are the next hops from the targetSw
1909 * to the dstSw according to the latest ECMP spg.
1910 *
1911 * @param targetSw the switch for which the next-hops are desired
1912 * @param dstSw the switch to which the next-hops lead to from the targetSw
1913 * @return set of next hop deviceIds, could be empty if no next hops are found
1914 */
1915 private Set<DeviceId> getNextHops(DeviceId targetSw, DeviceId dstSw) {
1916 boolean targetIsEdge = false;
1917 try {
1918 targetIsEdge = srManager.deviceConfiguration.isEdgeDevice(targetSw);
1919 } catch (DeviceConfigNotFoundException e) {
1920 log.warn(e.getMessage() + "Cannot determine if targetIsEdge {}.. "
1921 + "continuing to getNextHops", targetSw);
1922 }
1923
1924 EcmpShortestPathGraph ecmpSpg = updatedEcmpSpgMap.get(dstSw);
1925 if (ecmpSpg == null) {
1926 log.debug("No ecmpSpg found for dstSw: {}", dstSw);
1927 return ImmutableSet.of();
1928 }
1929 HashMap<Integer,
1930 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> switchVia =
1931 ecmpSpg.getAllLearnedSwitchesAndVia();
1932 for (Integer itrIdx : switchVia.keySet()) {
1933 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1934 switchVia.get(itrIdx);
1935 for (DeviceId target : swViaMap.keySet()) {
1936 if (!target.equals(targetSw)) {
1937 continue;
1938 }
Saurav Das60ca8d52018-04-23 18:42:12 -07001939 // optimization for spines to not use leaves to get
1940 // to a spine or other leaves. Also leaves should not use other
1941 // leaves to get to the destination
1942 if ((!targetIsEdge && itrIdx > 1) || targetIsEdge) {
Saurav Dasa4020382018-02-14 14:14:54 -08001943 boolean pathdevIsEdge = false;
1944 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
Saurav Das60ca8d52018-04-23 18:42:12 -07001945 log.debug("Evaluating next-hop in path: {}", via);
Saurav Dasa4020382018-02-14 14:14:54 -08001946 for (DeviceId pathdev : via) {
1947 try {
1948 pathdevIsEdge = srManager.deviceConfiguration
1949 .isEdgeDevice(pathdev);
1950 } catch (DeviceConfigNotFoundException e) {
1951 log.warn(e.getMessage());
1952 }
1953 if (pathdevIsEdge) {
Saurav Dasf1027d42018-06-11 17:02:31 -07001954 log.debug("Avoiding {} hop path for targetSw:{}"
Saurav Dasa4020382018-02-14 14:14:54 -08001955 + " --> dstSw:{} which goes through an edge"
1956 + " device {} in path {}", itrIdx,
1957 targetSw, dstSw, pathdev, via);
1958 return ImmutableSet.of();
1959 }
1960 }
1961 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001962 }
1963 Set<DeviceId> nextHops = new HashSet<>();
1964 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1965 if (via.isEmpty()) {
1966 // the dstSw is the next-hop from the targetSw
1967 nextHops.add(dstSw);
1968 } else {
1969 // first elem is next-hop in each ECMP path
1970 nextHops.add(via.get(0));
1971 }
1972 }
Saurav Das60ca8d52018-04-23 18:42:12 -07001973 log.debug("target {} --> dst: {} has next-hops:{}", targetSw,
1974 dstSw, nextHops);
Saurav Das7bcbe702017-06-13 15:35:54 -07001975 return nextHops;
1976 }
1977 }
Saurav Das60ca8d52018-04-23 18:42:12 -07001978 log.debug("No next hops found for target:{} --> dst: {}", targetSw, dstSw);
Saurav Das7bcbe702017-06-13 15:35:54 -07001979 return ImmutableSet.of(); //no next-hops found
1980 }
1981
Saurav Das7bcbe702017-06-13 15:35:54 -07001982 //////////////////////////////////////
1983 // Filtering rule creation
1984 //////////////////////////////////////
1985
1986 /**
Saurav Das018605f2017-02-18 14:05:44 -08001987 * Populates filtering rules for port, and punting rules
1988 * for gateway IPs, loopback IPs and arp/ndp traffic.
1989 * Should only be called by the master instance for this device/port.
sanghob35a6192015-04-01 13:05:26 -07001990 *
1991 * @param deviceId Switch ID to set the rules
1992 */
Charles Chana8487b02018-04-18 18:41:05 -07001993 void populatePortAddressingRules(DeviceId deviceId) {
Saurav Das59232cf2016-04-27 18:35:50 -07001994 // Although device is added, sometimes device store does not have the
1995 // ports for this device yet. It results in missing filtering rules in the
1996 // switch. We will attempt it a few times. If it still does not work,
1997 // user can manually repopulate using CLI command sr-reroute-network
Charles Chanf6ec1532017-02-08 16:10:40 -08001998 PortFilterInfo firstRun = rulePopulator.populateVlanMacFilters(deviceId);
Saurav Dasd2fded02016-12-02 15:43:47 -08001999 if (firstRun == null) {
2000 firstRun = new PortFilterInfo(0, 0, 0);
Saurav Das59232cf2016-04-27 18:35:50 -07002001 }
Saurav Dasd2fded02016-12-02 15:43:47 -08002002 executorService.schedule(new RetryFilters(deviceId, firstRun),
2003 RETRY_INTERVAL_MS, TimeUnit.MILLISECONDS);
sanghob35a6192015-04-01 13:05:26 -07002004 }
2005
2006 /**
Saurav Dasd2fded02016-12-02 15:43:47 -08002007 * RetryFilters populates filtering objectives for a device and keeps retrying
2008 * till the number of ports filtered are constant for a predefined number
2009 * of attempts.
2010 */
2011 protected final class RetryFilters implements Runnable {
2012 int constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS;
2013 DeviceId devId;
2014 int counter;
2015 PortFilterInfo prevRun;
2016
2017 private RetryFilters(DeviceId deviceId, PortFilterInfo previousRun) {
Saurav Das59232cf2016-04-27 18:35:50 -07002018 devId = deviceId;
Saurav Dasd2fded02016-12-02 15:43:47 -08002019 prevRun = previousRun;
2020 counter = 0;
Saurav Das59232cf2016-04-27 18:35:50 -07002021 }
2022
2023 @Override
2024 public void run() {
Charles Chan7f9737b2017-06-22 14:27:17 -07002025 log.debug("RETRY FILTER ATTEMPT {} ** dev:{}", ++counter, devId);
Charles Chanf6ec1532017-02-08 16:10:40 -08002026 PortFilterInfo thisRun = rulePopulator.populateVlanMacFilters(devId);
Saurav Dasd2fded02016-12-02 15:43:47 -08002027 boolean sameResult = prevRun.equals(thisRun);
2028 log.debug("dev:{} prevRun:{} thisRun:{} sameResult:{}", devId, prevRun,
2029 thisRun, sameResult);
Ray Milkeyc6c9b172018-02-26 09:36:31 -08002030 if (thisRun == null || !sameResult || (--constantAttempts > 0)) {
Saurav Das018605f2017-02-18 14:05:44 -08002031 // exponentially increasing intervals for retries
2032 executorService.schedule(this,
2033 RETRY_INTERVAL_MS * (int) Math.pow(counter, RETRY_INTERVAL_SCALE),
2034 TimeUnit.MILLISECONDS);
Saurav Dasd2fded02016-12-02 15:43:47 -08002035 if (!sameResult) {
2036 constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS; //reset
2037 }
Saurav Das59232cf2016-04-27 18:35:50 -07002038 }
Saurav Dasd2fded02016-12-02 15:43:47 -08002039 prevRun = (thisRun == null) ? prevRun : thisRun;
Saurav Das59232cf2016-04-27 18:35:50 -07002040 }
Saurav Das59232cf2016-04-27 18:35:50 -07002041 }
pier8b4ba992019-04-24 16:12:47 +02002042
2043 // Check jobs completion. It returns false if one of the job fails
2044 // and cancel the remaining
2045 private boolean checkJobs(List<Future<Boolean>> futures) {
2046 boolean completed = true;
2047 for (Future<Boolean> future : futures) {
2048 try {
2049 if (completed) {
2050 if (!future.get()) {
2051 completed = false;
2052 }
2053 } else {
2054 future.cancel(true);
2055 }
2056 } catch (InterruptedException | ExecutionException e) {
2057 completed = false;
2058 }
2059 }
2060 return completed;
2061 }
sanghob35a6192015-04-01 13:05:26 -07002062}