blob: 5baa6a94f39645e6c29f4c5a63306502fffbf42b [file] [log] [blame]
sanghob35a6192015-04-01 13:05:26 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sanghob35a6192015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Saurav Dasd2fded02016-12-02 15:43:47 -080018import com.google.common.base.MoreObjects;
Saurav Dasc88d4662017-05-15 15:34:25 -070019import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.ImmutableMap.Builder;
Charles Chan93e71ba2016-04-29 14:38:22 -070021import com.google.common.collect.ImmutableSet;
Saurav Das4e3224f2016-11-29 14:27:25 -080022import com.google.common.collect.Lists;
sangho20eff1d2015-04-13 15:15:58 -070023import com.google.common.collect.Maps;
24import com.google.common.collect.Sets;
Saurav Dasceccf242017-08-03 18:30:35 -070025
sangho666cd6d2015-04-14 16:27:13 -070026import org.onlab.packet.Ip4Address;
Pier Ventree0ae7a32016-11-23 09:57:42 -080027import org.onlab.packet.Ip6Address;
sanghob35a6192015-04-01 13:05:26 -070028import org.onlab.packet.IpPrefix;
Charles Chan2fde6d42017-08-23 14:46:43 -070029import org.onlab.packet.MacAddress;
30import org.onlab.packet.VlanId;
Saurav Das7bcbe702017-06-13 15:35:54 -070031import org.onosproject.cluster.NodeId;
Charles Chan93e71ba2016-04-29 14:38:22 -070032import org.onosproject.net.ConnectPoint;
sanghob35a6192015-04-01 13:05:26 -070033import org.onosproject.net.Device;
34import org.onosproject.net.DeviceId;
sangho20eff1d2015-04-13 15:15:58 -070035import org.onosproject.net.Link;
Charles Chan2fde6d42017-08-23 14:46:43 -070036import org.onosproject.net.PortNumber;
Charles Chan0b4e6182015-11-03 10:42:14 -080037import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
38import org.onosproject.segmentrouting.config.DeviceConfiguration;
Saurav Dasc88d4662017-05-15 15:34:25 -070039import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
sanghob35a6192015-04-01 13:05:26 -070040import org.slf4j.Logger;
41import org.slf4j.LoggerFactory;
42
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -070043import java.time.Instant;
sanghob35a6192015-04-01 13:05:26 -070044import java.util.ArrayList;
45import java.util.HashMap;
46import java.util.HashSet;
Saurav Das7bcbe702017-06-13 15:35:54 -070047import java.util.Iterator;
48import java.util.Map;
Saurav Dasd2fded02016-12-02 15:43:47 -080049import java.util.Objects;
sanghob35a6192015-04-01 13:05:26 -070050import java.util.Set;
Saurav Das59232cf2016-04-27 18:35:50 -070051import java.util.concurrent.ScheduledExecutorService;
52import java.util.concurrent.TimeUnit;
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +090053import java.util.concurrent.locks.Lock;
54import java.util.concurrent.locks.ReentrantLock;
Saurav Dasd2fded02016-12-02 15:43:47 -080055import static com.google.common.base.MoreObjects.toStringHelper;
Pier Ventree0ae7a32016-11-23 09:57:42 -080056import static com.google.common.base.Preconditions.checkNotNull;
57import static java.util.concurrent.Executors.newScheduledThreadPool;
58import static org.onlab.util.Tools.groupedThreads;
sanghob35a6192015-04-01 13:05:26 -070059
Charles Chane849c192016-01-11 18:28:54 -080060/**
61 * Default routing handler that is responsible for route computing and
62 * routing rule population.
63 */
sanghob35a6192015-04-01 13:05:26 -070064public class DefaultRoutingHandler {
Saurav Das018605f2017-02-18 14:05:44 -080065 private static final int MAX_CONSTANT_RETRY_ATTEMPTS = 5;
Ray Milkey3717e602018-02-01 13:49:47 -080066 private static final long RETRY_INTERVAL_MS = 250L;
Saurav Das018605f2017-02-18 14:05:44 -080067 private static final int RETRY_INTERVAL_SCALE = 1;
Saurav Dasceccf242017-08-03 18:30:35 -070068 private static final long STABLITY_THRESHOLD = 10; //secs
Charles Chan93e71ba2016-04-29 14:38:22 -070069 private static Logger log = LoggerFactory.getLogger(DefaultRoutingHandler.class);
sanghob35a6192015-04-01 13:05:26 -070070
71 private SegmentRoutingManager srManager;
72 private RoutingRulePopulator rulePopulator;
Shashikanth VH013a7bc2015-12-11 01:32:44 +053073 private HashMap<DeviceId, EcmpShortestPathGraph> currentEcmpSpgMap;
74 private HashMap<DeviceId, EcmpShortestPathGraph> updatedEcmpSpgMap;
sangho666cd6d2015-04-14 16:27:13 -070075 private DeviceConfiguration config;
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +090076 private final Lock statusLock = new ReentrantLock();
77 private volatile Status populationStatus;
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070078 private ScheduledExecutorService executorService
Saurav Dasd2fded02016-12-02 15:43:47 -080079 = newScheduledThreadPool(1, groupedThreads("retryftr", "retry-%d", log));
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -070080 private Instant lastRoutingChange;
sanghob35a6192015-04-01 13:05:26 -070081
82 /**
83 * Represents the default routing population status.
84 */
85 public enum Status {
86 // population process is not started yet.
87 IDLE,
88
89 // population process started.
90 STARTED,
91
Srikanth Vavilapallif5b234a2015-04-21 13:04:13 -070092 // population process was aborted due to errors, mostly for groups not
93 // found.
sanghob35a6192015-04-01 13:05:26 -070094 ABORTED,
95
96 // population process was finished successfully.
97 SUCCEEDED
98 }
99
100 /**
101 * Creates a DefaultRoutingHandler object.
102 *
103 * @param srManager SegmentRoutingManager object
104 */
105 public DefaultRoutingHandler(SegmentRoutingManager srManager) {
106 this.srManager = srManager;
107 this.rulePopulator = checkNotNull(srManager.routingRulePopulator);
sangho666cd6d2015-04-14 16:27:13 -0700108 this.config = checkNotNull(srManager.deviceConfiguration);
sanghob35a6192015-04-01 13:05:26 -0700109 this.populationStatus = Status.IDLE;
sangho20eff1d2015-04-13 15:15:58 -0700110 this.currentEcmpSpgMap = Maps.newHashMap();
sanghob35a6192015-04-01 13:05:26 -0700111 }
112
113 /**
Saurav Dasc88d4662017-05-15 15:34:25 -0700114 * Returns an immutable copy of the current ECMP shortest-path graph as
115 * computed by this controller instance.
116 *
Saurav Das7bcbe702017-06-13 15:35:54 -0700117 * @return immutable copy of the current ECMP graph
Saurav Dasc88d4662017-05-15 15:34:25 -0700118 */
119 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEmcpSpgMap() {
120 Builder<DeviceId, EcmpShortestPathGraph> builder = ImmutableMap.builder();
121 currentEcmpSpgMap.entrySet().forEach(entry -> {
122 if (entry.getValue() != null) {
123 builder.put(entry.getKey(), entry.getValue());
124 }
125 });
126 return builder.build();
127 }
128
Saurav Dasceccf242017-08-03 18:30:35 -0700129 /**
130 * Acquires the lock used when making routing changes.
131 */
132 public void acquireRoutingLock() {
133 statusLock.lock();
134 }
135
136 /**
137 * Releases the lock used when making routing changes.
138 */
139 public void releaseRoutingLock() {
140 statusLock.unlock();
141 }
142
143 /**
144 * Determines if routing in the network has been stable in the last
145 * STABLITY_THRESHOLD seconds, by comparing the current time to the last
146 * routing change timestamp.
147 *
148 * @return true if stable
149 */
150 public boolean isRoutingStable() {
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700151 long last = (long) (lastRoutingChange.toEpochMilli() / 1000.0);
152 long now = (long) (Instant.now().toEpochMilli() / 1000.0);
Saurav Das9df5b7c2017-08-14 16:44:43 -0700153 log.trace("Routing stable since {}s", now - last);
Saurav Dasceccf242017-08-03 18:30:35 -0700154 return (now - last) > STABLITY_THRESHOLD;
155 }
156
157
Saurav Das7bcbe702017-06-13 15:35:54 -0700158 //////////////////////////////////////
159 // Route path handling
160 //////////////////////////////////////
161
Saurav Das45f48152018-01-18 12:07:33 -0800162 /* The following three methods represent the three major ways in which
163 * route-path handling is triggered in the network
Saurav Das7bcbe702017-06-13 15:35:54 -0700164 * a) due to configuration change
165 * b) due to route-added event
166 * c) due to change in the topology
167 */
168
Saurav Dasc88d4662017-05-15 15:34:25 -0700169 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700170 * Populates all routing rules to all switches. Typically triggered at
171 * startup or after a configuration event.
sanghob35a6192015-04-01 13:05:26 -0700172 */
Saurav Dasc88d4662017-05-15 15:34:25 -0700173 public void populateAllRoutingRules() {
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700174 lastRoutingChange = Instant.now();
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900175 statusLock.lock();
176 try {
Saurav Das7bcbe702017-06-13 15:35:54 -0700177 if (populationStatus == Status.STARTED) {
178 log.warn("Previous rule population is not finished. Cannot"
179 + " proceed with populateAllRoutingRules");
180 return;
181 }
182
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900183 populationStatus = Status.STARTED;
184 rulePopulator.resetCounter();
Saurav Das7bcbe702017-06-13 15:35:54 -0700185 log.info("Starting to populate all routing rules");
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900186 log.debug("populateAllRoutingRules: populationStatus is STARTED");
sanghob35a6192015-04-01 13:05:26 -0700187
Saurav Das7bcbe702017-06-13 15:35:54 -0700188 // take a snapshot of the topology
189 updatedEcmpSpgMap = new HashMap<>();
190 Set<EdgePair> edgePairs = new HashSet<>();
191 Set<ArrayList<DeviceId>> routeChanges = new HashSet<>();
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800192 for (DeviceId dstSw : srManager.deviceConfiguration.getRouters()) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700193 EcmpShortestPathGraph ecmpSpgUpdated =
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800194 new EcmpShortestPathGraph(dstSw, srManager);
195 updatedEcmpSpgMap.put(dstSw, ecmpSpgUpdated);
196 DeviceId pairDev = getPairDev(dstSw);
Saurav Das7bcbe702017-06-13 15:35:54 -0700197 if (pairDev != null) {
198 // pairDev may not be available yet, but we still need to add
199 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev, srManager);
200 updatedEcmpSpgMap.put(pairDev, ecmpSpgUpdated);
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800201 edgePairs.add(new EdgePair(dstSw, pairDev));
Saurav Das7bcbe702017-06-13 15:35:54 -0700202 }
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800203 DeviceId ret = shouldHandleRouting(dstSw);
Saurav Das7bcbe702017-06-13 15:35:54 -0700204 if (ret == null) {
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900205 continue;
206 }
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800207 Set<DeviceId> devsToProcess = Sets.newHashSet(dstSw, ret);
Saurav Das7bcbe702017-06-13 15:35:54 -0700208 // To do a full reroute, assume all routes have changed
209 for (DeviceId dev : devsToProcess) {
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800210 for (DeviceId targetSw : srManager.deviceConfiguration.getRouters()) {
211 if (targetSw.equals(dev)) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700212 continue;
213 }
Jonathan Hart8ca2bc02017-11-30 18:23:42 -0800214 routeChanges.add(Lists.newArrayList(targetSw, dev));
Saurav Das7bcbe702017-06-13 15:35:54 -0700215 }
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900216 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700217 }
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900218
Saurav Das7bcbe702017-06-13 15:35:54 -0700219 if (!redoRouting(routeChanges, edgePairs, null)) {
220 log.debug("populateAllRoutingRules: populationStatus is ABORTED");
221 populationStatus = Status.ABORTED;
222 log.warn("Failed to repopulate all routing rules.");
223 return;
sanghob35a6192015-04-01 13:05:26 -0700224 }
225
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900226 log.debug("populateAllRoutingRules: populationStatus is SUCCEEDED");
227 populationStatus = Status.SUCCEEDED;
Saurav Das7bcbe702017-06-13 15:35:54 -0700228 log.info("Completed all routing rule population. Total # of rules pushed : {}",
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900229 rulePopulator.getCounter());
Saurav Dasc88d4662017-05-15 15:34:25 -0700230 return;
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900231 } finally {
232 statusLock.unlock();
sanghob35a6192015-04-01 13:05:26 -0700233 }
sanghob35a6192015-04-01 13:05:26 -0700234 }
235
sangho20eff1d2015-04-13 15:15:58 -0700236 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700237 * Populate rules from all other edge devices to the connect-point(s)
238 * specified for the given subnets.
239 *
240 * @param cpts connect point(s) of the subnets being added
241 * @param subnets subnets being added
Charles Chan2fde6d42017-08-23 14:46:43 -0700242 */
243 // XXX refactor
Saurav Das7bcbe702017-06-13 15:35:54 -0700244 protected void populateSubnet(Set<ConnectPoint> cpts, Set<IpPrefix> subnets) {
Charles Chan71e64f12017-09-11 15:21:57 -0700245 if (cpts == null || cpts.size() < 1 || cpts.size() > 2) {
246 log.warn("Skipping populateSubnet due to illegal size of connect points. {}", cpts);
247 return;
248 }
249
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700250 lastRoutingChange = Instant.now();
Saurav Das7bcbe702017-06-13 15:35:54 -0700251 statusLock.lock();
252 try {
253 if (populationStatus == Status.STARTED) {
254 log.warn("Previous rule population is not finished. Cannot"
255 + " proceed with routing rules for added routes");
256 return;
257 }
258 populationStatus = Status.STARTED;
259 rulePopulator.resetCounter();
Charles Chan2fde6d42017-08-23 14:46:43 -0700260 log.info("Starting to populate routing rules for added routes, subnets={}, cpts={}",
261 subnets, cpts);
Saurav Dasc568c342018-01-25 09:49:01 -0800262 // In principle an update to a subnet/prefix should not require a
263 // new ECMPspg calculation as it is not a topology event. As a
264 // result, we use the current/existing ECMPspg in the updated map
265 // used by the redoRouting method.
Saurav Das15a81782018-02-09 09:15:03 -0800266 if (updatedEcmpSpgMap == null) {
267 updatedEcmpSpgMap = new HashMap<>();
268 }
Saurav Dasc568c342018-01-25 09:49:01 -0800269 currentEcmpSpgMap.entrySet().forEach(entry -> {
270 updatedEcmpSpgMap.put(entry.getKey(), entry.getValue());
Saurav Dase7f51012018-02-09 17:26:45 -0800271 if (log.isTraceEnabled()) {
272 log.trace("Root switch: {}", entry.getKey());
273 log.trace(" Current/Existing SPG: {}", entry.getValue());
Saurav Dasc568c342018-01-25 09:49:01 -0800274 }
275 });
Saurav Das7bcbe702017-06-13 15:35:54 -0700276 Set<EdgePair> edgePairs = new HashSet<>();
277 Set<ArrayList<DeviceId>> routeChanges = new HashSet<>();
278 boolean handleRouting = false;
279
280 if (cpts.size() == 2) {
281 // ensure connect points are edge-pairs
282 Iterator<ConnectPoint> iter = cpts.iterator();
283 DeviceId dev1 = iter.next().deviceId();
284 DeviceId pairDev = getPairDev(dev1);
285 if (iter.next().deviceId().equals(pairDev)) {
286 edgePairs.add(new EdgePair(dev1, pairDev));
287 } else {
288 log.warn("Connectpoints {} for subnets {} not on "
289 + "pair-devices.. aborting populateSubnet", cpts, subnets);
290 populationStatus = Status.ABORTED;
291 return;
292 }
293 for (ConnectPoint cp : cpts) {
Saurav Dasc568c342018-01-25 09:49:01 -0800294 if (updatedEcmpSpgMap.get(cp.deviceId()) == null) {
295 EcmpShortestPathGraph ecmpSpgUpdated =
Saurav Das7bcbe702017-06-13 15:35:54 -0700296 new EcmpShortestPathGraph(cp.deviceId(), srManager);
Saurav Dasc568c342018-01-25 09:49:01 -0800297 updatedEcmpSpgMap.put(cp.deviceId(), ecmpSpgUpdated);
298 log.warn("populateSubnet: no updated graph for dev:{}"
299 + " ... creating", cp.deviceId());
300 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700301 DeviceId retId = shouldHandleRouting(cp.deviceId());
302 if (retId == null) {
303 continue;
304 }
305 handleRouting = true;
306 }
307 } else {
308 // single connect point
309 DeviceId dstSw = cpts.iterator().next().deviceId();
Saurav Dasc568c342018-01-25 09:49:01 -0800310 if (updatedEcmpSpgMap.get(dstSw) == null) {
311 EcmpShortestPathGraph ecmpSpgUpdated =
Saurav Das7bcbe702017-06-13 15:35:54 -0700312 new EcmpShortestPathGraph(dstSw, srManager);
Saurav Dasc568c342018-01-25 09:49:01 -0800313 updatedEcmpSpgMap.put(dstSw, ecmpSpgUpdated);
314 log.warn("populateSubnet: no updated graph for dev:{}"
315 + " ... creating", dstSw);
316 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700317 if (srManager.mastershipService.isLocalMaster(dstSw)) {
318 handleRouting = true;
319 }
320 }
321
322 if (!handleRouting) {
323 log.debug("This instance is not handling ecmp routing to the "
324 + "connectPoint(s) {}", cpts);
325 populationStatus = Status.ABORTED;
326 return;
327 }
328
329 // if it gets here, this instance should handle routing for the
330 // connectpoint(s). Assume all route-paths have to be updated to
331 // the connectpoint(s) with the following exceptions
332 // 1. if target is non-edge no need for routing rules
333 // 2. if target is one of the connectpoints
334 for (ConnectPoint cp : cpts) {
335 DeviceId dstSw = cp.deviceId();
336 for (Device targetSw : srManager.deviceService.getDevices()) {
337 boolean isEdge = false;
338 try {
339 isEdge = config.isEdgeDevice(targetSw.id());
340 } catch (DeviceConfigNotFoundException e) {
Charles Chan69871362018-02-16 17:20:54 -0800341 log.warn(e.getMessage() + "aborting populateSubnet on targetSw {}", targetSw.id());
342 continue;
Saurav Das7bcbe702017-06-13 15:35:54 -0700343 }
344 if (dstSw.equals(targetSw.id()) || !isEdge ||
345 (cpts.size() == 2 &&
346 targetSw.id().equals(getPairDev(dstSw)))) {
347 continue;
348 }
349 routeChanges.add(Lists.newArrayList(targetSw.id(), dstSw));
350 }
351 }
352
353 if (!redoRouting(routeChanges, edgePairs, subnets)) {
354 log.debug("populateSubnet: populationStatus is ABORTED");
355 populationStatus = Status.ABORTED;
356 log.warn("Failed to repopulate the rules for subnet.");
357 return;
358 }
359
360 log.debug("populateSubnet: populationStatus is SUCCEEDED");
361 populationStatus = Status.SUCCEEDED;
362 log.info("Completed subnet population. Total # of rules pushed : {}",
363 rulePopulator.getCounter());
364 return;
365
366 } finally {
367 statusLock.unlock();
368 }
369 }
370
371 /**
Saurav Dasc88d4662017-05-15 15:34:25 -0700372 * Populates the routing rules or makes hash group changes according to the
373 * route-path changes due to link failure, switch failure or link up. This
374 * method should only be called for one of these three possible event-types.
375 * Note that when a switch goes away, all of its links fail as well,
376 * but this is handled as a single switch removal event.
sangho20eff1d2015-04-13 15:15:58 -0700377 *
Saurav Dasc88d4662017-05-15 15:34:25 -0700378 * @param linkDown the single failed link, or null for other conditions
379 * such as link-up or a removed switch
380 * @param linkUp the single link up, or null for other conditions such as
381 * link-down or a removed switch
382 * @param switchDown the removed switch, or null for other conditions such as
383 * link-down or link-up
Saurav Das7bcbe702017-06-13 15:35:54 -0700384 */ // refactor
Saurav Dasc88d4662017-05-15 15:34:25 -0700385 public void populateRoutingRulesForLinkStatusChange(Link linkDown,
386 Link linkUp,
387 DeviceId switchDown) {
388 if ((linkDown != null && (linkUp != null || switchDown != null)) ||
389 (linkUp != null && (linkDown != null || switchDown != null)) ||
390 (switchDown != null && (linkUp != null || linkDown != null))) {
391 log.warn("Only one event can be handled for link status change .. aborting");
392 return;
393 }
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700394 lastRoutingChange = Instant.now();
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900395 statusLock.lock();
396 try {
sangho20eff1d2015-04-13 15:15:58 -0700397
398 if (populationStatus == Status.STARTED) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700399 log.warn("Previous rule population is not finished. Cannot"
Saurav Dasc568c342018-01-25 09:49:01 -0800400 + " proceeed with routingRules for Topology change");
Saurav Dasc88d4662017-05-15 15:34:25 -0700401 return;
sangho20eff1d2015-04-13 15:15:58 -0700402 }
403
Saurav Das7bcbe702017-06-13 15:35:54 -0700404 // Take snapshots of the topology
sangho45b009c2015-05-07 13:30:57 -0700405 updatedEcmpSpgMap = new HashMap<>();
Saurav Das7bcbe702017-06-13 15:35:54 -0700406 Set<EdgePair> edgePairs = new HashSet<>();
sangho45b009c2015-05-07 13:30:57 -0700407 for (Device sw : srManager.deviceService.getDevices()) {
Shashikanth VH013a7bc2015-12-11 01:32:44 +0530408 EcmpShortestPathGraph ecmpSpgUpdated =
409 new EcmpShortestPathGraph(sw.id(), srManager);
sangho45b009c2015-05-07 13:30:57 -0700410 updatedEcmpSpgMap.put(sw.id(), ecmpSpgUpdated);
Saurav Das7bcbe702017-06-13 15:35:54 -0700411 DeviceId pairDev = getPairDev(sw.id());
412 if (pairDev != null) {
413 // pairDev may not be available yet, but we still need to add
414 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev, srManager);
415 updatedEcmpSpgMap.put(pairDev, ecmpSpgUpdated);
416 edgePairs.add(new EdgePair(sw.id(), pairDev));
417 }
sangho45b009c2015-05-07 13:30:57 -0700418 }
419
Saurav Dasc568c342018-01-25 09:49:01 -0800420 log.info("Starting to populate routing rules from Topology change");
sangho52abe3a2015-05-05 14:13:34 -0700421
sangho20eff1d2015-04-13 15:15:58 -0700422 Set<ArrayList<DeviceId>> routeChanges;
Saurav Dasc88d4662017-05-15 15:34:25 -0700423 log.debug("populateRoutingRulesForLinkStatusChange: "
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700424 + "populationStatus is STARTED");
sangho20eff1d2015-04-13 15:15:58 -0700425 populationStatus = Status.STARTED;
Saurav Dasc568c342018-01-25 09:49:01 -0800426 rulePopulator.resetCounter(); //XXX maybe useful to have a rehash ctr
427 boolean hashGroupsChanged = false;
Saurav Das4e3224f2016-11-29 14:27:25 -0800428 // try optimized re-routing
Saurav Dasc88d4662017-05-15 15:34:25 -0700429 if (linkDown == null) {
430 // either a linkUp or a switchDown - compute all route changes by
431 // comparing all routes of existing ECMP SPG to new ECMP SPG
sangho20eff1d2015-04-13 15:15:58 -0700432 routeChanges = computeRouteChange();
Saurav Dasc88d4662017-05-15 15:34:25 -0700433
Saurav Das9df5b7c2017-08-14 16:44:43 -0700434 // deal with linkUp of a seen-before link
Saurav Das45f48152018-01-18 12:07:33 -0800435 if (linkUp != null && srManager.linkHandler.isSeenLink(linkUp)) {
436 if (!srManager.linkHandler.isBidirectional(linkUp)) {
Saurav Das9df5b7c2017-08-14 16:44:43 -0700437 log.warn("Not a bidirectional link yet .. not "
438 + "processing link {}", linkUp);
Saurav Das45f48152018-01-18 12:07:33 -0800439 srManager.linkHandler.updateSeenLink(linkUp, true);
Saurav Das9df5b7c2017-08-14 16:44:43 -0700440 populationStatus = Status.ABORTED;
441 return;
Saurav Dasc88d4662017-05-15 15:34:25 -0700442 }
Saurav Das9df5b7c2017-08-14 16:44:43 -0700443 // link previously seen before
444 // do hash-bucket changes instead of a re-route
445 processHashGroupChange(routeChanges, false, null);
446 // clear out routesChanges so a re-route is not attempted
447 routeChanges = ImmutableSet.of();
Saurav Dasc568c342018-01-25 09:49:01 -0800448 hashGroupsChanged = true;
Saurav Dasc88d4662017-05-15 15:34:25 -0700449 }
Saurav Das9df5b7c2017-08-14 16:44:43 -0700450 // for a linkUp of a never-seen-before link
451 // let it fall through to a reroute of the routeChanges
Saurav Dasc88d4662017-05-15 15:34:25 -0700452
453 // now that we are past the check for a previously seen link
454 // it is safe to update the store for the linkUp
455 if (linkUp != null) {
Saurav Das45f48152018-01-18 12:07:33 -0800456 srManager.linkHandler.updateSeenLink(linkUp, true);
Saurav Dasc88d4662017-05-15 15:34:25 -0700457 }
458
Saurav Das9df5b7c2017-08-14 16:44:43 -0700459 //deal with switchDown
460 if (switchDown != null) {
461 processHashGroupChange(routeChanges, true, switchDown);
462 // clear out routesChanges so a re-route is not attempted
463 routeChanges = ImmutableSet.of();
Saurav Dasc568c342018-01-25 09:49:01 -0800464 hashGroupsChanged = true;
Saurav Das9df5b7c2017-08-14 16:44:43 -0700465 }
sangho20eff1d2015-04-13 15:15:58 -0700466 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -0700467 // link has gone down
468 // Compare existing ECMP SPG only with the link that went down
469 routeChanges = computeDamagedRoutes(linkDown);
470 if (routeChanges != null) {
471 processHashGroupChange(routeChanges, true, null);
472 // clear out routesChanges so a re-route is not attempted
473 routeChanges = ImmutableSet.of();
Saurav Dasc568c342018-01-25 09:49:01 -0800474 hashGroupsChanged = true;
Saurav Dasc88d4662017-05-15 15:34:25 -0700475 }
sangho20eff1d2015-04-13 15:15:58 -0700476 }
477
Saurav Das4e3224f2016-11-29 14:27:25 -0800478 // do full re-routing if optimized routing returns null routeChanges
Saurav Dasb5c236e2016-06-07 10:08:06 -0700479 if (routeChanges == null) {
Saurav Dasc568c342018-01-25 09:49:01 -0800480 log.warn("Optimized routing failed... opting for full reroute");
Saurav Das7bcbe702017-06-13 15:35:54 -0700481 populationStatus = Status.ABORTED;
Saurav Dasc88d4662017-05-15 15:34:25 -0700482 populateAllRoutingRules();
483 return;
Saurav Dasb5c236e2016-06-07 10:08:06 -0700484 }
485
sangho20eff1d2015-04-13 15:15:58 -0700486 if (routeChanges.isEmpty()) {
Saurav Dasc568c342018-01-25 09:49:01 -0800487 if (hashGroupsChanged) {
488 log.info("Hash-groups changed for link status change");
489 } else {
490 log.info("No re-route or re-hash attempted for the link"
491 + " status change");
492 updatedEcmpSpgMap.keySet().forEach(devId -> {
493 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
494 log.debug("Updating ECMPspg for remaining dev:{}", devId);
495 });
496 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700497 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sangho20eff1d2015-04-13 15:15:58 -0700498 populationStatus = Status.SUCCEEDED;
Saurav Dasc88d4662017-05-15 15:34:25 -0700499 return;
sangho20eff1d2015-04-13 15:15:58 -0700500 }
501
Saurav Dasc88d4662017-05-15 15:34:25 -0700502 // reroute of routeChanges
Saurav Das7bcbe702017-06-13 15:35:54 -0700503 if (redoRouting(routeChanges, edgePairs, null)) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700504 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sangho20eff1d2015-04-13 15:15:58 -0700505 populationStatus = Status.SUCCEEDED;
Saurav Das7bcbe702017-06-13 15:35:54 -0700506 log.info("Completed repopulation of rules for link-status change."
507 + " # of rules populated : {}", rulePopulator.getCounter());
Saurav Dasc88d4662017-05-15 15:34:25 -0700508 return;
sangho20eff1d2015-04-13 15:15:58 -0700509 } else {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700510 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is ABORTED");
sangho20eff1d2015-04-13 15:15:58 -0700511 populationStatus = Status.ABORTED;
Saurav Das7bcbe702017-06-13 15:35:54 -0700512 log.warn("Failed to repopulate the rules for link status change.");
Saurav Dasc88d4662017-05-15 15:34:25 -0700513 return;
sangho20eff1d2015-04-13 15:15:58 -0700514 }
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900515 } finally {
516 statusLock.unlock();
sangho20eff1d2015-04-13 15:15:58 -0700517 }
518 }
519
Saurav Dasc88d4662017-05-15 15:34:25 -0700520 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700521 * Processes a set a route-path changes by reprogramming routing rules and
522 * creating new hash-groups or editing them if necessary. This method also
523 * determines the next-hops for the route-path from the src-switch (target)
524 * of the path towards the dst-switch of the path.
Saurav Dasc88d4662017-05-15 15:34:25 -0700525 *
Saurav Das7bcbe702017-06-13 15:35:54 -0700526 * @param routeChanges a set of route-path changes, where each route-path is
527 * a list with its first element the src-switch (target)
528 * of the path, and the second element the dst-switch of
529 * the path.
530 * @param edgePairs a set of edge-switches that are paired by configuration
531 * @param subnets a set of prefixes that need to be populated in the routing
532 * table of the target switch in the route-path. Can be null,
533 * in which case all the prefixes belonging to the dst-switch
534 * will be populated in the target switch
535 * @return true if successful in repopulating all routes
Saurav Dasc88d4662017-05-15 15:34:25 -0700536 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700537 private boolean redoRouting(Set<ArrayList<DeviceId>> routeChanges,
538 Set<EdgePair> edgePairs, Set<IpPrefix> subnets) {
539 // first make every entry two-elements
540 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
541 for (ArrayList<DeviceId> route : routeChanges) {
542 if (route.size() == 1) {
543 DeviceId dstSw = route.get(0);
544 EcmpShortestPathGraph ec = updatedEcmpSpgMap.get(dstSw);
545 if (ec == null) {
546 log.warn("No graph found for {} .. aborting redoRouting", dstSw);
547 return false;
548 }
549 ec.getAllLearnedSwitchesAndVia().keySet().forEach(key -> {
550 ec.getAllLearnedSwitchesAndVia().get(key).keySet().forEach(target -> {
551 changedRoutes.add(Lists.newArrayList(target, dstSw));
552 });
553 });
554 } else {
555 DeviceId targetSw = route.get(0);
556 DeviceId dstSw = route.get(1);
557 changedRoutes.add(Lists.newArrayList(targetSw, dstSw));
558 }
559 }
560
561 // now process changedRoutes according to edgePairs
562 if (!redoRoutingEdgePairs(edgePairs, subnets, changedRoutes)) {
563 return false; //abort routing and fail fast
564 }
565
566 // whatever is left in changedRoutes is now processed for individual dsts.
Saurav Dasc568c342018-01-25 09:49:01 -0800567 Set<DeviceId> updatedDevices = Sets.newHashSet();
568 if (!redoRoutingIndividualDests(subnets, changedRoutes,
569 updatedDevices)) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700570 return false; //abort routing and fail fast
571 }
572
Saurav Das7bcbe702017-06-13 15:35:54 -0700573 // update ecmpSPG for all edge-pairs
574 for (EdgePair ep : edgePairs) {
575 currentEcmpSpgMap.put(ep.dev1, updatedEcmpSpgMap.get(ep.dev1));
576 currentEcmpSpgMap.put(ep.dev2, updatedEcmpSpgMap.get(ep.dev2));
577 log.debug("Updating ECMPspg for edge-pair:{}-{}", ep.dev1, ep.dev2);
578 }
Saurav Dasc568c342018-01-25 09:49:01 -0800579
580 // here is where we update all devices not touched by this instance
581 updatedEcmpSpgMap.keySet().stream()
582 .filter(devId -> !edgePairs.stream().anyMatch(ep -> ep.includes(devId)))
583 .filter(devId -> !updatedDevices.contains(devId))
584 .forEach(devId -> {
585 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
586 log.debug("Updating ECMPspg for remaining dev:{}", devId);
587 });
Saurav Das7bcbe702017-06-13 15:35:54 -0700588 return true;
589 }
590
591 /**
592 * Programs targetSw in the changedRoutes for given prefixes reachable by
593 * an edgePair. If no prefixes are given, the method will use configured
594 * subnets/prefixes. If some configured subnets belong only to a specific
595 * destination in the edgePair, then the target switch will be programmed
596 * only to that destination.
597 *
598 * @param edgePairs set of edge-pairs for which target will be programmed
599 * @param subnets a set of prefixes that need to be populated in the routing
600 * table of the target switch in the changedRoutes. Can be null,
601 * in which case all the configured prefixes belonging to the
602 * paired switches will be populated in the target switch
603 * @param changedRoutes a set of route-path changes, where each route-path is
604 * a list with its first element the src-switch (target)
605 * of the path, and the second element the dst-switch of
606 * the path.
607 * @return true if successful
608 */
609 private boolean redoRoutingEdgePairs(Set<EdgePair> edgePairs,
610 Set<IpPrefix> subnets,
611 Set<ArrayList<DeviceId>> changedRoutes) {
612 for (EdgePair ep : edgePairs) {
613 // temp store for a target's changedRoutes to this edge-pair
614 Map<DeviceId, Set<ArrayList<DeviceId>>> targetRoutes = new HashMap<>();
615 Iterator<ArrayList<DeviceId>> i = changedRoutes.iterator();
616 while (i.hasNext()) {
617 ArrayList<DeviceId> route = i.next();
618 DeviceId dstSw = route.get(1);
619 if (ep.includes(dstSw)) {
620 // routeChange for edge pair found
621 // sort by target iff target is edge and remove from changedRoutes
622 DeviceId targetSw = route.get(0);
623 try {
624 if (!srManager.deviceConfiguration.isEdgeDevice(targetSw)) {
625 continue;
626 }
627 } catch (DeviceConfigNotFoundException e) {
628 log.warn(e.getMessage() + "aborting redoRouting");
629 return false;
630 }
631 // route is from another edge to this edge-pair
632 if (targetRoutes.containsKey(targetSw)) {
633 targetRoutes.get(targetSw).add(route);
634 } else {
635 Set<ArrayList<DeviceId>> temp = new HashSet<>();
636 temp.add(route);
637 targetRoutes.put(targetSw, temp);
638 }
639 i.remove();
640 }
641 }
642 // so now for this edgepair we have a per target set of routechanges
643 // process target->edgePair route
644 for (Map.Entry<DeviceId, Set<ArrayList<DeviceId>>> entry :
645 targetRoutes.entrySet()) {
646 log.debug("* redoRoutingDstPair Target:{} -> edge-pair {}",
647 entry.getKey(), ep);
648 DeviceId targetSw = entry.getKey();
649 Map<DeviceId, Set<DeviceId>> perDstNextHops = new HashMap<>();
650 entry.getValue().forEach(route -> {
651 Set<DeviceId> nhops = getNextHops(route.get(0), route.get(1));
652 log.debug("route: target {} -> dst {} found with next-hops {}",
653 route.get(0), route.get(1), nhops);
654 perDstNextHops.put(route.get(1), nhops);
655 });
656 Set<IpPrefix> ipDev1 = (subnets == null) ? config.getSubnets(ep.dev1)
657 : subnets;
658 Set<IpPrefix> ipDev2 = (subnets == null) ? config.getSubnets(ep.dev2)
659 : subnets;
660 ipDev1 = (ipDev1 == null) ? Sets.newHashSet() : ipDev1;
661 ipDev2 = (ipDev2 == null) ? Sets.newHashSet() : ipDev2;
Saurav Dasc568c342018-01-25 09:49:01 -0800662 Set<DeviceId> nhDev1 = perDstNextHops.get(ep.dev1);
663 Set<DeviceId> nhDev2 = perDstNextHops.get(ep.dev2);
Saurav Das7bcbe702017-06-13 15:35:54 -0700664 // handle routing to subnets common to edge-pair
Saurav Dasc568c342018-01-25 09:49:01 -0800665 // only if the targetSw is not part of the edge-pair and there
666 // exists a next hop to at least one of the devices in the edge-pair
667 if (!ep.includes(targetSw)
668 && ((nhDev1 != null && !nhDev1.isEmpty())
669 || (nhDev2 != null && !nhDev2.isEmpty()))) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700670 if (!populateEcmpRoutingRulePartial(
671 targetSw,
672 ep.dev1, ep.dev2,
673 perDstNextHops,
674 Sets.intersection(ipDev1, ipDev2))) {
675 return false; // abort everything and fail fast
676 }
677 }
Saurav Dasc568c342018-01-25 09:49:01 -0800678 // handle routing to subnets that only belong to dev1 only if
679 // a next-hop exists from the target to dev1
Saurav Das7bcbe702017-06-13 15:35:54 -0700680 Set<IpPrefix> onlyDev1Subnets = Sets.difference(ipDev1, ipDev2);
Saurav Dasc568c342018-01-25 09:49:01 -0800681 if (!onlyDev1Subnets.isEmpty()
682 && nhDev1 != null && !nhDev1.isEmpty()) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700683 Map<DeviceId, Set<DeviceId>> onlyDev1NextHops = new HashMap<>();
Saurav Dasc568c342018-01-25 09:49:01 -0800684 onlyDev1NextHops.put(ep.dev1, nhDev1);
Saurav Das7bcbe702017-06-13 15:35:54 -0700685 if (!populateEcmpRoutingRulePartial(
686 targetSw,
687 ep.dev1, null,
688 onlyDev1NextHops,
689 onlyDev1Subnets)) {
690 return false; // abort everything and fail fast
691 }
692 }
Saurav Dasc568c342018-01-25 09:49:01 -0800693 // handle routing to subnets that only belong to dev2 only if
694 // a next-hop exists from the target to dev2
Saurav Das7bcbe702017-06-13 15:35:54 -0700695 Set<IpPrefix> onlyDev2Subnets = Sets.difference(ipDev2, ipDev1);
Saurav Dasc568c342018-01-25 09:49:01 -0800696 if (!onlyDev2Subnets.isEmpty()
697 && nhDev2 != null && !nhDev2.isEmpty()) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700698 Map<DeviceId, Set<DeviceId>> onlyDev2NextHops = new HashMap<>();
Saurav Dasc568c342018-01-25 09:49:01 -0800699 onlyDev2NextHops.put(ep.dev2, nhDev2);
Saurav Das7bcbe702017-06-13 15:35:54 -0700700 if (!populateEcmpRoutingRulePartial(
701 targetSw,
702 ep.dev2, null,
703 onlyDev2NextHops,
704 onlyDev2Subnets)) {
705 return false; // abort everything and fail fast
706 }
707 }
708 }
709 // if it gets here it has succeeded for all targets to this edge-pair
710 }
711 return true;
712 }
713
714 /**
715 * Programs targetSw in the changedRoutes for given prefixes reachable by
716 * a destination switch that is not part of an edge-pair.
717 * If no prefixes are given, the method will use configured subnets/prefixes.
718 *
719 * @param subnets a set of prefixes that need to be populated in the routing
720 * table of the target switch in the changedRoutes. Can be null,
721 * in which case all the configured prefixes belonging to the
722 * paired switches will be populated in the target switch
723 * @param changedRoutes a set of route-path changes, where each route-path is
724 * a list with its first element the src-switch (target)
725 * of the path, and the second element the dst-switch of
726 * the path.
727 * @return true if successful
728 */
729 private boolean redoRoutingIndividualDests(Set<IpPrefix> subnets,
Saurav Dasc568c342018-01-25 09:49:01 -0800730 Set<ArrayList<DeviceId>> changedRoutes,
731 Set<DeviceId> updatedDevices) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700732 // aggregate route-path changes for each dst device
733 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> routesBydevice =
734 new HashMap<>();
735 for (ArrayList<DeviceId> route: changedRoutes) {
736 DeviceId dstSw = route.get(1);
737 ArrayList<ArrayList<DeviceId>> deviceRoutes =
738 routesBydevice.get(dstSw);
739 if (deviceRoutes == null) {
740 deviceRoutes = new ArrayList<>();
741 routesBydevice.put(dstSw, deviceRoutes);
742 }
743 deviceRoutes.add(route);
744 }
745 for (DeviceId impactedDstDevice : routesBydevice.keySet()) {
746 ArrayList<ArrayList<DeviceId>> deviceRoutes =
747 routesBydevice.get(impactedDstDevice);
748 for (ArrayList<DeviceId> route: deviceRoutes) {
749 log.debug("* redoRoutingIndiDst Target: {} -> dst: {}",
750 route.get(0), route.get(1));
751 DeviceId targetSw = route.get(0);
752 DeviceId dstSw = route.get(1); // same as impactedDstDevice
753 Set<DeviceId> nextHops = getNextHops(targetSw, dstSw);
Saurav Dasbd071d82018-01-09 17:38:44 -0800754 if (nextHops.isEmpty()) {
755 log.warn("Could not find next hop from target:{} --> dst {} "
756 + "skipping this route", targetSw, dstSw);
757 continue;
758 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700759 Map<DeviceId, Set<DeviceId>> nhops = new HashMap<>();
760 nhops.put(dstSw, nextHops);
761 if (!populateEcmpRoutingRulePartial(targetSw, dstSw, null, nhops,
762 (subnets == null) ? Sets.newHashSet() : subnets)) {
763 return false; // abort routing and fail fast
764 }
765 log.debug("Populating flow rules from target: {} to dst: {}"
766 + " is successful", targetSw, dstSw);
767 }
768 //Only if all the flows for all impacted routes to a
769 //specific target are pushed successfully, update the
770 //ECMP graph for that target. Or else the next event
771 //would not see any changes in the ECMP graphs.
772 //In another case, the target switch has gone away, so
773 //routes can't be installed. In that case, the current map
774 //is updated here, without any flows being pushed.
775 currentEcmpSpgMap.put(impactedDstDevice,
776 updatedEcmpSpgMap.get(impactedDstDevice));
Saurav Dasc568c342018-01-25 09:49:01 -0800777 updatedDevices.add(impactedDstDevice);
Saurav Das7bcbe702017-06-13 15:35:54 -0700778 log.debug("Updating ECMPspg for impacted dev:{}", impactedDstDevice);
779 }
780 return true;
781 }
782
783 /**
784 * Populate ECMP rules for subnets from target to destination via nexthops.
785 *
786 * @param targetSw Device ID of target switch in which rules will be programmed
787 * @param destSw1 Device ID of final destination switch to which the rules will forward
788 * @param destSw2 Device ID of paired destination switch to which the rules will forward
789 * A null deviceId indicates packets should only be sent to destSw1
790 * @param nextHops Map indication a list of next hops per destSw
791 * @param subnets Subnets to be populated. If empty, populate all configured subnets.
792 * @return true if it succeeds in populating rules
793 */ // refactor
794 private boolean populateEcmpRoutingRulePartial(DeviceId targetSw,
795 DeviceId destSw1,
796 DeviceId destSw2,
797 Map<DeviceId, Set<DeviceId>> nextHops,
798 Set<IpPrefix> subnets) {
799 boolean result;
800 // If both target switch and dest switch are edge routers, then set IP
801 // rule for both subnet and router IP.
802 boolean targetIsEdge;
803 boolean dest1IsEdge;
804 Ip4Address dest1RouterIpv4, dest2RouterIpv4 = null;
805 Ip6Address dest1RouterIpv6, dest2RouterIpv6 = null;
806
807 try {
808 targetIsEdge = config.isEdgeDevice(targetSw);
809 dest1IsEdge = config.isEdgeDevice(destSw1);
810 dest1RouterIpv4 = config.getRouterIpv4(destSw1);
811 dest1RouterIpv6 = config.getRouterIpv6(destSw1);
812 if (destSw2 != null) {
813 dest2RouterIpv4 = config.getRouterIpv4(destSw2);
814 dest2RouterIpv6 = config.getRouterIpv6(destSw2);
815 }
816 } catch (DeviceConfigNotFoundException e) {
817 log.warn(e.getMessage() + " Aborting populateEcmpRoutingRulePartial.");
Saurav Dasc88d4662017-05-15 15:34:25 -0700818 return false;
819 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700820
821 if (targetIsEdge && dest1IsEdge) {
822 subnets = (subnets != null && !subnets.isEmpty())
823 ? Sets.newHashSet(subnets)
824 : Sets.newHashSet(config.getSubnets(destSw1));
825 // XXX - Rethink this
826 /*subnets.add(dest1RouterIpv4.toIpPrefix());
827 if (dest1RouterIpv6 != null) {
828 subnets.add(dest1RouterIpv6.toIpPrefix());
829 }
830 if (destSw2 != null && dest2RouterIpv4 != null) {
831 subnets.add(dest2RouterIpv4.toIpPrefix());
832 if (dest2RouterIpv6 != null) {
833 subnets.add(dest2RouterIpv6.toIpPrefix());
834 }
835 }*/
836 log.debug(". populateEcmpRoutingRulePartial in device {} towards {} {} "
837 + "for subnets {}", targetSw, destSw1,
838 (destSw2 != null) ? ("& " + destSw2) : "",
839 subnets);
840 result = rulePopulator.populateIpRuleForSubnet(targetSw, subnets,
841 destSw1, destSw2,
842 nextHops);
843 if (!result) {
844 return false;
845 }
846 /* XXX rethink this
847 IpPrefix routerIpPrefix = destRouterIpv4.toIpPrefix();
848 log.debug("* populateEcmpRoutingRulePartial in device {} towards {} "
849 + "for router IP {}", targetSw, destSw, routerIpPrefix);
850 result = rulePopulator.populateIpRuleForRouter(targetSw, routerIpPrefix,
851 destSw, nextHops);
852 if (!result) {
853 return false;
854 }
855 // If present we deal with IPv6 loopback.
856 if (destRouterIpv6 != null) {
857 routerIpPrefix = destRouterIpv6.toIpPrefix();
858 log.debug("* populateEcmpRoutingRulePartial in device {} towards {}"
859 + " for v6 router IP {}", targetSw, destSw, routerIpPrefix);
860 result = rulePopulator.populateIpRuleForRouter(targetSw, routerIpPrefix,
861 destSw, nextHops);
862 if (!result) {
863 return false;
864 }
865 }*/
Saurav Dasc88d4662017-05-15 15:34:25 -0700866 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700867
868 if (!targetIsEdge && dest1IsEdge) {
869 // MPLS rules in all non-edge target devices. These rules are for
870 // individual destinations, even if the dsts are part of edge-pairs.
871 log.debug(". populateEcmpRoutingRulePartial in device{} towards {} for "
872 + "all MPLS rules", targetSw, destSw1);
873 result = rulePopulator.populateMplsRule(targetSw, destSw1,
874 nextHops.get(destSw1),
875 dest1RouterIpv4);
876 if (!result) {
877 return false;
878 }
879 if (dest1RouterIpv6 != null) {
880 result = rulePopulator.populateMplsRule(targetSw, destSw1,
881 nextHops.get(destSw1),
882 dest1RouterIpv6);
883 if (!result) {
884 return false;
885 }
886 }
887 }
888
889 // To save on ECMP groups
890 // avoid MPLS rules in non-edge-devices to non-edge-devices
891 // avoid MPLS transit rules in edge-devices
892 // avoid loopback IP rules in edge-devices to non-edge-devices
893 return true;
Saurav Dasc88d4662017-05-15 15:34:25 -0700894 }
895
896 /**
897 * Processes a set a route-path changes by editing hash groups.
898 *
899 * @param routeChanges a set of route-path changes, where each route-path is
900 * a list with its first element the src-switch of the path
901 * and the second element the dst-switch of the path.
902 * @param linkOrSwitchFailed true if the route changes are for a failed
903 * switch or linkDown event
904 * @param failedSwitch the switchId if the route changes are for a failed switch,
905 * otherwise null
906 */
907 private void processHashGroupChange(Set<ArrayList<DeviceId>> routeChanges,
908 boolean linkOrSwitchFailed,
909 DeviceId failedSwitch) {
Saurav Das9df5b7c2017-08-14 16:44:43 -0700910 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
911 // first, ensure each routeChanges entry has two elements
Saurav Dasc88d4662017-05-15 15:34:25 -0700912 for (ArrayList<DeviceId> route : routeChanges) {
Saurav Das9df5b7c2017-08-14 16:44:43 -0700913 if (route.size() == 1) {
914 // route-path changes are from everyone else to this switch
915 DeviceId dstSw = route.get(0);
916 srManager.deviceService.getAvailableDevices().forEach(sw -> {
917 if (!sw.id().equals(dstSw)) {
918 changedRoutes.add(Lists.newArrayList(sw.id(), dstSw));
919 }
920 });
921 } else {
922 changedRoutes.add(route);
Saurav Dasc88d4662017-05-15 15:34:25 -0700923 }
Saurav Das9df5b7c2017-08-14 16:44:43 -0700924 }
Saurav Dasc568c342018-01-25 09:49:01 -0800925 boolean someFailed = false;
926 Set<DeviceId> updatedDevices = Sets.newHashSet();
Saurav Das9df5b7c2017-08-14 16:44:43 -0700927 for (ArrayList<DeviceId> route : changedRoutes) {
928 DeviceId targetSw = route.get(0);
929 DeviceId dstSw = route.get(1);
Saurav Dasc88d4662017-05-15 15:34:25 -0700930 if (linkOrSwitchFailed) {
Saurav Das9df5b7c2017-08-14 16:44:43 -0700931 boolean success = fixHashGroupsForRoute(route, true);
Saurav Dasc88d4662017-05-15 15:34:25 -0700932 // it's possible that we cannot fix hash groups for a route
933 // if the target switch has failed. Nevertheless the ecmp graph
934 // for the impacted switch must still be updated.
Saurav Das9df5b7c2017-08-14 16:44:43 -0700935 if (!success && failedSwitch != null && targetSw.equals(failedSwitch)) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700936 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
937 currentEcmpSpgMap.remove(targetSw);
Saurav Das9df5b7c2017-08-14 16:44:43 -0700938 log.debug("Updating ECMPspg for dst:{} removing failed switch "
Saurav Dasc88d4662017-05-15 15:34:25 -0700939 + "target:{}", dstSw, targetSw);
Saurav Dasc568c342018-01-25 09:49:01 -0800940 updatedDevices.add(targetSw);
941 updatedDevices.add(dstSw);
Saurav Das9df5b7c2017-08-14 16:44:43 -0700942 continue;
Saurav Dasc88d4662017-05-15 15:34:25 -0700943 }
944 //linkfailed - update both sides
Saurav Dasc88d4662017-05-15 15:34:25 -0700945 if (success) {
946 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
Saurav Das9df5b7c2017-08-14 16:44:43 -0700947 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
Saurav Dasc568c342018-01-25 09:49:01 -0800948 log.debug("Updating ECMPspg for dst:{} and target:{} for linkdown"
949 + " or switchdown", dstSw, targetSw);
950 updatedDevices.add(targetSw);
951 updatedDevices.add(dstSw);
952 } else {
953 someFailed = true;
Saurav Das9df5b7c2017-08-14 16:44:43 -0700954 }
955 } else {
956 //linkup of seen before link
957 boolean success = fixHashGroupsForRoute(route, false);
958 if (success) {
959 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
960 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
961 log.debug("Updating ECMPspg for target:{} and dst:{} for linkup",
Saurav Dasc88d4662017-05-15 15:34:25 -0700962 targetSw, dstSw);
Saurav Dasc568c342018-01-25 09:49:01 -0800963 updatedDevices.add(targetSw);
964 updatedDevices.add(dstSw);
965 } else {
966 someFailed = true;
Saurav Dasc88d4662017-05-15 15:34:25 -0700967 }
968 }
969 }
Saurav Dasc568c342018-01-25 09:49:01 -0800970 if (!someFailed) {
971 // here is where we update all devices not touched by this instance
972 updatedEcmpSpgMap.keySet().stream()
973 .filter(devId -> !updatedDevices.contains(devId))
974 .forEach(devId -> {
975 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
976 log.debug("Updating ECMPspg for remaining dev:{}", devId);
977 });
978 }
Saurav Dasc88d4662017-05-15 15:34:25 -0700979 }
980
981 /**
982 * Edits hash groups in the src-switch (targetSw) of a route-path by
983 * calling the groupHandler to either add or remove buckets in an existing
984 * hash group.
985 *
986 * @param route a single list representing a route-path where the first element
987 * is the src-switch (targetSw) of the route-path and the
988 * second element is the dst-switch
989 * @param revoke true if buckets in the hash-groups need to be removed;
990 * false if buckets in the hash-groups need to be added
991 * @return true if the hash group editing is successful
992 */
993 private boolean fixHashGroupsForRoute(ArrayList<DeviceId> route,
994 boolean revoke) {
995 DeviceId targetSw = route.get(0);
996 if (route.size() < 2) {
997 log.warn("Cannot fixHashGroupsForRoute - no dstSw in route {}", route);
998 return false;
999 }
1000 DeviceId destSw = route.get(1);
Saurav Das9df5b7c2017-08-14 16:44:43 -07001001 log.debug("* processing fixHashGroupsForRoute: Target {} -> Dest {}",
Saurav Dasc88d4662017-05-15 15:34:25 -07001002 targetSw, destSw);
Saurav Dasc88d4662017-05-15 15:34:25 -07001003 // figure out the new next hops at the targetSw towards the destSw
Saurav Das9df5b7c2017-08-14 16:44:43 -07001004 Set<DeviceId> nextHops = getNextHops(targetSw, destSw);
Saurav Dasc88d4662017-05-15 15:34:25 -07001005 // call group handler to change hash group at targetSw
1006 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
1007 if (grpHandler == null) {
1008 log.warn("Cannot find grouphandler for dev:{} .. aborting"
1009 + " {} hash group buckets for route:{} ", targetSw,
1010 (revoke) ? "revoke" : "repopulate", route);
1011 return false;
1012 }
1013 log.debug("{} hash-groups buckets For Route {} -> {} to next-hops {}",
1014 (revoke) ? "revoke" : "repopulating",
1015 targetSw, destSw, nextHops);
1016 return (revoke) ? grpHandler.fixHashGroups(targetSw, nextHops,
1017 destSw, true)
1018 : grpHandler.fixHashGroups(targetSw, nextHops,
1019 destSw, false);
1020 }
1021
1022 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001023 * Start the flow rule population process if it was never started. The
1024 * process finishes successfully when all flow rules are set and stops with
1025 * ABORTED status when any groups required for flows is not set yet.
Saurav Dasc88d4662017-05-15 15:34:25 -07001026 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001027 public void startPopulationProcess() {
1028 statusLock.lock();
1029 try {
1030 if (populationStatus == Status.IDLE
1031 || populationStatus == Status.SUCCEEDED
1032 || populationStatus == Status.ABORTED) {
1033 populateAllRoutingRules();
sangho45b009c2015-05-07 13:30:57 -07001034 } else {
Saurav Das7bcbe702017-06-13 15:35:54 -07001035 log.warn("Not initiating startPopulationProcess as populationStatus is {}",
1036 populationStatus);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001037 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001038 } finally {
1039 statusLock.unlock();
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001040 }
sangho20eff1d2015-04-13 15:15:58 -07001041 }
1042
Saurav Dasb5c236e2016-06-07 10:08:06 -07001043 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001044 * Revoke rules of given subnet in all edge switches.
1045 *
1046 * @param subnets subnet being removed
1047 * @return true if succeed
1048 */
1049 protected boolean revokeSubnet(Set<IpPrefix> subnets) {
1050 statusLock.lock();
1051 try {
1052 return srManager.routingRulePopulator.revokeIpRuleForSubnet(subnets);
1053 } finally {
1054 statusLock.unlock();
1055 }
1056 }
1057
1058 /**
Charles Chan2fde6d42017-08-23 14:46:43 -07001059 * Populates IP rules for a route that has direct connection to the switch
1060 * if the current instance is the master of the switch.
1061 *
1062 * @param deviceId device ID of the device that next hop attaches to
1063 * @param prefix IP prefix of the route
1064 * @param hostMac MAC address of the next hop
1065 * @param hostVlanId Vlan ID of the nexthop
1066 * @param outPort port where the next hop attaches to
1067 */
1068 void populateRoute(DeviceId deviceId, IpPrefix prefix,
1069 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
1070 if (srManager.mastershipService.isLocalMaster(deviceId)) {
1071 srManager.routingRulePopulator.populateRoute(deviceId, prefix, hostMac, hostVlanId, outPort);
1072 }
1073 }
1074
1075 /**
1076 * Removes IP rules for a route when the next hop is gone.
1077 * if the current instance is the master of the switch.
1078 *
1079 * @param deviceId device ID of the device that next hop attaches to
1080 * @param prefix IP prefix of the route
1081 * @param hostMac MAC address of the next hop
1082 * @param hostVlanId Vlan ID of the nexthop
1083 * @param outPort port that next hop attaches to
1084 */
1085 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
1086 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
1087 if (srManager.mastershipService.isLocalMaster(deviceId)) {
1088 srManager.routingRulePopulator.revokeRoute(deviceId, prefix, hostMac, hostVlanId, outPort);
1089 }
1090 }
1091
1092 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001093 * Remove ECMP graph entry for the given device. Typically called when
1094 * device is no longer available.
1095 *
1096 * @param deviceId the device for which graphs need to be purged
1097 */
1098 protected void purgeEcmpGraph(DeviceId deviceId) {
Saurav Dasc568c342018-01-25 09:49:01 -08001099 statusLock.lock();
1100 try {
1101
1102 if (populationStatus == Status.STARTED) {
1103 log.warn("Previous rule population is not finished. Cannot"
1104 + " proceeed with purgeEcmpGraph for {}", deviceId);
1105 return;
1106 }
1107 log.debug("Updating ECMPspg for unavailable dev:{}", deviceId);
1108 currentEcmpSpgMap.remove(deviceId);
1109 if (updatedEcmpSpgMap != null) {
1110 updatedEcmpSpgMap.remove(deviceId);
1111 }
1112 } finally {
1113 statusLock.unlock();
Saurav Das7bcbe702017-06-13 15:35:54 -07001114 }
1115 }
1116
1117 //////////////////////////////////////
1118 // Routing helper methods and classes
1119 //////////////////////////////////////
1120
1121 /**
Saurav Das4e3224f2016-11-29 14:27:25 -08001122 * Computes set of affected routes due to failed link. Assumes
Saurav Dasb5c236e2016-06-07 10:08:06 -07001123 * previous ecmp shortest-path graph exists for a switch in order to compute
1124 * affected routes. If such a graph does not exist, the method returns null.
1125 *
1126 * @param linkFail the failed link
1127 * @return the set of affected routes which may be empty if no routes were
1128 * affected, or null if no previous ecmp spg was found for comparison
1129 */
sangho20eff1d2015-04-13 15:15:58 -07001130 private Set<ArrayList<DeviceId>> computeDamagedRoutes(Link linkFail) {
sangho20eff1d2015-04-13 15:15:58 -07001131 Set<ArrayList<DeviceId>> routes = new HashSet<>();
1132
1133 for (Device sw : srManager.deviceService.getDevices()) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001134 log.debug("Computing the impacted routes for device {} due to link fail",
1135 sw.id());
Saurav Das9df5b7c2017-08-14 16:44:43 -07001136 DeviceId retId = shouldHandleRouting(sw.id());
1137 if (retId == null) {
sangho20eff1d2015-04-13 15:15:58 -07001138 continue;
1139 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001140 Set<DeviceId> devicesToProcess = Sets.newHashSet(retId, sw.id());
1141 for (DeviceId rootSw : devicesToProcess) {
1142 EcmpShortestPathGraph ecmpSpg = currentEcmpSpgMap.get(rootSw);
1143 if (ecmpSpg == null) {
1144 log.warn("No existing ECMP graph for switch {}. Aborting optimized"
1145 + " rerouting and opting for full-reroute", rootSw);
1146 return null;
1147 }
1148 if (log.isDebugEnabled()) {
1149 log.debug("Root switch: {}", rootSw);
1150 log.debug(" Current/Existing SPG: {}", ecmpSpg);
1151 log.debug(" New/Updated SPG: {}", updatedEcmpSpgMap.get(rootSw));
1152 }
1153 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>>
1154 switchVia = ecmpSpg.getAllLearnedSwitchesAndVia();
1155 // figure out if the broken link affected any route-paths in this graph
1156 for (Integer itrIdx : switchVia.keySet()) {
1157 log.trace("Current/Exiting SPG Iterindex# {}", itrIdx);
1158 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1159 switchVia.get(itrIdx);
1160 for (DeviceId targetSw : swViaMap.keySet()) {
1161 log.trace("TargetSwitch {} --> RootSwitch {}",
1162 targetSw, rootSw);
Saurav Dasb5c236e2016-06-07 10:08:06 -07001163 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1164 log.trace(" Via:");
Pier Ventree0ae7a32016-11-23 09:57:42 -08001165 via.forEach(e -> log.trace(" {}", e));
Saurav Dasb5c236e2016-06-07 10:08:06 -07001166 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001167 Set<ArrayList<DeviceId>> subLinks =
1168 computeLinks(targetSw, rootSw, swViaMap);
1169 for (ArrayList<DeviceId> alink: subLinks) {
1170 if ((alink.get(0).equals(linkFail.src().deviceId()) &&
1171 alink.get(1).equals(linkFail.dst().deviceId()))
1172 ||
1173 (alink.get(0).equals(linkFail.dst().deviceId()) &&
1174 alink.get(1).equals(linkFail.src().deviceId()))) {
1175 log.debug("Impacted route:{}->{}", targetSw, rootSw);
1176 ArrayList<DeviceId> aRoute = new ArrayList<>();
1177 aRoute.add(targetSw); // switch with rules to populate
1178 aRoute.add(rootSw); // towards this destination
1179 routes.add(aRoute);
1180 break;
1181 }
sangho20eff1d2015-04-13 15:15:58 -07001182 }
1183 }
1184 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001185
sangho20eff1d2015-04-13 15:15:58 -07001186 }
sangho45b009c2015-05-07 13:30:57 -07001187
sangho20eff1d2015-04-13 15:15:58 -07001188 }
sangho20eff1d2015-04-13 15:15:58 -07001189 return routes;
1190 }
1191
Saurav Das4e3224f2016-11-29 14:27:25 -08001192 /**
1193 * Computes set of affected routes due to new links or failed switches.
1194 *
1195 * @return the set of affected routes which may be empty if no routes were
1196 * affected
1197 */
sangho20eff1d2015-04-13 15:15:58 -07001198 private Set<ArrayList<DeviceId>> computeRouteChange() {
Saurav Das7bcbe702017-06-13 15:35:54 -07001199 ImmutableSet.Builder<ArrayList<DeviceId>> changedRtBldr =
Saurav Das4e3224f2016-11-29 14:27:25 -08001200 ImmutableSet.builder();
sangho20eff1d2015-04-13 15:15:58 -07001201
1202 for (Device sw : srManager.deviceService.getDevices()) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001203 log.debug("Computing the impacted routes for device {}", sw.id());
1204 DeviceId retId = shouldHandleRouting(sw.id());
1205 if (retId == null) {
sangho20eff1d2015-04-13 15:15:58 -07001206 continue;
1207 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001208 Set<DeviceId> devicesToProcess = Sets.newHashSet(retId, sw.id());
1209 for (DeviceId rootSw : devicesToProcess) {
1210 if (log.isTraceEnabled()) {
1211 log.trace("Device links for dev: {}", rootSw);
1212 for (Link link: srManager.linkService.getDeviceLinks(rootSw)) {
1213 log.trace("{} -> {} ", link.src().deviceId(),
1214 link.dst().deviceId());
1215 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001216 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001217 EcmpShortestPathGraph currEcmpSpg = currentEcmpSpgMap.get(rootSw);
1218 if (currEcmpSpg == null) {
1219 log.debug("No existing ECMP graph for device {}.. adding self as "
1220 + "changed route", rootSw);
1221 changedRtBldr.add(Lists.newArrayList(rootSw));
1222 continue;
1223 }
1224 EcmpShortestPathGraph newEcmpSpg = updatedEcmpSpgMap.get(rootSw);
1225 if (log.isDebugEnabled()) {
1226 log.debug("Root switch: {}", rootSw);
1227 log.debug(" Current/Existing SPG: {}", currEcmpSpg);
1228 log.debug(" New/Updated SPG: {}", newEcmpSpg);
1229 }
1230 // first use the updated/new map to compare to current/existing map
1231 // as new links may have come up
1232 changedRtBldr.addAll(compareGraphs(newEcmpSpg, currEcmpSpg, rootSw));
1233 // then use the current/existing map to compare to updated/new map
1234 // as switch may have been removed
1235 changedRtBldr.addAll(compareGraphs(currEcmpSpg, newEcmpSpg, rootSw));
sangho45b009c2015-05-07 13:30:57 -07001236 }
Saurav Das4e3224f2016-11-29 14:27:25 -08001237 }
sangho20eff1d2015-04-13 15:15:58 -07001238
Saurav Das7bcbe702017-06-13 15:35:54 -07001239 Set<ArrayList<DeviceId>> changedRoutes = changedRtBldr.build();
Saurav Das4e3224f2016-11-29 14:27:25 -08001240 for (ArrayList<DeviceId> route: changedRoutes) {
1241 log.debug("Route changes Target -> Root");
1242 if (route.size() == 1) {
1243 log.debug(" : all -> {}", route.get(0));
1244 } else {
1245 log.debug(" : {} -> {}", route.get(0), route.get(1));
1246 }
1247 }
1248 return changedRoutes;
1249 }
1250
1251 /**
1252 * For the root switch, searches all the target nodes reachable in the base
1253 * graph, and compares paths to the ones in the comp graph.
1254 *
1255 * @param base the graph that is indexed for all reachable target nodes
1256 * from the root node
1257 * @param comp the graph that the base graph is compared to
1258 * @param rootSw both ecmp graphs are calculated for the root node
1259 * @return all the routes that have changed in the base graph
1260 */
1261 private Set<ArrayList<DeviceId>> compareGraphs(EcmpShortestPathGraph base,
1262 EcmpShortestPathGraph comp,
1263 DeviceId rootSw) {
1264 ImmutableSet.Builder<ArrayList<DeviceId>> changedRoutesBuilder =
1265 ImmutableSet.builder();
1266 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> baseMap =
1267 base.getAllLearnedSwitchesAndVia();
1268 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> compMap =
1269 comp.getAllLearnedSwitchesAndVia();
1270 for (Integer itrIdx : baseMap.keySet()) {
1271 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> baseViaMap =
1272 baseMap.get(itrIdx);
1273 for (DeviceId targetSw : baseViaMap.keySet()) {
1274 ArrayList<ArrayList<DeviceId>> basePath = baseViaMap.get(targetSw);
1275 ArrayList<ArrayList<DeviceId>> compPath = getVia(compMap, targetSw);
1276 if ((compPath == null) || !basePath.equals(compPath)) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001277 log.trace("Impacted route:{} -> {}", targetSw, rootSw);
Saurav Das4e3224f2016-11-29 14:27:25 -08001278 ArrayList<DeviceId> route = new ArrayList<>();
Saurav Das7bcbe702017-06-13 15:35:54 -07001279 route.add(targetSw); // switch with rules to populate
1280 route.add(rootSw); // towards this destination
Saurav Das4e3224f2016-11-29 14:27:25 -08001281 changedRoutesBuilder.add(route);
sangho20eff1d2015-04-13 15:15:58 -07001282 }
1283 }
sangho45b009c2015-05-07 13:30:57 -07001284 }
Saurav Das4e3224f2016-11-29 14:27:25 -08001285 return changedRoutesBuilder.build();
sangho20eff1d2015-04-13 15:15:58 -07001286 }
1287
Saurav Das7bcbe702017-06-13 15:35:54 -07001288 /**
1289 * Returns the ECMP paths traversed to reach the target switch.
1290 *
1291 * @param switchVia a per-iteration view of the ECMP graph for a root switch
1292 * @param targetSw the switch to reach from the root switch
1293 * @return the nodes traversed on ECMP paths to the target switch
1294 */
sangho20eff1d2015-04-13 15:15:58 -07001295 private ArrayList<ArrayList<DeviceId>> getVia(HashMap<Integer, HashMap<DeviceId,
Saurav Das4e3224f2016-11-29 14:27:25 -08001296 ArrayList<ArrayList<DeviceId>>>> switchVia, DeviceId targetSw) {
sangho20eff1d2015-04-13 15:15:58 -07001297 for (Integer itrIdx : switchVia.keySet()) {
1298 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1299 switchVia.get(itrIdx);
Saurav Das4e3224f2016-11-29 14:27:25 -08001300 if (swViaMap.get(targetSw) == null) {
sangho20eff1d2015-04-13 15:15:58 -07001301 continue;
1302 } else {
Saurav Das4e3224f2016-11-29 14:27:25 -08001303 return swViaMap.get(targetSw);
sangho20eff1d2015-04-13 15:15:58 -07001304 }
1305 }
1306
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001307 return null;
sangho20eff1d2015-04-13 15:15:58 -07001308 }
1309
Saurav Das7bcbe702017-06-13 15:35:54 -07001310 /**
1311 * Utility method to break down a path from src to dst device into a collection
1312 * of links.
1313 *
1314 * @param src src device of the path
1315 * @param dst dst device of the path
1316 * @param viaMap path taken from src to dst device
1317 * @return collection of links in the path
1318 */
sangho20eff1d2015-04-13 15:15:58 -07001319 private Set<ArrayList<DeviceId>> computeLinks(DeviceId src,
1320 DeviceId dst,
1321 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> viaMap) {
1322 Set<ArrayList<DeviceId>> subLinks = Sets.newHashSet();
1323 for (ArrayList<DeviceId> via : viaMap.get(src)) {
1324 DeviceId linkSrc = src;
1325 DeviceId linkDst = dst;
1326 for (DeviceId viaDevice: via) {
1327 ArrayList<DeviceId> link = new ArrayList<>();
1328 linkDst = viaDevice;
1329 link.add(linkSrc);
1330 link.add(linkDst);
1331 subLinks.add(link);
1332 linkSrc = viaDevice;
1333 }
1334 ArrayList<DeviceId> link = new ArrayList<>();
1335 link.add(linkSrc);
1336 link.add(dst);
1337 subLinks.add(link);
1338 }
1339
1340 return subLinks;
1341 }
1342
Charles Chan93e71ba2016-04-29 14:38:22 -07001343 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001344 * Determines whether this controller instance should handle routing for the
1345 * given {@code deviceId}, based on mastership and pairDeviceId if one exists.
1346 * Returns null if this instance should not handle routing for given {@code deviceId}.
1347 * Otherwise the returned value could be the given deviceId itself, or the
1348 * deviceId for the paired edge device. In the latter case, this instance
1349 * should handle routing for both the given device and the paired device.
Charles Chan93e71ba2016-04-29 14:38:22 -07001350 *
Saurav Das7bcbe702017-06-13 15:35:54 -07001351 * @param deviceId device identifier to consider for routing
1352 * @return null or deviceId which could be the same as the given deviceId
1353 * or the deviceId of a paired edge device
Charles Chan93e71ba2016-04-29 14:38:22 -07001354 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001355 private DeviceId shouldHandleRouting(DeviceId deviceId) {
1356 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1357 log.debug("Not master for dev:{} .. skipping routing, may get handled "
1358 + "elsewhere as part of paired devices", deviceId);
1359 return null;
1360 }
1361 NodeId myNode = srManager.mastershipService.getMasterFor(deviceId);
1362 DeviceId pairDev = getPairDev(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001363
Saurav Das7bcbe702017-06-13 15:35:54 -07001364 if (pairDev != null) {
1365 if (!srManager.deviceService.isAvailable(pairDev)) {
1366 log.warn("pairedDev {} not available .. routing this dev:{} "
1367 + "without mastership check",
1368 pairDev, deviceId);
1369 return pairDev; // handle both temporarily
1370 }
1371 NodeId pairMasterNode = srManager.mastershipService.getMasterFor(pairDev);
1372 if (myNode.compareTo(pairMasterNode) <= 0) {
1373 log.debug("Handling routing for both dev:{} pair-dev:{}; myNode: {}"
1374 + " pairMaster:{} compare:{}", deviceId, pairDev,
1375 myNode, pairMasterNode,
1376 myNode.compareTo(pairMasterNode));
1377 return pairDev; // handle both
1378 } else {
1379 log.debug("PairDev node: {} should handle routing for dev:{} and "
1380 + "pair-dev:{}", pairMasterNode, deviceId, pairDev);
1381 return null; // handle neither
sanghob35a6192015-04-01 13:05:26 -07001382 }
1383 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001384 return deviceId; // not paired, just handle given device
sanghob35a6192015-04-01 13:05:26 -07001385 }
1386
Charles Chan93e71ba2016-04-29 14:38:22 -07001387 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001388 * Returns the configured paired DeviceId for the given Device, or null
1389 * if no such paired device has been configured.
Charles Chan93e71ba2016-04-29 14:38:22 -07001390 *
Saurav Das7bcbe702017-06-13 15:35:54 -07001391 * @param deviceId
1392 * @return configured pair deviceId or null
Charles Chan93e71ba2016-04-29 14:38:22 -07001393 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001394 private DeviceId getPairDev(DeviceId deviceId) {
1395 DeviceId pairDev;
Charles Chan0b4e6182015-11-03 10:42:14 -08001396 try {
Saurav Das7bcbe702017-06-13 15:35:54 -07001397 pairDev = srManager.deviceConfiguration.getPairDeviceId(deviceId);
Charles Chan0b4e6182015-11-03 10:42:14 -08001398 } catch (DeviceConfigNotFoundException e) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001399 log.warn(e.getMessage() + " .. cannot continue routing for dev: {}");
1400 return null;
Charles Chan0b4e6182015-11-03 10:42:14 -08001401 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001402 return pairDev;
sanghob35a6192015-04-01 13:05:26 -07001403 }
1404
1405 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001406 * Returns the set of deviceIds which are the next hops from the targetSw
1407 * to the dstSw according to the latest ECMP spg.
1408 *
1409 * @param targetSw the switch for which the next-hops are desired
1410 * @param dstSw the switch to which the next-hops lead to from the targetSw
1411 * @return set of next hop deviceIds, could be empty if no next hops are found
1412 */
1413 private Set<DeviceId> getNextHops(DeviceId targetSw, DeviceId dstSw) {
1414 boolean targetIsEdge = false;
1415 try {
1416 targetIsEdge = srManager.deviceConfiguration.isEdgeDevice(targetSw);
1417 } catch (DeviceConfigNotFoundException e) {
1418 log.warn(e.getMessage() + "Cannot determine if targetIsEdge {}.. "
1419 + "continuing to getNextHops", targetSw);
1420 }
1421
1422 EcmpShortestPathGraph ecmpSpg = updatedEcmpSpgMap.get(dstSw);
1423 if (ecmpSpg == null) {
1424 log.debug("No ecmpSpg found for dstSw: {}", dstSw);
1425 return ImmutableSet.of();
1426 }
1427 HashMap<Integer,
1428 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> switchVia =
1429 ecmpSpg.getAllLearnedSwitchesAndVia();
1430 for (Integer itrIdx : switchVia.keySet()) {
1431 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1432 switchVia.get(itrIdx);
1433 for (DeviceId target : swViaMap.keySet()) {
1434 if (!target.equals(targetSw)) {
1435 continue;
1436 }
1437 if (!targetIsEdge && itrIdx > 1) {
1438 // optimization for spines to not use other leaves to get
1439 // to a leaf to avoid loops
1440 log.debug("Avoiding {} hop path for non-edge targetSw:{}"
1441 + " --> dstSw:{}", itrIdx, targetSw, dstSw);
1442 break;
1443 }
1444 Set<DeviceId> nextHops = new HashSet<>();
1445 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1446 if (via.isEmpty()) {
1447 // the dstSw is the next-hop from the targetSw
1448 nextHops.add(dstSw);
1449 } else {
1450 // first elem is next-hop in each ECMP path
1451 nextHops.add(via.get(0));
1452 }
1453 }
1454 return nextHops;
1455 }
1456 }
1457 return ImmutableSet.of(); //no next-hops found
1458 }
1459
1460 /**
1461 * Represents two devices that are paired by configuration. An EdgePair for
1462 * (dev1, dev2) is the same as as EdgePair for (dev2, dev1)
1463 */
1464 protected final class EdgePair {
1465 DeviceId dev1;
1466 DeviceId dev2;
1467
1468 EdgePair(DeviceId dev1, DeviceId dev2) {
1469 this.dev1 = dev1;
1470 this.dev2 = dev2;
1471 }
1472
1473 boolean includes(DeviceId dev) {
1474 return dev1.equals(dev) || dev2.equals(dev);
1475 }
1476
1477 @Override
1478 public boolean equals(Object o) {
1479 if (this == o) {
1480 return true;
1481 }
1482 if (!(o instanceof EdgePair)) {
1483 return false;
1484 }
1485 EdgePair that = (EdgePair) o;
1486 return ((this.dev1.equals(that.dev1) && this.dev2.equals(that.dev2)) ||
1487 (this.dev1.equals(that.dev2) && this.dev2.equals(that.dev1)));
1488 }
1489
1490 @Override
1491 public int hashCode() {
1492 if (dev1.toString().compareTo(dev2.toString()) <= 0) {
1493 return Objects.hash(dev1, dev2);
1494 } else {
1495 return Objects.hash(dev2, dev1);
1496 }
1497 }
1498
1499 @Override
1500 public String toString() {
1501 return toStringHelper(this)
1502 .add("Dev1", dev1)
1503 .add("Dev2", dev2)
1504 .toString();
1505 }
1506 }
1507
1508 //////////////////////////////////////
1509 // Filtering rule creation
1510 //////////////////////////////////////
1511
1512 /**
Saurav Das018605f2017-02-18 14:05:44 -08001513 * Populates filtering rules for port, and punting rules
1514 * for gateway IPs, loopback IPs and arp/ndp traffic.
1515 * Should only be called by the master instance for this device/port.
sanghob35a6192015-04-01 13:05:26 -07001516 *
1517 * @param deviceId Switch ID to set the rules
1518 */
Saurav Das822c4e22015-10-23 10:51:11 -07001519 public void populatePortAddressingRules(DeviceId deviceId) {
Saurav Das59232cf2016-04-27 18:35:50 -07001520 // Although device is added, sometimes device store does not have the
1521 // ports for this device yet. It results in missing filtering rules in the
1522 // switch. We will attempt it a few times. If it still does not work,
1523 // user can manually repopulate using CLI command sr-reroute-network
Charles Chanf6ec1532017-02-08 16:10:40 -08001524 PortFilterInfo firstRun = rulePopulator.populateVlanMacFilters(deviceId);
Saurav Dasd2fded02016-12-02 15:43:47 -08001525 if (firstRun == null) {
1526 firstRun = new PortFilterInfo(0, 0, 0);
Saurav Das59232cf2016-04-27 18:35:50 -07001527 }
Saurav Dasd2fded02016-12-02 15:43:47 -08001528 executorService.schedule(new RetryFilters(deviceId, firstRun),
1529 RETRY_INTERVAL_MS, TimeUnit.MILLISECONDS);
sanghob35a6192015-04-01 13:05:26 -07001530 }
1531
1532 /**
Saurav Dasd2fded02016-12-02 15:43:47 -08001533 * Utility class used to temporarily store information about the ports on a
1534 * device processed for filtering objectives.
Saurav Dasd2fded02016-12-02 15:43:47 -08001535 */
1536 public final class PortFilterInfo {
Saurav Das018605f2017-02-18 14:05:44 -08001537 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das59232cf2016-04-27 18:35:50 -07001538
Saurav Das018605f2017-02-18 14:05:44 -08001539 public PortFilterInfo(int disabledPorts, int errorPorts,
Saurav Dasd2fded02016-12-02 15:43:47 -08001540 int filteredPorts) {
1541 this.disabledPorts = disabledPorts;
1542 this.filteredPorts = filteredPorts;
Saurav Das018605f2017-02-18 14:05:44 -08001543 this.errorPorts = errorPorts;
Saurav Dasd2fded02016-12-02 15:43:47 -08001544 }
1545
1546 @Override
1547 public int hashCode() {
Saurav Das018605f2017-02-18 14:05:44 -08001548 return Objects.hash(disabledPorts, filteredPorts, errorPorts);
Saurav Dasd2fded02016-12-02 15:43:47 -08001549 }
1550
1551 @Override
1552 public boolean equals(Object obj) {
1553 if (this == obj) {
1554 return true;
1555 }
1556 if ((obj == null) || (!(obj instanceof PortFilterInfo))) {
1557 return false;
1558 }
1559 PortFilterInfo other = (PortFilterInfo) obj;
1560 return ((disabledPorts == other.disabledPorts) &&
1561 (filteredPorts == other.filteredPorts) &&
Saurav Das018605f2017-02-18 14:05:44 -08001562 (errorPorts == other.errorPorts));
Saurav Dasd2fded02016-12-02 15:43:47 -08001563 }
1564
1565 @Override
1566 public String toString() {
1567 MoreObjects.ToStringHelper helper = toStringHelper(this)
1568 .add("disabledPorts", disabledPorts)
Saurav Das018605f2017-02-18 14:05:44 -08001569 .add("errorPorts", errorPorts)
Saurav Dasd2fded02016-12-02 15:43:47 -08001570 .add("filteredPorts", filteredPorts);
1571 return helper.toString();
1572 }
1573 }
1574
1575 /**
1576 * RetryFilters populates filtering objectives for a device and keeps retrying
1577 * till the number of ports filtered are constant for a predefined number
1578 * of attempts.
1579 */
1580 protected final class RetryFilters implements Runnable {
1581 int constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS;
1582 DeviceId devId;
1583 int counter;
1584 PortFilterInfo prevRun;
1585
1586 private RetryFilters(DeviceId deviceId, PortFilterInfo previousRun) {
Saurav Das59232cf2016-04-27 18:35:50 -07001587 devId = deviceId;
Saurav Dasd2fded02016-12-02 15:43:47 -08001588 prevRun = previousRun;
1589 counter = 0;
Saurav Das59232cf2016-04-27 18:35:50 -07001590 }
1591
1592 @Override
1593 public void run() {
Charles Chan7f9737b2017-06-22 14:27:17 -07001594 log.debug("RETRY FILTER ATTEMPT {} ** dev:{}", ++counter, devId);
Charles Chanf6ec1532017-02-08 16:10:40 -08001595 PortFilterInfo thisRun = rulePopulator.populateVlanMacFilters(devId);
Saurav Dasd2fded02016-12-02 15:43:47 -08001596 boolean sameResult = prevRun.equals(thisRun);
1597 log.debug("dev:{} prevRun:{} thisRun:{} sameResult:{}", devId, prevRun,
1598 thisRun, sameResult);
1599 if (thisRun == null || !sameResult || (sameResult && --constantAttempts > 0)) {
Saurav Das018605f2017-02-18 14:05:44 -08001600 // exponentially increasing intervals for retries
1601 executorService.schedule(this,
1602 RETRY_INTERVAL_MS * (int) Math.pow(counter, RETRY_INTERVAL_SCALE),
1603 TimeUnit.MILLISECONDS);
Saurav Dasd2fded02016-12-02 15:43:47 -08001604 if (!sameResult) {
1605 constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS; //reset
1606 }
Saurav Das59232cf2016-04-27 18:35:50 -07001607 }
Saurav Dasd2fded02016-12-02 15:43:47 -08001608 prevRun = (thisRun == null) ? prevRun : thisRun;
Saurav Das59232cf2016-04-27 18:35:50 -07001609 }
Saurav Das59232cf2016-04-27 18:35:50 -07001610 }
1611
sanghob35a6192015-04-01 13:05:26 -07001612}