blob: 2eb52f36d725df6883df4406211cbcf8edb72ce3 [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Saurav Das62ae6792017-05-15 15:34:25 -070018import com.google.common.collect.ImmutableMap;
19import com.google.common.collect.ImmutableMap.Builder;
Charles Chanc22cef32016-04-29 14:38:22 -070020import com.google.common.collect.ImmutableSet;
Saurav Das1b391d52016-11-29 14:27:25 -080021import com.google.common.collect.Lists;
sanghofb7c7292015-04-13 15:15:58 -070022import com.google.common.collect.Maps;
23import com.google.common.collect.Sets;
Saurav Dasfbe74572017-08-03 18:30:35 -070024
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -070025import org.onlab.packet.EthType;
Charles Chan19b70032019-04-17 14:20:26 -070026import com.google.common.collect.Streams;
sangho9b169e32015-04-14 16:27:13 -070027import org.onlab.packet.Ip4Address;
Pier Ventreadb4ae62016-11-23 09:57:42 -080028import org.onlab.packet.Ip6Address;
sangho80f11cb2015-04-01 13:05:26 -070029import org.onlab.packet.IpPrefix;
Charles Chan910be6a2017-08-23 14:46:43 -070030import org.onlab.packet.MacAddress;
31import org.onlab.packet.VlanId;
piera9941192019-04-24 16:12:47 +020032import org.onlab.util.PredictableExecutor;
33import org.onlab.util.PredictableExecutor.PickyCallable;
Saurav Das261c3002017-06-13 15:35:54 -070034import org.onosproject.cluster.NodeId;
Saurav Das00e553b2018-04-21 17:19:48 -070035import org.onosproject.mastership.MastershipEvent;
Charles Chanc22cef32016-04-29 14:38:22 -070036import org.onosproject.net.ConnectPoint;
sangho80f11cb2015-04-01 13:05:26 -070037import org.onosproject.net.Device;
38import org.onosproject.net.DeviceId;
sanghofb7c7292015-04-13 15:15:58 -070039import org.onosproject.net.Link;
Charles Chan910be6a2017-08-23 14:46:43 -070040import org.onosproject.net.PortNumber;
Charles Chan319d1a22015-11-03 10:42:14 -080041import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
42import org.onosproject.segmentrouting.config.DeviceConfiguration;
Saurav Das62ae6792017-05-15 15:34:25 -070043import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
Charles Chand66d6712018-03-29 16:03:41 -070044import org.onosproject.store.serializers.KryoNamespaces;
45import org.onosproject.store.service.Serializer;
sangho80f11cb2015-04-01 13:05:26 -070046import org.slf4j.Logger;
47import org.slf4j.LoggerFactory;
48
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -070049import java.time.Instant;
sangho80f11cb2015-04-01 13:05:26 -070050import java.util.ArrayList;
Charles Chand66d6712018-03-29 16:03:41 -070051import java.util.Collections;
sangho80f11cb2015-04-01 13:05:26 -070052import java.util.HashMap;
53import java.util.HashSet;
Saurav Das261c3002017-06-13 15:35:54 -070054import java.util.Iterator;
Charles Chand66d6712018-03-29 16:03:41 -070055import java.util.List;
Saurav Das261c3002017-06-13 15:35:54 -070056import java.util.Map;
Saurav Dasd1872b02016-12-02 15:43:47 -080057import java.util.Objects;
Charles Chan6dbcd252018-04-02 11:46:38 -070058import java.util.Optional;
sangho80f11cb2015-04-01 13:05:26 -070059import java.util.Set;
piera9941192019-04-24 16:12:47 +020060import java.util.concurrent.CompletableFuture;
61import java.util.concurrent.ExecutionException;
62import java.util.concurrent.ExecutorService;
63import java.util.concurrent.Future;
Saurav Das07c74602016-04-27 18:35:50 -070064import java.util.concurrent.ScheduledExecutorService;
65import java.util.concurrent.TimeUnit;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +090066import java.util.concurrent.locks.Lock;
67import java.util.concurrent.locks.ReentrantLock;
Charles Chan19b70032019-04-17 14:20:26 -070068import java.util.stream.Collectors;
Saurav Dasdc7f2752018-03-18 21:28:15 -070069import java.util.stream.Stream;
70
Pier Ventreadb4ae62016-11-23 09:57:42 -080071import static com.google.common.base.Preconditions.checkNotNull;
72import static java.util.concurrent.Executors.newScheduledThreadPool;
73import static org.onlab.util.Tools.groupedThreads;
sangho80f11cb2015-04-01 13:05:26 -070074
Charles Chanb7f75ac2016-01-11 18:28:54 -080075/**
76 * Default routing handler that is responsible for route computing and
77 * routing rule population.
78 */
sangho80f11cb2015-04-01 13:05:26 -070079public class DefaultRoutingHandler {
Saurav Dasf9332192017-02-18 14:05:44 -080080 private static final int MAX_CONSTANT_RETRY_ATTEMPTS = 5;
Ray Milkey092e9e22018-02-01 13:49:47 -080081 private static final long RETRY_INTERVAL_MS = 250L;
Saurav Dasf9332192017-02-18 14:05:44 -080082 private static final int RETRY_INTERVAL_SCALE = 1;
Saurav Dasfbe74572017-08-03 18:30:35 -070083 private static final long STABLITY_THRESHOLD = 10; //secs
Saurav Das00e553b2018-04-21 17:19:48 -070084 private static final long MASTER_CHANGE_DELAY = 1000; // ms
Saurav Das68e1b6a2018-06-11 17:02:31 -070085 private static final long PURGE_DELAY = 1000; // ms
Charles Chanc22cef32016-04-29 14:38:22 -070086 private static Logger log = LoggerFactory.getLogger(DefaultRoutingHandler.class);
sangho80f11cb2015-04-01 13:05:26 -070087
88 private SegmentRoutingManager srManager;
89 private RoutingRulePopulator rulePopulator;
Shashikanth VH0637b162015-12-11 01:32:44 +053090 private HashMap<DeviceId, EcmpShortestPathGraph> currentEcmpSpgMap;
91 private HashMap<DeviceId, EcmpShortestPathGraph> updatedEcmpSpgMap;
sangho9b169e32015-04-14 16:27:13 -070092 private DeviceConfiguration config;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +090093 private final Lock statusLock = new ReentrantLock();
94 private volatile Status populationStatus;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -070095 private ScheduledExecutorService executorService
Saurav Dasd1872b02016-12-02 15:43:47 -080096 = newScheduledThreadPool(1, groupedThreads("retryftr", "retry-%d", log));
Saurav Das49368392018-04-23 18:42:12 -070097 private ScheduledExecutorService executorServiceMstChg
98 = newScheduledThreadPool(1, groupedThreads("masterChg", "mstch-%d", log));
Saurav Das68e1b6a2018-06-11 17:02:31 -070099 private ScheduledExecutorService executorServiceFRR
100 = newScheduledThreadPool(1, groupedThreads("fullRR", "fullRR-%d", log));
piera9941192019-04-24 16:12:47 +0200101 // Route populators - 0 will leverage available processors
102 private static final int DEFAULT_THREADS = 0;
103 private ExecutorService routePopulators;
Saurav Das49368392018-04-23 18:42:12 -0700104
Saurav Das00e553b2018-04-21 17:19:48 -0700105 private Instant lastRoutingChange = Instant.EPOCH;
Saurav Das68e1b6a2018-06-11 17:02:31 -0700106 private Instant lastFullReroute = Instant.EPOCH;
sangho80f11cb2015-04-01 13:05:26 -0700107
Saurav Das00e553b2018-04-21 17:19:48 -0700108 // Distributed store to keep track of ONOS instance that should program the
109 // device pair. There should be only one instance (the king) that programs the same pair.
Charles Chand66d6712018-03-29 16:03:41 -0700110 Map<Set<DeviceId>, NodeId> shouldProgram;
Charles Chanfbcb8812018-04-18 18:41:05 -0700111 Map<DeviceId, Boolean> shouldProgramCache;
Charles Chand66d6712018-03-29 16:03:41 -0700112
Saurav Das00e553b2018-04-21 17:19:48 -0700113 // Local store to keep track of all devices that this instance was responsible
114 // for programming in the last run. Helps to determine if mastership changed
115 // during a run - only relevant for programming as a result of topo change.
116 Set<DeviceId> lastProgrammed;
117
sangho80f11cb2015-04-01 13:05:26 -0700118 /**
119 * Represents the default routing population status.
120 */
121 public enum Status {
122 // population process is not started yet.
123 IDLE,
sangho80f11cb2015-04-01 13:05:26 -0700124 // population process started.
125 STARTED,
piera9941192019-04-24 16:12:47 +0200126 // population process was aborted due to errors, mostly for groups not found.
sangho80f11cb2015-04-01 13:05:26 -0700127 ABORTED,
sangho80f11cb2015-04-01 13:05:26 -0700128 // population process was finished successfully.
129 SUCCEEDED
130 }
131
132 /**
133 * Creates a DefaultRoutingHandler object.
134 *
135 * @param srManager SegmentRoutingManager object
136 */
Charles Chand66d6712018-03-29 16:03:41 -0700137 DefaultRoutingHandler(SegmentRoutingManager srManager) {
Charles Chanfbcb8812018-04-18 18:41:05 -0700138 this.shouldProgram = srManager.storageService.<Set<DeviceId>, NodeId>consistentMapBuilder()
139 .withName("sr-should-program")
140 .withSerializer(Serializer.using(KryoNamespaces.API))
141 .withRelaxedReadConsistency()
142 .build().asJavaMap();
143 this.shouldProgramCache = Maps.newConcurrentMap();
144 update(srManager);
piera9941192019-04-24 16:12:47 +0200145 this.routePopulators = new PredictableExecutor(DEFAULT_THREADS,
146 groupedThreads("onos/sr", "r-populator-%d", log));
Charles Chanfbcb8812018-04-18 18:41:05 -0700147 }
148
149 /**
150 * Updates a DefaultRoutingHandler object.
151 *
152 * @param srManager SegmentRoutingManager object
153 */
154 void update(SegmentRoutingManager srManager) {
sangho80f11cb2015-04-01 13:05:26 -0700155 this.srManager = srManager;
156 this.rulePopulator = checkNotNull(srManager.routingRulePopulator);
sangho9b169e32015-04-14 16:27:13 -0700157 this.config = checkNotNull(srManager.deviceConfiguration);
sangho80f11cb2015-04-01 13:05:26 -0700158 this.populationStatus = Status.IDLE;
sanghofb7c7292015-04-13 15:15:58 -0700159 this.currentEcmpSpgMap = Maps.newHashMap();
Saurav Das00e553b2018-04-21 17:19:48 -0700160 this.lastProgrammed = Sets.newConcurrentHashSet();
sangho80f11cb2015-04-01 13:05:26 -0700161 }
162
163 /**
Saurav Das62ae6792017-05-15 15:34:25 -0700164 * Returns an immutable copy of the current ECMP shortest-path graph as
165 * computed by this controller instance.
166 *
Saurav Das261c3002017-06-13 15:35:54 -0700167 * @return immutable copy of the current ECMP graph
Saurav Das62ae6792017-05-15 15:34:25 -0700168 */
169 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEmcpSpgMap() {
170 Builder<DeviceId, EcmpShortestPathGraph> builder = ImmutableMap.builder();
171 currentEcmpSpgMap.entrySet().forEach(entry -> {
172 if (entry.getValue() != null) {
173 builder.put(entry.getKey(), entry.getValue());
174 }
175 });
176 return builder.build();
177 }
178
Saurav Dasfbe74572017-08-03 18:30:35 -0700179 /**
180 * Acquires the lock used when making routing changes.
181 */
182 public void acquireRoutingLock() {
183 statusLock.lock();
184 }
185
186 /**
187 * Releases the lock used when making routing changes.
188 */
189 public void releaseRoutingLock() {
190 statusLock.unlock();
191 }
192
193 /**
194 * Determines if routing in the network has been stable in the last
195 * STABLITY_THRESHOLD seconds, by comparing the current time to the last
196 * routing change timestamp.
197 *
198 * @return true if stable
199 */
200 public boolean isRoutingStable() {
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -0700201 long last = (long) (lastRoutingChange.toEpochMilli() / 1000.0);
202 long now = (long) (Instant.now().toEpochMilli() / 1000.0);
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700203 log.trace("Routing stable since {}s", now - last);
Saurav Dasfbe74572017-08-03 18:30:35 -0700204 return (now - last) > STABLITY_THRESHOLD;
205 }
206
Saurav Das49368392018-04-23 18:42:12 -0700207 /**
208 * Gracefully shuts down the defaultRoutingHandler. Typically called when
209 * the app is deactivated
210 */
211 public void shutdown() {
212 executorService.shutdown();
213 executorServiceMstChg.shutdown();
Saurav Das68e1b6a2018-06-11 17:02:31 -0700214 executorServiceFRR.shutdown();
piera9941192019-04-24 16:12:47 +0200215 routePopulators.shutdown();
Saurav Das49368392018-04-23 18:42:12 -0700216 }
Saurav Dasfbe74572017-08-03 18:30:35 -0700217
Saurav Das261c3002017-06-13 15:35:54 -0700218 //////////////////////////////////////
219 // Route path handling
220 //////////////////////////////////////
221
Saurav Dase6c448a2018-01-18 12:07:33 -0800222 /* The following three methods represent the three major ways in which
223 * route-path handling is triggered in the network
Saurav Das261c3002017-06-13 15:35:54 -0700224 * a) due to configuration change
225 * b) due to route-added event
226 * c) due to change in the topology
227 */
228
Saurav Das62ae6792017-05-15 15:34:25 -0700229 /**
Saurav Das261c3002017-06-13 15:35:54 -0700230 * Populates all routing rules to all switches. Typically triggered at
231 * startup or after a configuration event.
sangho80f11cb2015-04-01 13:05:26 -0700232 */
Saurav Das62ae6792017-05-15 15:34:25 -0700233 public void populateAllRoutingRules() {
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -0700234 lastRoutingChange = Instant.now();
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900235 statusLock.lock();
236 try {
Saurav Das261c3002017-06-13 15:35:54 -0700237 if (populationStatus == Status.STARTED) {
238 log.warn("Previous rule population is not finished. Cannot"
239 + " proceed with populateAllRoutingRules");
240 return;
241 }
242
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900243 populationStatus = Status.STARTED;
244 rulePopulator.resetCounter();
Saurav Das261c3002017-06-13 15:35:54 -0700245 log.info("Starting to populate all routing rules");
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900246 log.debug("populateAllRoutingRules: populationStatus is STARTED");
sangho80f11cb2015-04-01 13:05:26 -0700247
Saurav Das261c3002017-06-13 15:35:54 -0700248 // take a snapshot of the topology
249 updatedEcmpSpgMap = new HashMap<>();
250 Set<EdgePair> edgePairs = new HashSet<>();
251 Set<ArrayList<DeviceId>> routeChanges = new HashSet<>();
Jonathan Hart61e24e12017-11-30 18:23:42 -0800252 for (DeviceId dstSw : srManager.deviceConfiguration.getRouters()) {
Saurav Das261c3002017-06-13 15:35:54 -0700253 EcmpShortestPathGraph ecmpSpgUpdated =
Jonathan Hart61e24e12017-11-30 18:23:42 -0800254 new EcmpShortestPathGraph(dstSw, srManager);
255 updatedEcmpSpgMap.put(dstSw, ecmpSpgUpdated);
Charles Chan6dbcd252018-04-02 11:46:38 -0700256 Optional<DeviceId> pairDev = srManager.getPairDeviceId(dstSw);
257 if (pairDev.isPresent()) {
Saurav Das261c3002017-06-13 15:35:54 -0700258 // pairDev may not be available yet, but we still need to add
Charles Chan6dbcd252018-04-02 11:46:38 -0700259 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev.get(), srManager);
260 updatedEcmpSpgMap.put(pairDev.get(), ecmpSpgUpdated);
261 edgePairs.add(new EdgePair(dstSw, pairDev.get()));
Saurav Das261c3002017-06-13 15:35:54 -0700262 }
Charles Chand66d6712018-03-29 16:03:41 -0700263
264 if (!shouldProgram(dstSw)) {
Saurav Das00e553b2018-04-21 17:19:48 -0700265 lastProgrammed.remove(dstSw);
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900266 continue;
Saurav Das00e553b2018-04-21 17:19:48 -0700267 } else {
268 lastProgrammed.add(dstSw);
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900269 }
Saurav Das00e553b2018-04-21 17:19:48 -0700270 // To do a full reroute, assume all route-paths have changed
Charles Chand66d6712018-03-29 16:03:41 -0700271 for (DeviceId dev : deviceAndItsPair(dstSw)) {
Jonathan Hart61e24e12017-11-30 18:23:42 -0800272 for (DeviceId targetSw : srManager.deviceConfiguration.getRouters()) {
273 if (targetSw.equals(dev)) {
Saurav Das261c3002017-06-13 15:35:54 -0700274 continue;
275 }
Jonathan Hart61e24e12017-11-30 18:23:42 -0800276 routeChanges.add(Lists.newArrayList(targetSw, dev));
Saurav Das261c3002017-06-13 15:35:54 -0700277 }
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900278 }
Saurav Das261c3002017-06-13 15:35:54 -0700279 }
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900280
Saurav Das261c3002017-06-13 15:35:54 -0700281 if (!redoRouting(routeChanges, edgePairs, null)) {
282 log.debug("populateAllRoutingRules: populationStatus is ABORTED");
283 populationStatus = Status.ABORTED;
284 log.warn("Failed to repopulate all routing rules.");
285 return;
sangho80f11cb2015-04-01 13:05:26 -0700286 }
287
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900288 log.debug("populateAllRoutingRules: populationStatus is SUCCEEDED");
289 populationStatus = Status.SUCCEEDED;
Saurav Das261c3002017-06-13 15:35:54 -0700290 log.info("Completed all routing rule population. Total # of rules pushed : {}",
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900291 rulePopulator.getCounter());
Saurav Das62ae6792017-05-15 15:34:25 -0700292 return;
pierdebd15c2019-04-19 20:55:53 +0200293 } catch (Exception e) {
294 log.error("populateAllRoutingRules thrown an exception: {}",
295 e.getMessage(), e);
296 populationStatus = Status.ABORTED;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900297 } finally {
298 statusLock.unlock();
sangho80f11cb2015-04-01 13:05:26 -0700299 }
sangho80f11cb2015-04-01 13:05:26 -0700300 }
301
sanghofb7c7292015-04-13 15:15:58 -0700302 /**
Saurav Das261c3002017-06-13 15:35:54 -0700303 * Populate rules from all other edge devices to the connect-point(s)
304 * specified for the given subnets.
305 *
306 * @param cpts connect point(s) of the subnets being added
307 * @param subnets subnets being added
Charles Chan910be6a2017-08-23 14:46:43 -0700308 */
309 // XXX refactor
Saurav Das261c3002017-06-13 15:35:54 -0700310 protected void populateSubnet(Set<ConnectPoint> cpts, Set<IpPrefix> subnets) {
Charles Chan6db55b92017-09-11 15:21:57 -0700311 if (cpts == null || cpts.size() < 1 || cpts.size() > 2) {
312 log.warn("Skipping populateSubnet due to illegal size of connect points. {}", cpts);
313 return;
314 }
315
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -0700316 lastRoutingChange = Instant.now();
Saurav Das261c3002017-06-13 15:35:54 -0700317 statusLock.lock();
318 try {
319 if (populationStatus == Status.STARTED) {
320 log.warn("Previous rule population is not finished. Cannot"
321 + " proceed with routing rules for added routes");
322 return;
323 }
324 populationStatus = Status.STARTED;
325 rulePopulator.resetCounter();
Charles Chan910be6a2017-08-23 14:46:43 -0700326 log.info("Starting to populate routing rules for added routes, subnets={}, cpts={}",
327 subnets, cpts);
Saurav Das6430f412018-01-25 09:49:01 -0800328 // In principle an update to a subnet/prefix should not require a
329 // new ECMPspg calculation as it is not a topology event. As a
330 // result, we use the current/existing ECMPspg in the updated map
331 // used by the redoRouting method.
Saurav Das6de6ffd2018-02-09 09:15:03 -0800332 if (updatedEcmpSpgMap == null) {
333 updatedEcmpSpgMap = new HashMap<>();
334 }
Saurav Das6430f412018-01-25 09:49:01 -0800335 currentEcmpSpgMap.entrySet().forEach(entry -> {
336 updatedEcmpSpgMap.put(entry.getKey(), entry.getValue());
Saurav Dase321cff2018-02-09 17:26:45 -0800337 if (log.isTraceEnabled()) {
338 log.trace("Root switch: {}", entry.getKey());
339 log.trace(" Current/Existing SPG: {}", entry.getValue());
Saurav Das6430f412018-01-25 09:49:01 -0800340 }
341 });
Saurav Das261c3002017-06-13 15:35:54 -0700342 Set<EdgePair> edgePairs = new HashSet<>();
343 Set<ArrayList<DeviceId>> routeChanges = new HashSet<>();
344 boolean handleRouting = false;
345
346 if (cpts.size() == 2) {
347 // ensure connect points are edge-pairs
348 Iterator<ConnectPoint> iter = cpts.iterator();
349 DeviceId dev1 = iter.next().deviceId();
Charles Chan6dbcd252018-04-02 11:46:38 -0700350 Optional<DeviceId> pairDev = srManager.getPairDeviceId(dev1);
351 if (pairDev.isPresent() && iter.next().deviceId().equals(pairDev.get())) {
352 edgePairs.add(new EdgePair(dev1, pairDev.get()));
Saurav Das261c3002017-06-13 15:35:54 -0700353 } else {
354 log.warn("Connectpoints {} for subnets {} not on "
355 + "pair-devices.. aborting populateSubnet", cpts, subnets);
356 populationStatus = Status.ABORTED;
357 return;
358 }
359 for (ConnectPoint cp : cpts) {
Saurav Das6430f412018-01-25 09:49:01 -0800360 if (updatedEcmpSpgMap.get(cp.deviceId()) == null) {
361 EcmpShortestPathGraph ecmpSpgUpdated =
Saurav Das261c3002017-06-13 15:35:54 -0700362 new EcmpShortestPathGraph(cp.deviceId(), srManager);
Saurav Das6430f412018-01-25 09:49:01 -0800363 updatedEcmpSpgMap.put(cp.deviceId(), ecmpSpgUpdated);
364 log.warn("populateSubnet: no updated graph for dev:{}"
365 + " ... creating", cp.deviceId());
366 }
Charles Chand66d6712018-03-29 16:03:41 -0700367 if (!shouldProgram(cp.deviceId())) {
Saurav Das261c3002017-06-13 15:35:54 -0700368 continue;
369 }
370 handleRouting = true;
371 }
372 } else {
373 // single connect point
374 DeviceId dstSw = cpts.iterator().next().deviceId();
Saurav Das6430f412018-01-25 09:49:01 -0800375 if (updatedEcmpSpgMap.get(dstSw) == null) {
376 EcmpShortestPathGraph ecmpSpgUpdated =
Saurav Das261c3002017-06-13 15:35:54 -0700377 new EcmpShortestPathGraph(dstSw, srManager);
Saurav Das6430f412018-01-25 09:49:01 -0800378 updatedEcmpSpgMap.put(dstSw, ecmpSpgUpdated);
379 log.warn("populateSubnet: no updated graph for dev:{}"
380 + " ... creating", dstSw);
381 }
Charles Chand66d6712018-03-29 16:03:41 -0700382 handleRouting = shouldProgram(dstSw);
Saurav Das261c3002017-06-13 15:35:54 -0700383 }
384
385 if (!handleRouting) {
386 log.debug("This instance is not handling ecmp routing to the "
387 + "connectPoint(s) {}", cpts);
388 populationStatus = Status.ABORTED;
389 return;
390 }
391
392 // if it gets here, this instance should handle routing for the
393 // connectpoint(s). Assume all route-paths have to be updated to
394 // the connectpoint(s) with the following exceptions
395 // 1. if target is non-edge no need for routing rules
396 // 2. if target is one of the connectpoints
397 for (ConnectPoint cp : cpts) {
398 DeviceId dstSw = cp.deviceId();
399 for (Device targetSw : srManager.deviceService.getDevices()) {
400 boolean isEdge = false;
401 try {
402 isEdge = config.isEdgeDevice(targetSw.id());
403 } catch (DeviceConfigNotFoundException e) {
Charles Chaneaf3c9b2018-02-16 17:20:54 -0800404 log.warn(e.getMessage() + "aborting populateSubnet on targetSw {}", targetSw.id());
405 continue;
Saurav Das261c3002017-06-13 15:35:54 -0700406 }
Charles Chan6dbcd252018-04-02 11:46:38 -0700407 Optional<DeviceId> pairDev = srManager.getPairDeviceId(dstSw);
Saurav Das261c3002017-06-13 15:35:54 -0700408 if (dstSw.equals(targetSw.id()) || !isEdge ||
Charles Chan6dbcd252018-04-02 11:46:38 -0700409 (cpts.size() == 2 && pairDev.isPresent() && targetSw.id().equals(pairDev.get()))) {
Saurav Das261c3002017-06-13 15:35:54 -0700410 continue;
411 }
412 routeChanges.add(Lists.newArrayList(targetSw.id(), dstSw));
413 }
414 }
415
416 if (!redoRouting(routeChanges, edgePairs, subnets)) {
417 log.debug("populateSubnet: populationStatus is ABORTED");
418 populationStatus = Status.ABORTED;
419 log.warn("Failed to repopulate the rules for subnet.");
420 return;
421 }
422
423 log.debug("populateSubnet: populationStatus is SUCCEEDED");
424 populationStatus = Status.SUCCEEDED;
425 log.info("Completed subnet population. Total # of rules pushed : {}",
426 rulePopulator.getCounter());
427 return;
428
pierdebd15c2019-04-19 20:55:53 +0200429 } catch (Exception e) {
430 log.error("populateSubnet thrown an exception: {}",
431 e.getMessage(), e);
432 populationStatus = Status.ABORTED;
Saurav Das261c3002017-06-13 15:35:54 -0700433 } finally {
434 statusLock.unlock();
435 }
436 }
437
438 /**
Saurav Das62ae6792017-05-15 15:34:25 -0700439 * Populates the routing rules or makes hash group changes according to the
440 * route-path changes due to link failure, switch failure or link up. This
441 * method should only be called for one of these three possible event-types.
Saurav Dasdc7f2752018-03-18 21:28:15 -0700442 * Note that when a switch goes away, all of its links fail as well, but
443 * this is handled as a single switch removal event.
sanghofb7c7292015-04-13 15:15:58 -0700444 *
Saurav Dasdc7f2752018-03-18 21:28:15 -0700445 * @param linkDown the single failed link, or null for other conditions such
446 * as link-up or a removed switch
Saurav Das62ae6792017-05-15 15:34:25 -0700447 * @param linkUp the single link up, or null for other conditions such as
Saurav Dasdc7f2752018-03-18 21:28:15 -0700448 * link-down or a removed switch
449 * @param switchDown the removed switch, or null for other conditions such
450 * as link-down or link-up
451 * @param seenBefore true if this event is for a linkUp or linkDown for a
452 * seen link
453 */
454 // TODO This method should be refactored into three separated methods
Charles Chan9d2dd552018-06-19 20:56:33 -0700455 public void populateRoutingRulesForLinkStatusChange(Link linkDown, Link linkUp,
456 DeviceId switchDown, boolean seenBefore) {
Saurav Dasdc7f2752018-03-18 21:28:15 -0700457 if (Stream.of(linkDown, linkUp, switchDown).filter(Objects::nonNull)
458 .count() != 1) {
Saurav Das62ae6792017-05-15 15:34:25 -0700459 log.warn("Only one event can be handled for link status change .. aborting");
460 return;
461 }
Saurav Dasdc7f2752018-03-18 21:28:15 -0700462
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -0700463 lastRoutingChange = Instant.now();
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900464 statusLock.lock();
465 try {
sanghofb7c7292015-04-13 15:15:58 -0700466
467 if (populationStatus == Status.STARTED) {
Saurav Das261c3002017-06-13 15:35:54 -0700468 log.warn("Previous rule population is not finished. Cannot"
Saurav Das6430f412018-01-25 09:49:01 -0800469 + " proceeed with routingRules for Topology change");
Saurav Das62ae6792017-05-15 15:34:25 -0700470 return;
sanghofb7c7292015-04-13 15:15:58 -0700471 }
472
Saurav Das261c3002017-06-13 15:35:54 -0700473 // Take snapshots of the topology
sangho28d0b6d2015-05-07 13:30:57 -0700474 updatedEcmpSpgMap = new HashMap<>();
Saurav Das261c3002017-06-13 15:35:54 -0700475 Set<EdgePair> edgePairs = new HashSet<>();
sangho28d0b6d2015-05-07 13:30:57 -0700476 for (Device sw : srManager.deviceService.getDevices()) {
Shashikanth VH0637b162015-12-11 01:32:44 +0530477 EcmpShortestPathGraph ecmpSpgUpdated =
478 new EcmpShortestPathGraph(sw.id(), srManager);
sangho28d0b6d2015-05-07 13:30:57 -0700479 updatedEcmpSpgMap.put(sw.id(), ecmpSpgUpdated);
Charles Chan6dbcd252018-04-02 11:46:38 -0700480 Optional<DeviceId> pairDev = srManager.getPairDeviceId(sw.id());
481 if (pairDev.isPresent()) {
Saurav Das261c3002017-06-13 15:35:54 -0700482 // pairDev may not be available yet, but we still need to add
Charles Chan6dbcd252018-04-02 11:46:38 -0700483 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev.get(), srManager);
484 updatedEcmpSpgMap.put(pairDev.get(), ecmpSpgUpdated);
485 edgePairs.add(new EdgePair(sw.id(), pairDev.get()));
Saurav Das261c3002017-06-13 15:35:54 -0700486 }
sangho28d0b6d2015-05-07 13:30:57 -0700487 }
488
Saurav Das6430f412018-01-25 09:49:01 -0800489 log.info("Starting to populate routing rules from Topology change");
sanghodf0153f2015-05-05 14:13:34 -0700490
sanghofb7c7292015-04-13 15:15:58 -0700491 Set<ArrayList<DeviceId>> routeChanges;
Saurav Das62ae6792017-05-15 15:34:25 -0700492 log.debug("populateRoutingRulesForLinkStatusChange: "
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700493 + "populationStatus is STARTED");
sanghofb7c7292015-04-13 15:15:58 -0700494 populationStatus = Status.STARTED;
Saurav Das6430f412018-01-25 09:49:01 -0800495 rulePopulator.resetCounter(); //XXX maybe useful to have a rehash ctr
496 boolean hashGroupsChanged = false;
Saurav Das1b391d52016-11-29 14:27:25 -0800497 // try optimized re-routing
Saurav Das62ae6792017-05-15 15:34:25 -0700498 if (linkDown == null) {
499 // either a linkUp or a switchDown - compute all route changes by
500 // comparing all routes of existing ECMP SPG to new ECMP SPG
Saurav Dascea556f2018-03-05 14:37:16 -0800501 routeChanges = computeRouteChange(switchDown);
Saurav Das62ae6792017-05-15 15:34:25 -0700502
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700503 // deal with linkUp of a seen-before link
Saurav Dasdc7f2752018-03-18 21:28:15 -0700504 if (linkUp != null && seenBefore) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700505 // link previously seen before
506 // do hash-bucket changes instead of a re-route
507 processHashGroupChange(routeChanges, false, null);
508 // clear out routesChanges so a re-route is not attempted
509 routeChanges = ImmutableSet.of();
Saurav Das6430f412018-01-25 09:49:01 -0800510 hashGroupsChanged = true;
Saurav Das62ae6792017-05-15 15:34:25 -0700511 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700512 // for a linkUp of a never-seen-before link
513 // let it fall through to a reroute of the routeChanges
Saurav Das62ae6792017-05-15 15:34:25 -0700514
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700515 //deal with switchDown
516 if (switchDown != null) {
517 processHashGroupChange(routeChanges, true, switchDown);
518 // clear out routesChanges so a re-route is not attempted
519 routeChanges = ImmutableSet.of();
Saurav Das6430f412018-01-25 09:49:01 -0800520 hashGroupsChanged = true;
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700521 }
sanghofb7c7292015-04-13 15:15:58 -0700522 } else {
Saurav Das62ae6792017-05-15 15:34:25 -0700523 // link has gone down
524 // Compare existing ECMP SPG only with the link that went down
525 routeChanges = computeDamagedRoutes(linkDown);
Saurav Das68e1b6a2018-06-11 17:02:31 -0700526 processHashGroupChange(routeChanges, true, null);
527 // clear out routesChanges so a re-route is not attempted
528 routeChanges = ImmutableSet.of();
529 hashGroupsChanged = true;
Saurav Dasb149be12016-06-07 10:08:06 -0700530 }
531
sanghofb7c7292015-04-13 15:15:58 -0700532 if (routeChanges.isEmpty()) {
Saurav Das6430f412018-01-25 09:49:01 -0800533 if (hashGroupsChanged) {
534 log.info("Hash-groups changed for link status change");
535 } else {
536 log.info("No re-route or re-hash attempted for the link"
537 + " status change");
538 updatedEcmpSpgMap.keySet().forEach(devId -> {
539 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
540 log.debug("Updating ECMPspg for remaining dev:{}", devId);
541 });
542 }
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700543 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sanghofb7c7292015-04-13 15:15:58 -0700544 populationStatus = Status.SUCCEEDED;
Saurav Das62ae6792017-05-15 15:34:25 -0700545 return;
sanghofb7c7292015-04-13 15:15:58 -0700546 }
547
Saurav Das62ae6792017-05-15 15:34:25 -0700548 // reroute of routeChanges
Saurav Das261c3002017-06-13 15:35:54 -0700549 if (redoRouting(routeChanges, edgePairs, null)) {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700550 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sanghofb7c7292015-04-13 15:15:58 -0700551 populationStatus = Status.SUCCEEDED;
Saurav Das261c3002017-06-13 15:35:54 -0700552 log.info("Completed repopulation of rules for link-status change."
553 + " # of rules populated : {}", rulePopulator.getCounter());
Saurav Das62ae6792017-05-15 15:34:25 -0700554 return;
sanghofb7c7292015-04-13 15:15:58 -0700555 } else {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700556 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is ABORTED");
sanghofb7c7292015-04-13 15:15:58 -0700557 populationStatus = Status.ABORTED;
Saurav Das261c3002017-06-13 15:35:54 -0700558 log.warn("Failed to repopulate the rules for link status change.");
Saurav Das62ae6792017-05-15 15:34:25 -0700559 return;
sanghofb7c7292015-04-13 15:15:58 -0700560 }
pierdebd15c2019-04-19 20:55:53 +0200561 } catch (Exception e) {
562 log.error("populateRoutingRulesForLinkStatusChange thrown an exception: {}",
563 e.getMessage(), e);
564 populationStatus = Status.ABORTED;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900565 } finally {
566 statusLock.unlock();
sanghofb7c7292015-04-13 15:15:58 -0700567 }
568 }
569
Saurav Das62ae6792017-05-15 15:34:25 -0700570 /**
Saurav Das261c3002017-06-13 15:35:54 -0700571 * Processes a set a route-path changes by reprogramming routing rules and
572 * creating new hash-groups or editing them if necessary. This method also
573 * determines the next-hops for the route-path from the src-switch (target)
574 * of the path towards the dst-switch of the path.
Saurav Das62ae6792017-05-15 15:34:25 -0700575 *
Saurav Das261c3002017-06-13 15:35:54 -0700576 * @param routeChanges a set of route-path changes, where each route-path is
577 * a list with its first element the src-switch (target)
578 * of the path, and the second element the dst-switch of
579 * the path.
580 * @param edgePairs a set of edge-switches that are paired by configuration
581 * @param subnets a set of prefixes that need to be populated in the routing
582 * table of the target switch in the route-path. Can be null,
583 * in which case all the prefixes belonging to the dst-switch
584 * will be populated in the target switch
585 * @return true if successful in repopulating all routes
Saurav Das62ae6792017-05-15 15:34:25 -0700586 */
Saurav Das261c3002017-06-13 15:35:54 -0700587 private boolean redoRouting(Set<ArrayList<DeviceId>> routeChanges,
588 Set<EdgePair> edgePairs, Set<IpPrefix> subnets) {
589 // first make every entry two-elements
590 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
591 for (ArrayList<DeviceId> route : routeChanges) {
592 if (route.size() == 1) {
593 DeviceId dstSw = route.get(0);
594 EcmpShortestPathGraph ec = updatedEcmpSpgMap.get(dstSw);
595 if (ec == null) {
596 log.warn("No graph found for {} .. aborting redoRouting", dstSw);
597 return false;
598 }
599 ec.getAllLearnedSwitchesAndVia().keySet().forEach(key -> {
600 ec.getAllLearnedSwitchesAndVia().get(key).keySet().forEach(target -> {
601 changedRoutes.add(Lists.newArrayList(target, dstSw));
602 });
603 });
604 } else {
605 DeviceId targetSw = route.get(0);
606 DeviceId dstSw = route.get(1);
607 changedRoutes.add(Lists.newArrayList(targetSw, dstSw));
608 }
609 }
610
611 // now process changedRoutes according to edgePairs
612 if (!redoRoutingEdgePairs(edgePairs, subnets, changedRoutes)) {
613 return false; //abort routing and fail fast
614 }
615
616 // whatever is left in changedRoutes is now processed for individual dsts.
Saurav Das6430f412018-01-25 09:49:01 -0800617 Set<DeviceId> updatedDevices = Sets.newHashSet();
618 if (!redoRoutingIndividualDests(subnets, changedRoutes,
619 updatedDevices)) {
Saurav Das261c3002017-06-13 15:35:54 -0700620 return false; //abort routing and fail fast
621 }
622
Saurav Das261c3002017-06-13 15:35:54 -0700623 // update ecmpSPG for all edge-pairs
624 for (EdgePair ep : edgePairs) {
625 currentEcmpSpgMap.put(ep.dev1, updatedEcmpSpgMap.get(ep.dev1));
626 currentEcmpSpgMap.put(ep.dev2, updatedEcmpSpgMap.get(ep.dev2));
627 log.debug("Updating ECMPspg for edge-pair:{}-{}", ep.dev1, ep.dev2);
628 }
Saurav Das6430f412018-01-25 09:49:01 -0800629
630 // here is where we update all devices not touched by this instance
631 updatedEcmpSpgMap.keySet().stream()
632 .filter(devId -> !edgePairs.stream().anyMatch(ep -> ep.includes(devId)))
633 .filter(devId -> !updatedDevices.contains(devId))
634 .forEach(devId -> {
635 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
636 log.debug("Updating ECMPspg for remaining dev:{}", devId);
637 });
Saurav Das261c3002017-06-13 15:35:54 -0700638 return true;
639 }
640
641 /**
642 * Programs targetSw in the changedRoutes for given prefixes reachable by
643 * an edgePair. If no prefixes are given, the method will use configured
644 * subnets/prefixes. If some configured subnets belong only to a specific
645 * destination in the edgePair, then the target switch will be programmed
646 * only to that destination.
647 *
648 * @param edgePairs set of edge-pairs for which target will be programmed
649 * @param subnets a set of prefixes that need to be populated in the routing
650 * table of the target switch in the changedRoutes. Can be null,
651 * in which case all the configured prefixes belonging to the
652 * paired switches will be populated in the target switch
653 * @param changedRoutes a set of route-path changes, where each route-path is
654 * a list with its first element the src-switch (target)
655 * of the path, and the second element the dst-switch of
656 * the path.
657 * @return true if successful
658 */
piera9941192019-04-24 16:12:47 +0200659 private boolean redoRoutingEdgePairs(Set<EdgePair> edgePairs, Set<IpPrefix> subnets,
660 Set<ArrayList<DeviceId>> changedRoutes) {
Saurav Das261c3002017-06-13 15:35:54 -0700661 for (EdgePair ep : edgePairs) {
662 // temp store for a target's changedRoutes to this edge-pair
663 Map<DeviceId, Set<ArrayList<DeviceId>>> targetRoutes = new HashMap<>();
664 Iterator<ArrayList<DeviceId>> i = changedRoutes.iterator();
665 while (i.hasNext()) {
666 ArrayList<DeviceId> route = i.next();
667 DeviceId dstSw = route.get(1);
668 if (ep.includes(dstSw)) {
669 // routeChange for edge pair found
670 // sort by target iff target is edge and remove from changedRoutes
671 DeviceId targetSw = route.get(0);
672 try {
673 if (!srManager.deviceConfiguration.isEdgeDevice(targetSw)) {
674 continue;
675 }
676 } catch (DeviceConfigNotFoundException e) {
677 log.warn(e.getMessage() + "aborting redoRouting");
678 return false;
679 }
680 // route is from another edge to this edge-pair
681 if (targetRoutes.containsKey(targetSw)) {
682 targetRoutes.get(targetSw).add(route);
683 } else {
684 Set<ArrayList<DeviceId>> temp = new HashSet<>();
685 temp.add(route);
686 targetRoutes.put(targetSw, temp);
687 }
688 i.remove();
689 }
690 }
691 // so now for this edgepair we have a per target set of routechanges
692 // process target->edgePair route
piera9941192019-04-24 16:12:47 +0200693 List<Future<Boolean>> futures = Lists.newArrayList();
Saurav Das261c3002017-06-13 15:35:54 -0700694 for (Map.Entry<DeviceId, Set<ArrayList<DeviceId>>> entry :
695 targetRoutes.entrySet()) {
696 log.debug("* redoRoutingDstPair Target:{} -> edge-pair {}",
697 entry.getKey(), ep);
piera9941192019-04-24 16:12:47 +0200698 futures.add(routePopulators.submit(new RedoRoutingEdgePair(entry.getKey(), entry.getValue(),
699 subnets, ep)));
700 }
701 if (!checkJobs(futures)) {
702 return false;
Saurav Das261c3002017-06-13 15:35:54 -0700703 }
704 // if it gets here it has succeeded for all targets to this edge-pair
705 }
706 return true;
707 }
708
piera9941192019-04-24 16:12:47 +0200709 private final class RedoRoutingEdgePair implements PickyCallable<Boolean> {
710 private DeviceId targetSw;
711 private Set<ArrayList<DeviceId>> routes;
712 private Set<IpPrefix> subnets;
713 private EdgePair ep;
714
715 /**
716 * Builds a RedoRoutingEdgePair task which provides a result.
717 *
718 * @param targetSw the target switch
719 * @param routes the changed routes
720 * @param subnets the subnets
721 * @param ep the edge pair
722 */
723 RedoRoutingEdgePair(DeviceId targetSw, Set<ArrayList<DeviceId>> routes,
724 Set<IpPrefix> subnets, EdgePair ep) {
725 this.targetSw = targetSw;
726 this.routes = routes;
727 this.subnets = subnets;
728 this.ep = ep;
729 }
730
731 @Override
732 public Boolean call() throws Exception {
733 return redoRoutingEdgePair();
734 }
735
736 @Override
737 public int hint() {
738 return targetSw.hashCode();
739 }
740
741 private boolean redoRoutingEdgePair() {
742 Map<DeviceId, Set<DeviceId>> perDstNextHops = new HashMap<>();
743 routes.forEach(route -> {
744 Set<DeviceId> nhops = getNextHops(route.get(0), route.get(1));
745 log.debug("route: target {} -> dst {} found with next-hops {}",
746 route.get(0), route.get(1), nhops);
747 perDstNextHops.put(route.get(1), nhops);
748 });
749
750 List<Set<IpPrefix>> batchedSubnetDev1, batchedSubnetDev2;
751 if (subnets != null) {
752 batchedSubnetDev1 = Lists.<Set<IpPrefix>>newArrayList(Sets.newHashSet(subnets));
753 batchedSubnetDev2 = Lists.<Set<IpPrefix>>newArrayList(Sets.newHashSet(subnets));
754 } else {
755 batchedSubnetDev1 = config.getBatchedSubnets(ep.dev1);
756 batchedSubnetDev2 = config.getBatchedSubnets(ep.dev2);
757 }
758 List<Set<IpPrefix>> batchedSubnetBoth = Streams
759 .zip(batchedSubnetDev1.stream(), batchedSubnetDev2.stream(), (a, b) -> Sets.intersection(a, b))
760 .filter(set -> !set.isEmpty())
761 .collect(Collectors.toList());
762 List<Set<IpPrefix>> batchedSubnetDev1Only = Streams
763 .zip(batchedSubnetDev1.stream(), batchedSubnetDev2.stream(), (a, b) -> Sets.difference(a, b))
764 .filter(set -> !set.isEmpty())
765 .collect(Collectors.toList());
766 List<Set<IpPrefix>> batchedSubnetDev2Only = Streams
767 .zip(batchedSubnetDev1.stream(), batchedSubnetDev2.stream(), (a, b) -> Sets.difference(b, a))
768 .filter(set -> !set.isEmpty())
769 .collect(Collectors.toList());
770
771 Set<DeviceId> nhDev1 = perDstNextHops.get(ep.dev1);
772 Set<DeviceId> nhDev2 = perDstNextHops.get(ep.dev2);
773
774 // handle routing to subnets common to edge-pair
775 // only if the targetSw is not part of the edge-pair and there
776 // exists a next hop to at least one of the devices in the edge-pair
777 if (!ep.includes(targetSw)
778 && ((nhDev1 != null && !nhDev1.isEmpty()) || (nhDev2 != null && !nhDev2.isEmpty()))) {
779 log.trace("getSubnets on both {} and {}: {}", ep.dev1, ep.dev2, batchedSubnetBoth);
780 for (Set<IpPrefix> prefixes : batchedSubnetBoth) {
781 if (!populateEcmpRoutingRulePartial(targetSw, ep.dev1, ep.dev2,
782 perDstNextHops, prefixes)) {
783 return false; // abort everything and fail fast
784 }
785 }
786
787 }
788 // handle routing to subnets that only belong to dev1 only if
789 // a next-hop exists from the target to dev1
790 if (!batchedSubnetDev1Only.isEmpty() &&
791 batchedSubnetDev1Only.stream().anyMatch(subnet -> !subnet.isEmpty()) &&
792 nhDev1 != null && !nhDev1.isEmpty()) {
793 Map<DeviceId, Set<DeviceId>> onlyDev1NextHops = new HashMap<>();
794 onlyDev1NextHops.put(ep.dev1, nhDev1);
795 log.trace("getSubnets on {} only: {}", ep.dev1, batchedSubnetDev1Only);
796 for (Set<IpPrefix> prefixes : batchedSubnetDev1Only) {
797 if (!populateEcmpRoutingRulePartial(targetSw, ep.dev1, null,
798 onlyDev1NextHops, prefixes)) {
799 return false; // abort everything and fail fast
800 }
801 }
802 }
803 // handle routing to subnets that only belong to dev2 only if
804 // a next-hop exists from the target to dev2
805 if (!batchedSubnetDev2Only.isEmpty() &&
806 batchedSubnetDev2Only.stream().anyMatch(subnet -> !subnet.isEmpty()) &&
807 nhDev2 != null && !nhDev2.isEmpty()) {
808 Map<DeviceId, Set<DeviceId>> onlyDev2NextHops = new HashMap<>();
809 onlyDev2NextHops.put(ep.dev2, nhDev2);
810 log.trace("getSubnets on {} only: {}", ep.dev2, batchedSubnetDev2Only);
811 for (Set<IpPrefix> prefixes : batchedSubnetDev2Only) {
812 if (!populateEcmpRoutingRulePartial(targetSw, ep.dev2, null,
813 onlyDev2NextHops, prefixes)) {
814 return false; // abort everything and fail fast
815 }
816 }
817 }
818 return true;
819 }
820 }
821
Saurav Das261c3002017-06-13 15:35:54 -0700822 /**
823 * Programs targetSw in the changedRoutes for given prefixes reachable by
824 * a destination switch that is not part of an edge-pair.
825 * If no prefixes are given, the method will use configured subnets/prefixes.
826 *
827 * @param subnets a set of prefixes that need to be populated in the routing
828 * table of the target switch in the changedRoutes. Can be null,
829 * in which case all the configured prefixes belonging to the
830 * paired switches will be populated in the target switch
831 * @param changedRoutes a set of route-path changes, where each route-path is
832 * a list with its first element the src-switch (target)
833 * of the path, and the second element the dst-switch of
834 * the path.
835 * @return true if successful
836 */
piera9941192019-04-24 16:12:47 +0200837 private boolean redoRoutingIndividualDests(Set<IpPrefix> subnets, Set<ArrayList<DeviceId>> changedRoutes,
Saurav Das6430f412018-01-25 09:49:01 -0800838 Set<DeviceId> updatedDevices) {
Saurav Das261c3002017-06-13 15:35:54 -0700839 // aggregate route-path changes for each dst device
840 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> routesBydevice =
841 new HashMap<>();
842 for (ArrayList<DeviceId> route: changedRoutes) {
843 DeviceId dstSw = route.get(1);
844 ArrayList<ArrayList<DeviceId>> deviceRoutes =
845 routesBydevice.get(dstSw);
846 if (deviceRoutes == null) {
847 deviceRoutes = new ArrayList<>();
848 routesBydevice.put(dstSw, deviceRoutes);
849 }
850 deviceRoutes.add(route);
851 }
piera9941192019-04-24 16:12:47 +0200852 // iterate over the impacted devices
Saurav Das261c3002017-06-13 15:35:54 -0700853 for (DeviceId impactedDstDevice : routesBydevice.keySet()) {
854 ArrayList<ArrayList<DeviceId>> deviceRoutes =
855 routesBydevice.get(impactedDstDevice);
piera9941192019-04-24 16:12:47 +0200856 List<Future<Boolean>> futures = Lists.newArrayList();
Saurav Das261c3002017-06-13 15:35:54 -0700857 for (ArrayList<DeviceId> route: deviceRoutes) {
858 log.debug("* redoRoutingIndiDst Target: {} -> dst: {}",
859 route.get(0), route.get(1));
piera9941192019-04-24 16:12:47 +0200860 futures.add(routePopulators.submit(new RedoRoutingIndividualDest(subnets, route)));
861 }
862 // check the execution of each job
863 if (!checkJobs(futures)) {
864 return false;
Saurav Das261c3002017-06-13 15:35:54 -0700865 }
866 //Only if all the flows for all impacted routes to a
867 //specific target are pushed successfully, update the
868 //ECMP graph for that target. Or else the next event
869 //would not see any changes in the ECMP graphs.
870 //In another case, the target switch has gone away, so
871 //routes can't be installed. In that case, the current map
872 //is updated here, without any flows being pushed.
873 currentEcmpSpgMap.put(impactedDstDevice,
874 updatedEcmpSpgMap.get(impactedDstDevice));
Saurav Das6430f412018-01-25 09:49:01 -0800875 updatedDevices.add(impactedDstDevice);
Saurav Das261c3002017-06-13 15:35:54 -0700876 log.debug("Updating ECMPspg for impacted dev:{}", impactedDstDevice);
877 }
878 return true;
879 }
880
piera9941192019-04-24 16:12:47 +0200881 private final class RedoRoutingIndividualDest implements PickyCallable<Boolean> {
882 private DeviceId targetSw;
883 private ArrayList<DeviceId> route;
884 private Set<IpPrefix> subnets;
885
886 /**
887 * Builds a RedoRoutingIndividualDest task, which provides a result.
888 *
889 * @param subnets a set of prefixes
890 * @param route a route-path change
891 */
892 RedoRoutingIndividualDest(Set<IpPrefix> subnets, ArrayList<DeviceId> route) {
893 this.targetSw = route.get(0);
894 this.route = route;
895 this.subnets = subnets;
896 }
897
898 @Override
899 public Boolean call() throws Exception {
900 DeviceId dstSw = route.get(1); // same as impactedDstDevice
901 Set<DeviceId> nextHops = getNextHops(targetSw, dstSw);
902 if (nextHops.isEmpty()) {
903 log.debug("Could not find next hop from target:{} --> dst {} "
904 + "skipping this route", targetSw, dstSw);
905 return true;
906 }
907 Map<DeviceId, Set<DeviceId>> nhops = new HashMap<>();
908 nhops.put(dstSw, nextHops);
909 if (!populateEcmpRoutingRulePartial(targetSw, dstSw, null, nhops,
910 (subnets == null) ? Sets.newHashSet() : subnets)) {
911 return false; // abort routing and fail fast
912 }
913 log.debug("Populating flow rules from target: {} to dst: {}"
914 + " is successful", targetSw, dstSw);
915 return true;
916 }
917
918 @Override
919 public int hint() {
920 return targetSw.hashCode();
921 }
922 }
923
Saurav Das261c3002017-06-13 15:35:54 -0700924 /**
925 * Populate ECMP rules for subnets from target to destination via nexthops.
926 *
927 * @param targetSw Device ID of target switch in which rules will be programmed
928 * @param destSw1 Device ID of final destination switch to which the rules will forward
929 * @param destSw2 Device ID of paired destination switch to which the rules will forward
930 * A null deviceId indicates packets should only be sent to destSw1
Saurav Das97241862018-02-14 14:14:54 -0800931 * @param nextHops Map of a set of next hops per destSw
Saurav Das261c3002017-06-13 15:35:54 -0700932 * @param subnets Subnets to be populated. If empty, populate all configured subnets.
933 * @return true if it succeeds in populating rules
934 */ // refactor
piera9941192019-04-24 16:12:47 +0200935 private boolean populateEcmpRoutingRulePartial(DeviceId targetSw, DeviceId destSw1, DeviceId destSw2,
936 Map<DeviceId, Set<DeviceId>> nextHops, Set<IpPrefix> subnets) {
Saurav Das261c3002017-06-13 15:35:54 -0700937 boolean result;
938 // If both target switch and dest switch are edge routers, then set IP
939 // rule for both subnet and router IP.
940 boolean targetIsEdge;
941 boolean dest1IsEdge;
942 Ip4Address dest1RouterIpv4, dest2RouterIpv4 = null;
943 Ip6Address dest1RouterIpv6, dest2RouterIpv6 = null;
944
945 try {
946 targetIsEdge = config.isEdgeDevice(targetSw);
947 dest1IsEdge = config.isEdgeDevice(destSw1);
948 dest1RouterIpv4 = config.getRouterIpv4(destSw1);
949 dest1RouterIpv6 = config.getRouterIpv6(destSw1);
950 if (destSw2 != null) {
951 dest2RouterIpv4 = config.getRouterIpv4(destSw2);
952 dest2RouterIpv6 = config.getRouterIpv6(destSw2);
953 }
954 } catch (DeviceConfigNotFoundException e) {
955 log.warn(e.getMessage() + " Aborting populateEcmpRoutingRulePartial.");
Saurav Das62ae6792017-05-15 15:34:25 -0700956 return false;
957 }
Saurav Das261c3002017-06-13 15:35:54 -0700958
959 if (targetIsEdge && dest1IsEdge) {
Charles Chan19b70032019-04-17 14:20:26 -0700960 List<Set<IpPrefix>> batchedSubnets;
961 if (subnets != null && !subnets.isEmpty()) {
962 batchedSubnets = Lists.<Set<IpPrefix>>newArrayList(Sets.newHashSet(subnets));
963 } else {
964 batchedSubnets = config.getBatchedSubnets(destSw1);
965 }
Saurav Das97241862018-02-14 14:14:54 -0800966 // XXX - Rethink this - ignoring routerIPs in all other switches
967 // even edge to edge switches
Saurav Das261c3002017-06-13 15:35:54 -0700968 /*subnets.add(dest1RouterIpv4.toIpPrefix());
969 if (dest1RouterIpv6 != null) {
970 subnets.add(dest1RouterIpv6.toIpPrefix());
971 }
972 if (destSw2 != null && dest2RouterIpv4 != null) {
973 subnets.add(dest2RouterIpv4.toIpPrefix());
974 if (dest2RouterIpv6 != null) {
975 subnets.add(dest2RouterIpv6.toIpPrefix());
976 }
977 }*/
Charles Chan19b70032019-04-17 14:20:26 -0700978 log.trace("getSubnets on {}: {}", destSw1, batchedSubnets);
979 for (Set<IpPrefix> prefixes : batchedSubnets) {
980 log.debug(". populateEcmpRoutingRulePartial in device {} towards {} {} "
981 + "for subnets {}", targetSw, destSw1,
982 (destSw2 != null) ? ("& " + destSw2) : "",
983 prefixes);
984 if (!rulePopulator.populateIpRuleForSubnet(targetSw, prefixes, destSw1, destSw2, nextHops)) {
985 return false;
986 }
Saurav Das261c3002017-06-13 15:35:54 -0700987 }
Saurav Das62ae6792017-05-15 15:34:25 -0700988 }
Saurav Das261c3002017-06-13 15:35:54 -0700989
990 if (!targetIsEdge && dest1IsEdge) {
991 // MPLS rules in all non-edge target devices. These rules are for
992 // individual destinations, even if the dsts are part of edge-pairs.
993 log.debug(". populateEcmpRoutingRulePartial in device{} towards {} for "
994 + "all MPLS rules", targetSw, destSw1);
piera9941192019-04-24 16:12:47 +0200995 result = rulePopulator.populateMplsRule(targetSw, destSw1, nextHops.get(destSw1), dest1RouterIpv4);
Saurav Das261c3002017-06-13 15:35:54 -0700996 if (!result) {
997 return false;
998 }
999 if (dest1RouterIpv6 != null) {
Saurav Das97241862018-02-14 14:14:54 -08001000 int v4sid = 0, v6sid = 0;
1001 try {
1002 v4sid = config.getIPv4SegmentId(destSw1);
1003 v6sid = config.getIPv6SegmentId(destSw1);
1004 } catch (DeviceConfigNotFoundException e) {
1005 log.warn(e.getMessage());
1006 }
1007 if (v4sid != v6sid) {
piera9941192019-04-24 16:12:47 +02001008 result = rulePopulator.populateMplsRule(targetSw, destSw1, nextHops.get(destSw1),
Saurav Das97241862018-02-14 14:14:54 -08001009 dest1RouterIpv6);
1010 if (!result) {
1011 return false;
1012 }
Saurav Das261c3002017-06-13 15:35:54 -07001013 }
1014 }
1015 }
1016
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -07001017 if (!targetIsEdge && !dest1IsEdge) {
1018 // MPLS rules for inter-connected spines
1019 // can be merged with above if, left it here for clarity
1020 log.debug(". populateEcmpRoutingRulePartial in device{} towards {} for "
1021 + "all MPLS rules", targetSw, destSw1);
1022
piera9941192019-04-24 16:12:47 +02001023 result = rulePopulator.populateMplsRule(targetSw, destSw1, nextHops.get(destSw1), dest1RouterIpv4);
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -07001024 if (!result) {
1025 return false;
1026 }
1027
1028 if (dest1RouterIpv6 != null) {
1029 int v4sid = 0, v6sid = 0;
1030 try {
1031 v4sid = config.getIPv4SegmentId(destSw1);
1032 v6sid = config.getIPv6SegmentId(destSw1);
1033 } catch (DeviceConfigNotFoundException e) {
1034 log.warn(e.getMessage());
1035 }
1036 if (v4sid != v6sid) {
piera9941192019-04-24 16:12:47 +02001037 result = rulePopulator.populateMplsRule(targetSw, destSw1, nextHops.get(destSw1),
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -07001038 dest1RouterIpv6);
1039 if (!result) {
1040 return false;
1041 }
1042 }
1043 }
1044 }
1045
Saurav Das261c3002017-06-13 15:35:54 -07001046 // To save on ECMP groups
1047 // avoid MPLS rules in non-edge-devices to non-edge-devices
1048 // avoid MPLS transit rules in edge-devices
1049 // avoid loopback IP rules in edge-devices to non-edge-devices
1050 return true;
Saurav Das62ae6792017-05-15 15:34:25 -07001051 }
1052
1053 /**
1054 * Processes a set a route-path changes by editing hash groups.
1055 *
1056 * @param routeChanges a set of route-path changes, where each route-path is
1057 * a list with its first element the src-switch of the path
1058 * and the second element the dst-switch of the path.
1059 * @param linkOrSwitchFailed true if the route changes are for a failed
1060 * switch or linkDown event
1061 * @param failedSwitch the switchId if the route changes are for a failed switch,
1062 * otherwise null
1063 */
1064 private void processHashGroupChange(Set<ArrayList<DeviceId>> routeChanges,
1065 boolean linkOrSwitchFailed,
1066 DeviceId failedSwitch) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001067 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
1068 // first, ensure each routeChanges entry has two elements
Saurav Das62ae6792017-05-15 15:34:25 -07001069 for (ArrayList<DeviceId> route : routeChanges) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001070 if (route.size() == 1) {
1071 // route-path changes are from everyone else to this switch
1072 DeviceId dstSw = route.get(0);
1073 srManager.deviceService.getAvailableDevices().forEach(sw -> {
1074 if (!sw.id().equals(dstSw)) {
1075 changedRoutes.add(Lists.newArrayList(sw.id(), dstSw));
1076 }
1077 });
1078 } else {
1079 changedRoutes.add(route);
Saurav Das62ae6792017-05-15 15:34:25 -07001080 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001081 }
Saurav Das6430f412018-01-25 09:49:01 -08001082 boolean someFailed = false;
1083 Set<DeviceId> updatedDevices = Sets.newHashSet();
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001084 for (ArrayList<DeviceId> route : changedRoutes) {
1085 DeviceId targetSw = route.get(0);
1086 DeviceId dstSw = route.get(1);
Saurav Das62ae6792017-05-15 15:34:25 -07001087 if (linkOrSwitchFailed) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001088 boolean success = fixHashGroupsForRoute(route, true);
Saurav Das62ae6792017-05-15 15:34:25 -07001089 // it's possible that we cannot fix hash groups for a route
1090 // if the target switch has failed. Nevertheless the ecmp graph
1091 // for the impacted switch must still be updated.
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001092 if (!success && failedSwitch != null && targetSw.equals(failedSwitch)) {
Saurav Das62ae6792017-05-15 15:34:25 -07001093 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
1094 currentEcmpSpgMap.remove(targetSw);
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001095 log.debug("Updating ECMPspg for dst:{} removing failed switch "
Saurav Das62ae6792017-05-15 15:34:25 -07001096 + "target:{}", dstSw, targetSw);
Saurav Das6430f412018-01-25 09:49:01 -08001097 updatedDevices.add(targetSw);
1098 updatedDevices.add(dstSw);
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001099 continue;
Saurav Das62ae6792017-05-15 15:34:25 -07001100 }
1101 //linkfailed - update both sides
Saurav Das62ae6792017-05-15 15:34:25 -07001102 if (success) {
1103 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001104 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
Saurav Das6430f412018-01-25 09:49:01 -08001105 log.debug("Updating ECMPspg for dst:{} and target:{} for linkdown"
1106 + " or switchdown", dstSw, targetSw);
1107 updatedDevices.add(targetSw);
1108 updatedDevices.add(dstSw);
1109 } else {
1110 someFailed = true;
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001111 }
1112 } else {
1113 //linkup of seen before link
1114 boolean success = fixHashGroupsForRoute(route, false);
1115 if (success) {
1116 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
1117 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
1118 log.debug("Updating ECMPspg for target:{} and dst:{} for linkup",
Saurav Das62ae6792017-05-15 15:34:25 -07001119 targetSw, dstSw);
Saurav Das6430f412018-01-25 09:49:01 -08001120 updatedDevices.add(targetSw);
1121 updatedDevices.add(dstSw);
1122 } else {
1123 someFailed = true;
Saurav Das62ae6792017-05-15 15:34:25 -07001124 }
1125 }
1126 }
Saurav Das6430f412018-01-25 09:49:01 -08001127 if (!someFailed) {
1128 // here is where we update all devices not touched by this instance
1129 updatedEcmpSpgMap.keySet().stream()
1130 .filter(devId -> !updatedDevices.contains(devId))
1131 .forEach(devId -> {
1132 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
1133 log.debug("Updating ECMPspg for remaining dev:{}", devId);
1134 });
1135 }
Saurav Das62ae6792017-05-15 15:34:25 -07001136 }
1137
1138 /**
1139 * Edits hash groups in the src-switch (targetSw) of a route-path by
1140 * calling the groupHandler to either add or remove buckets in an existing
1141 * hash group.
1142 *
1143 * @param route a single list representing a route-path where the first element
1144 * is the src-switch (targetSw) of the route-path and the
1145 * second element is the dst-switch
1146 * @param revoke true if buckets in the hash-groups need to be removed;
1147 * false if buckets in the hash-groups need to be added
1148 * @return true if the hash group editing is successful
1149 */
1150 private boolean fixHashGroupsForRoute(ArrayList<DeviceId> route,
1151 boolean revoke) {
1152 DeviceId targetSw = route.get(0);
1153 if (route.size() < 2) {
1154 log.warn("Cannot fixHashGroupsForRoute - no dstSw in route {}", route);
1155 return false;
1156 }
1157 DeviceId destSw = route.get(1);
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001158 log.debug("* processing fixHashGroupsForRoute: Target {} -> Dest {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001159 targetSw, destSw);
Saurav Das62ae6792017-05-15 15:34:25 -07001160 // figure out the new next hops at the targetSw towards the destSw
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001161 Set<DeviceId> nextHops = getNextHops(targetSw, destSw);
Saurav Das62ae6792017-05-15 15:34:25 -07001162 // call group handler to change hash group at targetSw
1163 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
1164 if (grpHandler == null) {
1165 log.warn("Cannot find grouphandler for dev:{} .. aborting"
1166 + " {} hash group buckets for route:{} ", targetSw,
1167 (revoke) ? "revoke" : "repopulate", route);
1168 return false;
1169 }
Saurav Das68e1b6a2018-06-11 17:02:31 -07001170 log.debug("{} hash-groups buckets For Route {} -> {} to new next-hops {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001171 (revoke) ? "revoke" : "repopulating",
1172 targetSw, destSw, nextHops);
1173 return (revoke) ? grpHandler.fixHashGroups(targetSw, nextHops,
1174 destSw, true)
1175 : grpHandler.fixHashGroups(targetSw, nextHops,
1176 destSw, false);
1177 }
1178
1179 /**
Saurav Das261c3002017-06-13 15:35:54 -07001180 * Start the flow rule population process if it was never started. The
1181 * process finishes successfully when all flow rules are set and stops with
1182 * ABORTED status when any groups required for flows is not set yet.
Saurav Das62ae6792017-05-15 15:34:25 -07001183 */
Saurav Das261c3002017-06-13 15:35:54 -07001184 public void startPopulationProcess() {
1185 statusLock.lock();
1186 try {
1187 if (populationStatus == Status.IDLE
1188 || populationStatus == Status.SUCCEEDED
1189 || populationStatus == Status.ABORTED) {
1190 populateAllRoutingRules();
sangho28d0b6d2015-05-07 13:30:57 -07001191 } else {
Saurav Das261c3002017-06-13 15:35:54 -07001192 log.warn("Not initiating startPopulationProcess as populationStatus is {}",
1193 populationStatus);
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001194 }
Saurav Das261c3002017-06-13 15:35:54 -07001195 } finally {
1196 statusLock.unlock();
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001197 }
sanghofb7c7292015-04-13 15:15:58 -07001198 }
1199
Saurav Dasb149be12016-06-07 10:08:06 -07001200 /**
Saurav Das261c3002017-06-13 15:35:54 -07001201 * Revoke rules of given subnet in all edge switches.
1202 *
1203 * @param subnets subnet being removed
1204 * @return true if succeed
1205 */
1206 protected boolean revokeSubnet(Set<IpPrefix> subnets) {
piera9941192019-04-24 16:12:47 +02001207 DeviceId targetSw;
1208 List<Future<Boolean>> futures = Lists.newArrayList();
1209 for (Device sw : srManager.deviceService.getAvailableDevices()) {
1210 targetSw = sw.id();
1211 if (shouldProgram(targetSw)) {
1212 futures.add(routePopulators.submit(new RevokeSubnet(targetSw, subnets)));
1213 } else {
1214 futures.add(CompletableFuture.completedFuture(true));
1215 }
1216 }
1217 // check the execution of each job
1218 return checkJobs(futures);
1219 }
1220
1221 private final class RevokeSubnet implements PickyCallable<Boolean> {
1222 private DeviceId targetSw;
1223 private Set<IpPrefix> subnets;
1224
1225 /**
1226 * Builds a RevokeSubnet task, which provides a result.
1227 *
1228 * @param subnets a set of prefixes
1229 * @param targetSw target switch
1230 */
1231 RevokeSubnet(DeviceId targetSw, Set<IpPrefix> subnets) {
1232 this.targetSw = targetSw;
1233 this.subnets = subnets;
1234 }
1235
1236 @Override
1237 public Boolean call() throws Exception {
1238 return srManager.routingRulePopulator.revokeIpRuleForSubnet(targetSw, subnets);
1239 }
1240
1241 @Override
1242 public int hint() {
1243 return targetSw.hashCode();
Saurav Das261c3002017-06-13 15:35:54 -07001244 }
1245 }
1246
1247 /**
Charles Chan910be6a2017-08-23 14:46:43 -07001248 * Populates IP rules for a route that has direct connection to the switch
1249 * if the current instance is the master of the switch.
1250 *
1251 * @param deviceId device ID of the device that next hop attaches to
1252 * @param prefix IP prefix of the route
1253 * @param hostMac MAC address of the next hop
1254 * @param hostVlanId Vlan ID of the nexthop
1255 * @param outPort port where the next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001256 * @param directHost host is of type direct or indirect
Charles Chan910be6a2017-08-23 14:46:43 -07001257 */
1258 void populateRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001259 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Charles Chand66d6712018-03-29 16:03:41 -07001260 if (shouldProgram(deviceId)) {
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001261 srManager.routingRulePopulator.populateRoute(deviceId, prefix, hostMac, hostVlanId, outPort, directHost);
Charles Chan910be6a2017-08-23 14:46:43 -07001262 }
1263 }
1264
1265 /**
1266 * Removes IP rules for a route when the next hop is gone.
1267 * if the current instance is the master of the switch.
1268 *
1269 * @param deviceId device ID of the device that next hop attaches to
1270 * @param prefix IP prefix of the route
1271 * @param hostMac MAC address of the next hop
1272 * @param hostVlanId Vlan ID of the nexthop
1273 * @param outPort port that next hop attaches to
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001274 * @param directHost host is of type direct or indirect
Charles Chan910be6a2017-08-23 14:46:43 -07001275 */
1276 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001277 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort, boolean directHost) {
Charles Chand66d6712018-03-29 16:03:41 -07001278 if (shouldProgram(deviceId)) {
Ruchi Sahota71bcb4e2019-01-28 01:08:18 +00001279 srManager.routingRulePopulator.revokeRoute(deviceId, prefix, hostMac, hostVlanId, outPort, directHost);
Charles Chan910be6a2017-08-23 14:46:43 -07001280 }
1281 }
1282
Charles Chand66d6712018-03-29 16:03:41 -07001283 void populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
1284 if (shouldProgram(deviceId)) {
1285 srManager.routingRulePopulator.populateBridging(deviceId, port, mac, vlanId);
1286 }
1287 }
1288
1289 void revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
1290 if (shouldProgram(deviceId)) {
1291 srManager.routingRulePopulator.revokeBridging(deviceId, port, mac, vlanId);
1292 }
1293 }
1294
1295 void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
1296 VlanId vlanId, boolean popVlan, boolean install) {
1297 if (shouldProgram(deviceId)) {
1298 srManager.routingRulePopulator.updateBridging(deviceId, portNum, hostMac, vlanId, popVlan, install);
1299 }
1300 }
1301
1302 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1303 VlanId vlanId, boolean popVlan, boolean install) {
1304 if (shouldProgram(deviceId)) {
1305 srManager.routingRulePopulator.updateFwdObj(deviceId, portNumber, prefix, hostMac,
1306 vlanId, popVlan, install);
1307 }
1308 }
1309
Charles Chan910be6a2017-08-23 14:46:43 -07001310 /**
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001311 * Populates IP rules for a route when the next hop is double-tagged.
1312 *
1313 * @param deviceId device ID that next hop attaches to
1314 * @param prefix IP prefix of the route
1315 * @param hostMac MAC address of the next hop
1316 * @param innerVlan Inner Vlan ID of the next hop
1317 * @param outerVlan Outer Vlan ID of the next hop
1318 * @param outerTpid Outer TPID of the next hop
1319 * @param outPort port that the next hop attaches to
1320 */
1321 void populateDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId innerVlan,
1322 VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1323 if (srManager.mastershipService.isLocalMaster(deviceId)) {
Charles Chan61c086d2019-07-26 17:46:15 -07001324 srManager.routingRulePopulator.populateDoubleTaggedRoute(
1325 deviceId, prefix, hostMac, innerVlan, outerVlan, outerTpid, outPort);
1326 srManager.routingRulePopulator.processDoubleTaggedFilter(
1327 deviceId, outPort, outerVlan, innerVlan, true);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001328 }
1329 }
1330
1331 /**
1332 * Revokes IP rules for a route when the next hop is double-tagged.
1333 *
1334 * @param deviceId device ID that next hop attaches to
1335 * @param prefix IP prefix of the route
1336 * @param hostMac MAC address of the next hop
1337 * @param innerVlan Inner Vlan ID of the next hop
1338 * @param outerVlan Outer Vlan ID of the next hop
1339 * @param outerTpid Outer TPID of the next hop
1340 * @param outPort port that the next hop attaches to
1341 */
1342 void revokeDoubleTaggedRoute(DeviceId deviceId, IpPrefix prefix, MacAddress hostMac, VlanId innerVlan,
1343 VlanId outerVlan, EthType outerTpid, PortNumber outPort) {
1344 // Revoke route either if this node have the mastership (when device is available) or
1345 // if this node is the leader (even when device is unavailable)
1346 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1347 if (srManager.deviceService.isAvailable(deviceId)) {
1348 // Master node will revoke specified rule.
1349 log.debug("This node is not a master for {}, stop revoking route.", deviceId);
1350 return;
1351 }
1352
1353 // isLocalMaster will return false when the device is unavailable.
1354 // Verify if this node is the leader in that case.
1355 NodeId leader = srManager.leadershipService.runForLeadership(
1356 deviceId.toString()).leaderNodeId();
1357 if (!srManager.clusterService.getLocalNode().id().equals(leader)) {
1358 // Leader node will revoke specified rule.
1359 log.debug("This node is not a master for {}, stop revoking route.", deviceId);
1360 return;
1361 }
1362 }
1363
Charles Chan61c086d2019-07-26 17:46:15 -07001364 srManager.routingRulePopulator.revokeDoubleTaggedRoute(deviceId, prefix, hostMac,
1365 innerVlan, outerVlan, outerTpid, outPort);
1366 srManager.routingRulePopulator.processDoubleTaggedFilter(deviceId, outPort, outerVlan, innerVlan, false);
Jonghwan Hyun9aaa34f2018-04-09 09:40:50 -07001367 }
1368
1369
1370 /**
Saurav Das261c3002017-06-13 15:35:54 -07001371 * Remove ECMP graph entry for the given device. Typically called when
1372 * device is no longer available.
1373 *
1374 * @param deviceId the device for which graphs need to be purged
1375 */
Charles Chanfbcb8812018-04-18 18:41:05 -07001376 void purgeEcmpGraph(DeviceId deviceId) {
Saurav Das6430f412018-01-25 09:49:01 -08001377 statusLock.lock();
1378 try {
Saurav Das6430f412018-01-25 09:49:01 -08001379 if (populationStatus == Status.STARTED) {
1380 log.warn("Previous rule population is not finished. Cannot"
1381 + " proceeed with purgeEcmpGraph for {}", deviceId);
1382 return;
1383 }
1384 log.debug("Updating ECMPspg for unavailable dev:{}", deviceId);
1385 currentEcmpSpgMap.remove(deviceId);
1386 if (updatedEcmpSpgMap != null) {
1387 updatedEcmpSpgMap.remove(deviceId);
1388 }
1389 } finally {
1390 statusLock.unlock();
Saurav Das261c3002017-06-13 15:35:54 -07001391 }
1392 }
1393
Saurav Das00e553b2018-04-21 17:19:48 -07001394 /**
1395 * Attempts a full reroute of route-paths if topology has changed relatively
1396 * close to a mastership change event. Does not do a reroute if mastership
1397 * change is due to reasons other than a ONOS cluster event - for example a
1398 * call to balance-masters, or a switch up/down event.
1399 *
1400 * @param devId the device identifier for which mastership has changed
1401 * @param me the mastership event
1402 */
1403 void checkFullRerouteForMasterChange(DeviceId devId, MastershipEvent me) {
1404 // give small delay to absorb mastership events that are caused by
1405 // device that has disconnected from cluster
Saurav Das49368392018-04-23 18:42:12 -07001406 executorServiceMstChg.schedule(new MasterChange(devId, me),
1407 MASTER_CHANGE_DELAY, TimeUnit.MILLISECONDS);
Saurav Das00e553b2018-04-21 17:19:48 -07001408 }
1409
1410 protected final class MasterChange implements Runnable {
1411 private DeviceId devId;
1412 private MastershipEvent me;
1413 private static final long CLUSTER_EVENT_THRESHOLD = 4500; // ms
1414 private static final long DEVICE_EVENT_THRESHOLD = 2000; // ms
Saurav Dasec683dc2018-04-27 18:42:30 -07001415 private static final long EDGE_PORT_EVENT_THRESHOLD = 10000; //ms
Saurav Das68e1b6a2018-06-11 17:02:31 -07001416 private static final long FULL_REROUTE_THRESHOLD = 10000; // ms
Saurav Das00e553b2018-04-21 17:19:48 -07001417
1418 MasterChange(DeviceId devId, MastershipEvent me) {
1419 this.devId = devId;
1420 this.me = me;
1421 }
1422
1423 @Override
1424 public void run() {
1425 long lce = srManager.clusterListener.timeSinceLastClusterEvent();
1426 boolean clusterEvent = lce < CLUSTER_EVENT_THRESHOLD;
1427
1428 // ignore event for lost switch if cluster event hasn't happened -
1429 // device down event will handle it
1430 if ((me.roleInfo().master() == null
1431 || !srManager.deviceService.isAvailable(devId))
1432 && !clusterEvent) {
1433 log.debug("Full reroute not required for lost device: {}/{} "
1434 + "clusterEvent/timeSince: {}/{}",
1435 devId, me.roleInfo(), clusterEvent, lce);
1436 return;
1437 }
1438
1439 long update = srManager.deviceService.getLastUpdatedInstant(devId);
1440 long lde = Instant.now().toEpochMilli() - update;
1441 boolean deviceEvent = lde < DEVICE_EVENT_THRESHOLD;
1442
1443 // ignore event for recently connected switch if cluster event hasn't
1444 // happened - link up events will handle it
1445 if (srManager.deviceService.isAvailable(devId) && deviceEvent
1446 && !clusterEvent) {
1447 log.debug("Full reroute not required for recently available"
1448 + " device: {}/{} deviceEvent/timeSince: {}/{} "
1449 + "clusterEvent/timeSince: {}/{}",
1450 devId, me.roleInfo(), deviceEvent, lde, clusterEvent, lce);
1451 return;
1452 }
1453
Saurav Dasec683dc2018-04-27 18:42:30 -07001454 long lepe = Instant.now().toEpochMilli()
1455 - srManager.lastEdgePortEvent.toEpochMilli();
1456 boolean edgePortEvent = lepe < EDGE_PORT_EVENT_THRESHOLD;
1457
Saurav Das00e553b2018-04-21 17:19:48 -07001458 // if it gets here, then mastership change is likely due to onos
1459 // instance failure, or network partition in onos cluster
1460 // normally a mastership change like this does not require re-programming
1461 // but if topology changes happen at the same time then we may miss events
1462 if (!isRoutingStable() && clusterEvent) {
Saurav Dasec683dc2018-04-27 18:42:30 -07001463 log.warn("Mastership changed for dev: {}/{} while programming route-paths "
Saurav Das00e553b2018-04-21 17:19:48 -07001464 + "due to clusterEvent {} ms ago .. attempting full reroute",
1465 devId, me.roleInfo(), lce);
1466 if (srManager.mastershipService.isLocalMaster(devId)) {
1467 // old master could have died when populating filters
1468 populatePortAddressingRules(devId);
1469 }
Saurav Das68e1b6a2018-06-11 17:02:31 -07001470 // old master could have died when creating groups
Saurav Das00e553b2018-04-21 17:19:48 -07001471 // XXX right now we have no fine-grained way to only make changes
Saurav Das68e1b6a2018-06-11 17:02:31 -07001472 // for the route paths affected by this device. Thus we do a
1473 // full reroute after purging all hash groups. We also try to do
1474 // it only once, irrespective of the number of devices
1475 // that changed mastership when their master instance died.
1476 long lfrr = Instant.now().toEpochMilli() - lastFullReroute.toEpochMilli();
1477 boolean doFullReroute = lfrr > FULL_REROUTE_THRESHOLD;
1478 if (doFullReroute) {
1479 lastFullReroute = Instant.now();
1480 for (Device dev : srManager.deviceService.getDevices()) {
1481 if (shouldProgram(dev.id())) {
1482 srManager.purgeHashedNextObjectiveStore(dev.id());
1483 }
1484 }
1485 // give small delay to ensure entire store is purged
1486 executorServiceFRR.schedule(new FullRerouteAfterPurge(),
1487 PURGE_DELAY,
1488 TimeUnit.MILLISECONDS);
1489 } else {
1490 log.warn("Full reroute attempted {} ms ago .. skipping", lfrr);
1491 }
Saurav Dasec683dc2018-04-27 18:42:30 -07001492
1493 } else if (edgePortEvent && clusterEvent) {
1494 log.warn("Mastership changed for dev: {}/{} due to clusterEvent {} ms ago "
1495 + "while edge-port event happened {} ms ago "
1496 + " .. reprogramming all edge-ports",
1497 devId, me.roleInfo(), lce, lepe);
1498 if (shouldProgram(devId)) {
1499 srManager.deviceService.getPorts(devId).stream()
1500 .filter(p -> srManager.interfaceService
1501 .isConfigured(new ConnectPoint(devId, p.number())))
1502 .forEach(p -> srManager.processPortUpdated(devId, p));
1503 }
1504
Saurav Das00e553b2018-04-21 17:19:48 -07001505 } else {
1506 log.debug("Stable route-paths .. full reroute not attempted for "
1507 + "mastership change {}/{} deviceEvent/timeSince: {}/{} "
1508 + "clusterEvent/timeSince: {}/{}", devId, me.roleInfo(),
1509 deviceEvent, lde, clusterEvent, lce);
1510 }
1511 }
1512 }
1513
Saurav Das68e1b6a2018-06-11 17:02:31 -07001514 /**
1515 * Performs a full reroute of routing rules in all the switches. Assumes
1516 * caller has purged hash groups from the nextObjective store, otherwise
1517 * re-uses ones available in the store.
1518 */
1519 protected final class FullRerouteAfterPurge implements Runnable {
1520 @Override
1521 public void run() {
1522 populateAllRoutingRules();
1523 }
1524 }
1525
1526
Saurav Das261c3002017-06-13 15:35:54 -07001527 //////////////////////////////////////
1528 // Routing helper methods and classes
1529 //////////////////////////////////////
1530
1531 /**
Saurav Das68e1b6a2018-06-11 17:02:31 -07001532 * Computes set of affected routes due to failed link. Assumes previous ecmp
1533 * shortest-path graph exists for a switch in order to compute affected
1534 * routes. If such a graph does not exist, the method returns null.
Saurav Dasb149be12016-06-07 10:08:06 -07001535 *
1536 * @param linkFail the failed link
1537 * @return the set of affected routes which may be empty if no routes were
Saurav Das68e1b6a2018-06-11 17:02:31 -07001538 * affected
Saurav Dasb149be12016-06-07 10:08:06 -07001539 */
sanghofb7c7292015-04-13 15:15:58 -07001540 private Set<ArrayList<DeviceId>> computeDamagedRoutes(Link linkFail) {
sanghofb7c7292015-04-13 15:15:58 -07001541 Set<ArrayList<DeviceId>> routes = new HashSet<>();
1542
1543 for (Device sw : srManager.deviceService.getDevices()) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001544 log.debug("Computing the impacted routes for device {} due to link fail",
1545 sw.id());
Charles Chand66d6712018-03-29 16:03:41 -07001546 if (!shouldProgram(sw.id())) {
Saurav Das00e553b2018-04-21 17:19:48 -07001547 lastProgrammed.remove(sw.id());
sanghofb7c7292015-04-13 15:15:58 -07001548 continue;
1549 }
Charles Chand66d6712018-03-29 16:03:41 -07001550 for (DeviceId rootSw : deviceAndItsPair(sw.id())) {
Saurav Das00e553b2018-04-21 17:19:48 -07001551 // check for mastership change since last run
1552 if (!lastProgrammed.contains(sw.id())) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001553 log.warn("New responsibility for this node to program dev:{}"
Saurav Das00e553b2018-04-21 17:19:48 -07001554 + " ... nuking current ECMPspg", sw.id());
1555 currentEcmpSpgMap.remove(sw.id());
1556 }
Saurav Das68e1b6a2018-06-11 17:02:31 -07001557 lastProgrammed.add(sw.id());
1558
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001559 EcmpShortestPathGraph ecmpSpg = currentEcmpSpgMap.get(rootSw);
1560 if (ecmpSpg == null) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001561 log.warn("No existing ECMP graph for switch {}. Assuming "
1562 + "all route-paths have changed towards it.", rootSw);
1563 for (DeviceId targetSw : srManager.deviceConfiguration.getRouters()) {
1564 if (targetSw.equals(rootSw)) {
1565 continue;
1566 }
1567 routes.add(Lists.newArrayList(targetSw, rootSw));
1568 log.debug("Impacted route:{}->{}", targetSw, rootSw);
1569 }
1570 continue;
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001571 }
Saurav Das68e1b6a2018-06-11 17:02:31 -07001572
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001573 if (log.isDebugEnabled()) {
1574 log.debug("Root switch: {}", rootSw);
1575 log.debug(" Current/Existing SPG: {}", ecmpSpg);
1576 log.debug(" New/Updated SPG: {}", updatedEcmpSpgMap.get(rootSw));
1577 }
1578 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>>
1579 switchVia = ecmpSpg.getAllLearnedSwitchesAndVia();
1580 // figure out if the broken link affected any route-paths in this graph
1581 for (Integer itrIdx : switchVia.keySet()) {
1582 log.trace("Current/Exiting SPG Iterindex# {}", itrIdx);
1583 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1584 switchVia.get(itrIdx);
1585 for (DeviceId targetSw : swViaMap.keySet()) {
1586 log.trace("TargetSwitch {} --> RootSwitch {}",
1587 targetSw, rootSw);
Saurav Dasb149be12016-06-07 10:08:06 -07001588 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1589 log.trace(" Via:");
Pier Ventreadb4ae62016-11-23 09:57:42 -08001590 via.forEach(e -> log.trace(" {}", e));
Saurav Dasb149be12016-06-07 10:08:06 -07001591 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001592 Set<ArrayList<DeviceId>> subLinks =
1593 computeLinks(targetSw, rootSw, swViaMap);
1594 for (ArrayList<DeviceId> alink: subLinks) {
1595 if ((alink.get(0).equals(linkFail.src().deviceId()) &&
1596 alink.get(1).equals(linkFail.dst().deviceId()))
1597 ||
1598 (alink.get(0).equals(linkFail.dst().deviceId()) &&
1599 alink.get(1).equals(linkFail.src().deviceId()))) {
1600 log.debug("Impacted route:{}->{}", targetSw, rootSw);
1601 ArrayList<DeviceId> aRoute = new ArrayList<>();
1602 aRoute.add(targetSw); // switch with rules to populate
1603 aRoute.add(rootSw); // towards this destination
1604 routes.add(aRoute);
1605 break;
1606 }
sanghofb7c7292015-04-13 15:15:58 -07001607 }
1608 }
1609 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001610
sanghofb7c7292015-04-13 15:15:58 -07001611 }
sangho28d0b6d2015-05-07 13:30:57 -07001612
sanghofb7c7292015-04-13 15:15:58 -07001613 }
sanghofb7c7292015-04-13 15:15:58 -07001614 return routes;
1615 }
1616
Saurav Das1b391d52016-11-29 14:27:25 -08001617 /**
1618 * Computes set of affected routes due to new links or failed switches.
1619 *
Saurav Dasdc7f2752018-03-18 21:28:15 -07001620 * @param failedSwitch deviceId of failed switch if any
Saurav Das1b391d52016-11-29 14:27:25 -08001621 * @return the set of affected routes which may be empty if no routes were
1622 * affected
1623 */
Saurav Dascea556f2018-03-05 14:37:16 -08001624 private Set<ArrayList<DeviceId>> computeRouteChange(DeviceId failedSwitch) {
Saurav Das261c3002017-06-13 15:35:54 -07001625 ImmutableSet.Builder<ArrayList<DeviceId>> changedRtBldr =
Saurav Das1b391d52016-11-29 14:27:25 -08001626 ImmutableSet.builder();
sanghofb7c7292015-04-13 15:15:58 -07001627
1628 for (Device sw : srManager.deviceService.getDevices()) {
Saurav Das261c3002017-06-13 15:35:54 -07001629 log.debug("Computing the impacted routes for device {}", sw.id());
Charles Chand66d6712018-03-29 16:03:41 -07001630 if (!shouldProgram(sw.id())) {
Saurav Das00e553b2018-04-21 17:19:48 -07001631 lastProgrammed.remove(sw.id());
sanghofb7c7292015-04-13 15:15:58 -07001632 continue;
1633 }
Charles Chand66d6712018-03-29 16:03:41 -07001634 for (DeviceId rootSw : deviceAndItsPair(sw.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001635 if (log.isTraceEnabled()) {
1636 log.trace("Device links for dev: {}", rootSw);
1637 for (Link link: srManager.linkService.getDeviceLinks(rootSw)) {
1638 log.trace("{} -> {} ", link.src().deviceId(),
1639 link.dst().deviceId());
1640 }
Saurav Dasb149be12016-06-07 10:08:06 -07001641 }
Saurav Das00e553b2018-04-21 17:19:48 -07001642 // check for mastership change since last run
1643 if (!lastProgrammed.contains(sw.id())) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001644 log.warn("New responsibility for this node to program dev:{}"
Saurav Das00e553b2018-04-21 17:19:48 -07001645 + " ... nuking current ECMPspg", sw.id());
1646 currentEcmpSpgMap.remove(sw.id());
1647 }
Saurav Das68e1b6a2018-06-11 17:02:31 -07001648 lastProgrammed.add(sw.id());
Saurav Das261c3002017-06-13 15:35:54 -07001649 EcmpShortestPathGraph currEcmpSpg = currentEcmpSpgMap.get(rootSw);
1650 if (currEcmpSpg == null) {
1651 log.debug("No existing ECMP graph for device {}.. adding self as "
1652 + "changed route", rootSw);
1653 changedRtBldr.add(Lists.newArrayList(rootSw));
1654 continue;
1655 }
1656 EcmpShortestPathGraph newEcmpSpg = updatedEcmpSpgMap.get(rootSw);
Saurav Dasdebcf882018-04-06 20:16:01 -07001657 if (newEcmpSpg == null) {
1658 log.warn("Cannot find updated ECMP graph for dev:{}", rootSw);
1659 continue;
1660 }
Saurav Das261c3002017-06-13 15:35:54 -07001661 if (log.isDebugEnabled()) {
1662 log.debug("Root switch: {}", rootSw);
1663 log.debug(" Current/Existing SPG: {}", currEcmpSpg);
1664 log.debug(" New/Updated SPG: {}", newEcmpSpg);
1665 }
1666 // first use the updated/new map to compare to current/existing map
1667 // as new links may have come up
1668 changedRtBldr.addAll(compareGraphs(newEcmpSpg, currEcmpSpg, rootSw));
1669 // then use the current/existing map to compare to updated/new map
1670 // as switch may have been removed
1671 changedRtBldr.addAll(compareGraphs(currEcmpSpg, newEcmpSpg, rootSw));
sangho28d0b6d2015-05-07 13:30:57 -07001672 }
Saurav Das1b391d52016-11-29 14:27:25 -08001673 }
sanghofb7c7292015-04-13 15:15:58 -07001674
Saurav Dascea556f2018-03-05 14:37:16 -08001675 // handle clearing state for a failed switch in case the switch does
1676 // not have a pair, or the pair is not available
1677 if (failedSwitch != null) {
Charles Chan6dbcd252018-04-02 11:46:38 -07001678 Optional<DeviceId> pairDev = srManager.getPairDeviceId(failedSwitch);
1679 if (!pairDev.isPresent() || !srManager.deviceService.isAvailable(pairDev.get())) {
Saurav Dascea556f2018-03-05 14:37:16 -08001680 log.debug("Proxy Route changes to downed Sw:{}", failedSwitch);
1681 srManager.deviceService.getDevices().forEach(dev -> {
1682 if (!dev.id().equals(failedSwitch) &&
1683 srManager.mastershipService.isLocalMaster(dev.id())) {
1684 log.debug(" : {}", dev.id());
1685 changedRtBldr.add(Lists.newArrayList(dev.id(), failedSwitch));
1686 }
1687 });
1688 }
1689 }
1690
Saurav Das261c3002017-06-13 15:35:54 -07001691 Set<ArrayList<DeviceId>> changedRoutes = changedRtBldr.build();
Saurav Das1b391d52016-11-29 14:27:25 -08001692 for (ArrayList<DeviceId> route: changedRoutes) {
1693 log.debug("Route changes Target -> Root");
1694 if (route.size() == 1) {
1695 log.debug(" : all -> {}", route.get(0));
1696 } else {
1697 log.debug(" : {} -> {}", route.get(0), route.get(1));
1698 }
1699 }
1700 return changedRoutes;
1701 }
1702
1703 /**
1704 * For the root switch, searches all the target nodes reachable in the base
1705 * graph, and compares paths to the ones in the comp graph.
1706 *
1707 * @param base the graph that is indexed for all reachable target nodes
1708 * from the root node
1709 * @param comp the graph that the base graph is compared to
1710 * @param rootSw both ecmp graphs are calculated for the root node
1711 * @return all the routes that have changed in the base graph
1712 */
1713 private Set<ArrayList<DeviceId>> compareGraphs(EcmpShortestPathGraph base,
1714 EcmpShortestPathGraph comp,
1715 DeviceId rootSw) {
1716 ImmutableSet.Builder<ArrayList<DeviceId>> changedRoutesBuilder =
1717 ImmutableSet.builder();
1718 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> baseMap =
1719 base.getAllLearnedSwitchesAndVia();
1720 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> compMap =
1721 comp.getAllLearnedSwitchesAndVia();
1722 for (Integer itrIdx : baseMap.keySet()) {
1723 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> baseViaMap =
1724 baseMap.get(itrIdx);
1725 for (DeviceId targetSw : baseViaMap.keySet()) {
1726 ArrayList<ArrayList<DeviceId>> basePath = baseViaMap.get(targetSw);
1727 ArrayList<ArrayList<DeviceId>> compPath = getVia(compMap, targetSw);
1728 if ((compPath == null) || !basePath.equals(compPath)) {
Saurav Das62ae6792017-05-15 15:34:25 -07001729 log.trace("Impacted route:{} -> {}", targetSw, rootSw);
Saurav Das1b391d52016-11-29 14:27:25 -08001730 ArrayList<DeviceId> route = new ArrayList<>();
Saurav Das261c3002017-06-13 15:35:54 -07001731 route.add(targetSw); // switch with rules to populate
1732 route.add(rootSw); // towards this destination
Saurav Das1b391d52016-11-29 14:27:25 -08001733 changedRoutesBuilder.add(route);
sanghofb7c7292015-04-13 15:15:58 -07001734 }
1735 }
sangho28d0b6d2015-05-07 13:30:57 -07001736 }
Saurav Das1b391d52016-11-29 14:27:25 -08001737 return changedRoutesBuilder.build();
sanghofb7c7292015-04-13 15:15:58 -07001738 }
1739
Saurav Das261c3002017-06-13 15:35:54 -07001740 /**
1741 * Returns the ECMP paths traversed to reach the target switch.
1742 *
1743 * @param switchVia a per-iteration view of the ECMP graph for a root switch
1744 * @param targetSw the switch to reach from the root switch
1745 * @return the nodes traversed on ECMP paths to the target switch
1746 */
sanghofb7c7292015-04-13 15:15:58 -07001747 private ArrayList<ArrayList<DeviceId>> getVia(HashMap<Integer, HashMap<DeviceId,
Saurav Das1b391d52016-11-29 14:27:25 -08001748 ArrayList<ArrayList<DeviceId>>>> switchVia, DeviceId targetSw) {
sanghofb7c7292015-04-13 15:15:58 -07001749 for (Integer itrIdx : switchVia.keySet()) {
1750 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1751 switchVia.get(itrIdx);
Saurav Das1b391d52016-11-29 14:27:25 -08001752 if (swViaMap.get(targetSw) == null) {
sanghofb7c7292015-04-13 15:15:58 -07001753 continue;
1754 } else {
Saurav Das1b391d52016-11-29 14:27:25 -08001755 return swViaMap.get(targetSw);
sanghofb7c7292015-04-13 15:15:58 -07001756 }
1757 }
1758
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001759 return null;
sanghofb7c7292015-04-13 15:15:58 -07001760 }
1761
Saurav Das261c3002017-06-13 15:35:54 -07001762 /**
1763 * Utility method to break down a path from src to dst device into a collection
1764 * of links.
1765 *
1766 * @param src src device of the path
1767 * @param dst dst device of the path
1768 * @param viaMap path taken from src to dst device
1769 * @return collection of links in the path
1770 */
sanghofb7c7292015-04-13 15:15:58 -07001771 private Set<ArrayList<DeviceId>> computeLinks(DeviceId src,
1772 DeviceId dst,
1773 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> viaMap) {
1774 Set<ArrayList<DeviceId>> subLinks = Sets.newHashSet();
1775 for (ArrayList<DeviceId> via : viaMap.get(src)) {
1776 DeviceId linkSrc = src;
1777 DeviceId linkDst = dst;
1778 for (DeviceId viaDevice: via) {
1779 ArrayList<DeviceId> link = new ArrayList<>();
1780 linkDst = viaDevice;
1781 link.add(linkSrc);
1782 link.add(linkDst);
1783 subLinks.add(link);
1784 linkSrc = viaDevice;
1785 }
1786 ArrayList<DeviceId> link = new ArrayList<>();
1787 link.add(linkSrc);
1788 link.add(dst);
1789 subLinks.add(link);
1790 }
1791
1792 return subLinks;
1793 }
1794
Charles Chanc22cef32016-04-29 14:38:22 -07001795 /**
Charles Chand66d6712018-03-29 16:03:41 -07001796 * Determines whether this controller instance should program the
Saurav Das261c3002017-06-13 15:35:54 -07001797 * given {@code deviceId}, based on mastership and pairDeviceId if one exists.
Charles Chand66d6712018-03-29 16:03:41 -07001798 * <p>
1799 * Once an instance is elected, it will be the only instance responsible for programming
1800 * both devices in the pair until it goes down.
Charles Chanc22cef32016-04-29 14:38:22 -07001801 *
Saurav Das261c3002017-06-13 15:35:54 -07001802 * @param deviceId device identifier to consider for routing
Charles Chand66d6712018-03-29 16:03:41 -07001803 * @return true if current instance should handle the routing for given device
Charles Chanc22cef32016-04-29 14:38:22 -07001804 */
Charles Chand66d6712018-03-29 16:03:41 -07001805 boolean shouldProgram(DeviceId deviceId) {
Charles Chanfbcb8812018-04-18 18:41:05 -07001806 Boolean cached = shouldProgramCache.get(deviceId);
1807 if (cached != null) {
Saurav Das00e553b2018-04-21 17:19:48 -07001808 log.debug("shouldProgram dev:{} cached:{}", deviceId, cached);
Charles Chanfbcb8812018-04-18 18:41:05 -07001809 return cached;
1810 }
1811
Charles Chand66d6712018-03-29 16:03:41 -07001812 Optional<DeviceId> pairDeviceId = srManager.getPairDeviceId(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001813
Charles Chand66d6712018-03-29 16:03:41 -07001814 NodeId currentNodeId = srManager.clusterService.getLocalNode().id();
1815 NodeId masterNodeId = srManager.mastershipService.getMasterFor(deviceId);
1816 Optional<NodeId> pairMasterNodeId = pairDeviceId.map(srManager.mastershipService::getMasterFor);
Saurav Das68e1b6a2018-06-11 17:02:31 -07001817 log.debug("Evaluate shouldProgram {}/pair={}. currentNodeId={}, master={}, pairMaster={}",
Charles Chand66d6712018-03-29 16:03:41 -07001818 deviceId, pairDeviceId, currentNodeId, masterNodeId, pairMasterNodeId);
1819
1820 // No pair device configured. Only handle when current instance is the master of the device
1821 if (!pairDeviceId.isPresent()) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001822 log.debug("No pair device. currentNodeId={}, master={}", currentNodeId, masterNodeId);
Charles Chand66d6712018-03-29 16:03:41 -07001823 return currentNodeId.equals(masterNodeId);
sangho80f11cb2015-04-01 13:05:26 -07001824 }
Charles Chand66d6712018-03-29 16:03:41 -07001825
1826 // Should not handle if current instance is not the master of either switch
1827 if (!currentNodeId.equals(masterNodeId) &&
1828 !(pairMasterNodeId.isPresent() && currentNodeId.equals(pairMasterNodeId.get()))) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001829 log.debug("Current nodeId {} is neither the master of target device {} nor pair device {}",
Charles Chand66d6712018-03-29 16:03:41 -07001830 currentNodeId, deviceId, pairDeviceId);
1831 return false;
1832 }
1833
1834 Set<DeviceId> key = Sets.newHashSet(deviceId, pairDeviceId.get());
1835
1836 NodeId king = shouldProgram.compute(key, ((k, v) -> {
1837 if (v == null) {
1838 // There is no value in the map. Elect a node
1839 return elect(Lists.newArrayList(masterNodeId, pairMasterNodeId.orElse(null)));
1840 } else {
1841 if (v.equals(masterNodeId) || v.equals(pairMasterNodeId.orElse(null))) {
1842 // Use the node in the map if it is still alive and is a master of any of the two switches
1843 return v;
1844 } else {
1845 // Previously elected node is no longer the master of either switch. Re-elect a node.
1846 return elect(Lists.newArrayList(masterNodeId, pairMasterNodeId.orElse(null)));
1847 }
1848 }
1849 }));
1850
1851 if (king != null) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001852 log.debug("{} is king, should handle routing for {}/pair={}", king, deviceId, pairDeviceId);
Charles Chanfbcb8812018-04-18 18:41:05 -07001853 shouldProgramCache.put(deviceId, king.equals(currentNodeId));
Charles Chand66d6712018-03-29 16:03:41 -07001854 return king.equals(currentNodeId);
1855 } else {
1856 log.error("Fail to elect a king for {}/pair={}. Abort.", deviceId, pairDeviceId);
Charles Chanfbcb8812018-04-18 18:41:05 -07001857 shouldProgramCache.remove(deviceId);
Charles Chand66d6712018-03-29 16:03:41 -07001858 return false;
1859 }
1860 }
1861
1862 /**
1863 * Elects a node who should take responsibility of programming devices.
1864 * @param nodeIds list of candidate node ID
1865 *
1866 * @return NodeId of the node that gets elected, or null if none of the node can be elected
1867 */
1868 private NodeId elect(List<NodeId> nodeIds) {
1869 // Remove all null elements. This could happen when some device has no master
1870 nodeIds.removeAll(Collections.singleton(null));
1871 nodeIds.sort(null);
1872 return nodeIds.size() == 0 ? null : nodeIds.get(0);
1873 }
1874
Charles Chanfbcb8812018-04-18 18:41:05 -07001875 void invalidateShouldProgramCache(DeviceId deviceId) {
1876 shouldProgramCache.remove(deviceId);
1877 }
1878
Charles Chand66d6712018-03-29 16:03:41 -07001879 /**
1880 * Returns a set of device ID, containing given device and its pair device if exist.
1881 *
1882 * @param deviceId Device ID
1883 * @return a set of device ID, containing given device and its pair device if exist.
1884 */
1885 private Set<DeviceId> deviceAndItsPair(DeviceId deviceId) {
1886 Set<DeviceId> ret = Sets.newHashSet(deviceId);
1887 srManager.getPairDeviceId(deviceId).ifPresent(ret::add);
1888 return ret;
sangho80f11cb2015-04-01 13:05:26 -07001889 }
1890
Charles Chanc22cef32016-04-29 14:38:22 -07001891 /**
Saurav Das261c3002017-06-13 15:35:54 -07001892 * Returns the set of deviceIds which are the next hops from the targetSw
1893 * to the dstSw according to the latest ECMP spg.
1894 *
1895 * @param targetSw the switch for which the next-hops are desired
1896 * @param dstSw the switch to which the next-hops lead to from the targetSw
1897 * @return set of next hop deviceIds, could be empty if no next hops are found
1898 */
1899 private Set<DeviceId> getNextHops(DeviceId targetSw, DeviceId dstSw) {
1900 boolean targetIsEdge = false;
1901 try {
1902 targetIsEdge = srManager.deviceConfiguration.isEdgeDevice(targetSw);
1903 } catch (DeviceConfigNotFoundException e) {
1904 log.warn(e.getMessage() + "Cannot determine if targetIsEdge {}.. "
1905 + "continuing to getNextHops", targetSw);
1906 }
1907
1908 EcmpShortestPathGraph ecmpSpg = updatedEcmpSpgMap.get(dstSw);
1909 if (ecmpSpg == null) {
1910 log.debug("No ecmpSpg found for dstSw: {}", dstSw);
1911 return ImmutableSet.of();
1912 }
1913 HashMap<Integer,
1914 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> switchVia =
1915 ecmpSpg.getAllLearnedSwitchesAndVia();
1916 for (Integer itrIdx : switchVia.keySet()) {
1917 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1918 switchVia.get(itrIdx);
1919 for (DeviceId target : swViaMap.keySet()) {
1920 if (!target.equals(targetSw)) {
1921 continue;
1922 }
Saurav Das49368392018-04-23 18:42:12 -07001923 // optimization for spines to not use leaves to get
1924 // to a spine or other leaves. Also leaves should not use other
1925 // leaves to get to the destination
1926 if ((!targetIsEdge && itrIdx > 1) || targetIsEdge) {
Saurav Das97241862018-02-14 14:14:54 -08001927 boolean pathdevIsEdge = false;
1928 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
Saurav Das49368392018-04-23 18:42:12 -07001929 log.debug("Evaluating next-hop in path: {}", via);
Saurav Das97241862018-02-14 14:14:54 -08001930 for (DeviceId pathdev : via) {
1931 try {
1932 pathdevIsEdge = srManager.deviceConfiguration
1933 .isEdgeDevice(pathdev);
1934 } catch (DeviceConfigNotFoundException e) {
1935 log.warn(e.getMessage());
1936 }
1937 if (pathdevIsEdge) {
Saurav Das68e1b6a2018-06-11 17:02:31 -07001938 log.debug("Avoiding {} hop path for targetSw:{}"
Saurav Das97241862018-02-14 14:14:54 -08001939 + " --> dstSw:{} which goes through an edge"
1940 + " device {} in path {}", itrIdx,
1941 targetSw, dstSw, pathdev, via);
1942 return ImmutableSet.of();
1943 }
1944 }
1945 }
Saurav Das261c3002017-06-13 15:35:54 -07001946 }
1947 Set<DeviceId> nextHops = new HashSet<>();
1948 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1949 if (via.isEmpty()) {
1950 // the dstSw is the next-hop from the targetSw
1951 nextHops.add(dstSw);
1952 } else {
1953 // first elem is next-hop in each ECMP path
1954 nextHops.add(via.get(0));
1955 }
1956 }
Saurav Das49368392018-04-23 18:42:12 -07001957 log.debug("target {} --> dst: {} has next-hops:{}", targetSw,
1958 dstSw, nextHops);
Saurav Das261c3002017-06-13 15:35:54 -07001959 return nextHops;
1960 }
1961 }
Saurav Das49368392018-04-23 18:42:12 -07001962 log.debug("No next hops found for target:{} --> dst: {}", targetSw, dstSw);
Saurav Das261c3002017-06-13 15:35:54 -07001963 return ImmutableSet.of(); //no next-hops found
1964 }
1965
Saurav Das261c3002017-06-13 15:35:54 -07001966 //////////////////////////////////////
1967 // Filtering rule creation
1968 //////////////////////////////////////
1969
1970 /**
Saurav Dasf9332192017-02-18 14:05:44 -08001971 * Populates filtering rules for port, and punting rules
1972 * for gateway IPs, loopback IPs and arp/ndp traffic.
1973 * Should only be called by the master instance for this device/port.
sangho80f11cb2015-04-01 13:05:26 -07001974 *
1975 * @param deviceId Switch ID to set the rules
1976 */
Charles Chanfbcb8812018-04-18 18:41:05 -07001977 void populatePortAddressingRules(DeviceId deviceId) {
Saurav Das07c74602016-04-27 18:35:50 -07001978 // Although device is added, sometimes device store does not have the
1979 // ports for this device yet. It results in missing filtering rules in the
1980 // switch. We will attempt it a few times. If it still does not work,
1981 // user can manually repopulate using CLI command sr-reroute-network
Charles Chan18fa4252017-02-08 16:10:40 -08001982 PortFilterInfo firstRun = rulePopulator.populateVlanMacFilters(deviceId);
Saurav Dasd1872b02016-12-02 15:43:47 -08001983 if (firstRun == null) {
1984 firstRun = new PortFilterInfo(0, 0, 0);
Saurav Das07c74602016-04-27 18:35:50 -07001985 }
Saurav Dasd1872b02016-12-02 15:43:47 -08001986 executorService.schedule(new RetryFilters(deviceId, firstRun),
1987 RETRY_INTERVAL_MS, TimeUnit.MILLISECONDS);
sangho80f11cb2015-04-01 13:05:26 -07001988 }
1989
1990 /**
Saurav Dasd1872b02016-12-02 15:43:47 -08001991 * RetryFilters populates filtering objectives for a device and keeps retrying
1992 * till the number of ports filtered are constant for a predefined number
1993 * of attempts.
1994 */
1995 protected final class RetryFilters implements Runnable {
1996 int constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS;
1997 DeviceId devId;
1998 int counter;
1999 PortFilterInfo prevRun;
2000
2001 private RetryFilters(DeviceId deviceId, PortFilterInfo previousRun) {
Saurav Das07c74602016-04-27 18:35:50 -07002002 devId = deviceId;
Saurav Dasd1872b02016-12-02 15:43:47 -08002003 prevRun = previousRun;
2004 counter = 0;
Saurav Das07c74602016-04-27 18:35:50 -07002005 }
2006
2007 @Override
2008 public void run() {
Charles Chan077314e2017-06-22 14:27:17 -07002009 log.debug("RETRY FILTER ATTEMPT {} ** dev:{}", ++counter, devId);
Charles Chan18fa4252017-02-08 16:10:40 -08002010 PortFilterInfo thisRun = rulePopulator.populateVlanMacFilters(devId);
Saurav Dasd1872b02016-12-02 15:43:47 -08002011 boolean sameResult = prevRun.equals(thisRun);
2012 log.debug("dev:{} prevRun:{} thisRun:{} sameResult:{}", devId, prevRun,
2013 thisRun, sameResult);
Ray Milkey614352e2018-02-26 09:36:31 -08002014 if (thisRun == null || !sameResult || (--constantAttempts > 0)) {
Saurav Dasf9332192017-02-18 14:05:44 -08002015 // exponentially increasing intervals for retries
2016 executorService.schedule(this,
2017 RETRY_INTERVAL_MS * (int) Math.pow(counter, RETRY_INTERVAL_SCALE),
2018 TimeUnit.MILLISECONDS);
Saurav Dasd1872b02016-12-02 15:43:47 -08002019 if (!sameResult) {
2020 constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS; //reset
2021 }
Saurav Das07c74602016-04-27 18:35:50 -07002022 }
Saurav Dasd1872b02016-12-02 15:43:47 -08002023 prevRun = (thisRun == null) ? prevRun : thisRun;
Saurav Das07c74602016-04-27 18:35:50 -07002024 }
Saurav Das07c74602016-04-27 18:35:50 -07002025 }
piera9941192019-04-24 16:12:47 +02002026
2027 // Check jobs completion. It returns false if one of the job fails
2028 // and cancel the remaining
2029 private boolean checkJobs(List<Future<Boolean>> futures) {
2030 boolean completed = true;
2031 for (Future<Boolean> future : futures) {
2032 try {
2033 if (completed) {
2034 if (!future.get()) {
2035 completed = false;
2036 }
2037 } else {
2038 future.cancel(true);
2039 }
2040 } catch (InterruptedException | ExecutionException e) {
2041 completed = false;
2042 }
2043 }
2044 return completed;
2045 }
sangho80f11cb2015-04-01 13:05:26 -07002046}