blob: 3aed5ccc04755411743b1efed4f33c0cde41b8f6 [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());
271 if (log.isDebugEnabled()) {
272 log.debug("Root switch: {}", entry.getKey());
273 log.debug(" Current/Existing SPG: {}", entry.getValue());
274 }
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) {
341 log.warn(e.getMessage() + "aborting populateSubnet");
342 populationStatus = Status.ABORTED;
343 return;
344 }
345 if (dstSw.equals(targetSw.id()) || !isEdge ||
346 (cpts.size() == 2 &&
347 targetSw.id().equals(getPairDev(dstSw)))) {
348 continue;
349 }
350 routeChanges.add(Lists.newArrayList(targetSw.id(), dstSw));
351 }
352 }
353
354 if (!redoRouting(routeChanges, edgePairs, subnets)) {
355 log.debug("populateSubnet: populationStatus is ABORTED");
356 populationStatus = Status.ABORTED;
357 log.warn("Failed to repopulate the rules for subnet.");
358 return;
359 }
360
361 log.debug("populateSubnet: populationStatus is SUCCEEDED");
362 populationStatus = Status.SUCCEEDED;
363 log.info("Completed subnet population. Total # of rules pushed : {}",
364 rulePopulator.getCounter());
365 return;
366
367 } finally {
368 statusLock.unlock();
369 }
370 }
371
372 /**
Saurav Dasc88d4662017-05-15 15:34:25 -0700373 * Populates the routing rules or makes hash group changes according to the
374 * route-path changes due to link failure, switch failure or link up. This
375 * method should only be called for one of these three possible event-types.
376 * Note that when a switch goes away, all of its links fail as well,
377 * but this is handled as a single switch removal event.
sangho20eff1d2015-04-13 15:15:58 -0700378 *
Saurav Dasc88d4662017-05-15 15:34:25 -0700379 * @param linkDown the single failed link, or null for other conditions
380 * such as link-up or a removed switch
381 * @param linkUp the single link up, or null for other conditions such as
382 * link-down or a removed switch
383 * @param switchDown the removed switch, or null for other conditions such as
384 * link-down or link-up
Saurav Das7bcbe702017-06-13 15:35:54 -0700385 */ // refactor
Saurav Dasc88d4662017-05-15 15:34:25 -0700386 public void populateRoutingRulesForLinkStatusChange(Link linkDown,
387 Link linkUp,
388 DeviceId switchDown) {
389 if ((linkDown != null && (linkUp != null || switchDown != null)) ||
390 (linkUp != null && (linkDown != null || switchDown != null)) ||
391 (switchDown != null && (linkUp != null || linkDown != null))) {
392 log.warn("Only one event can be handled for link status change .. aborting");
393 return;
394 }
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700395 lastRoutingChange = Instant.now();
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900396 statusLock.lock();
397 try {
sangho20eff1d2015-04-13 15:15:58 -0700398
399 if (populationStatus == Status.STARTED) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700400 log.warn("Previous rule population is not finished. Cannot"
Saurav Dasc568c342018-01-25 09:49:01 -0800401 + " proceeed with routingRules for Topology change");
Saurav Dasc88d4662017-05-15 15:34:25 -0700402 return;
sangho20eff1d2015-04-13 15:15:58 -0700403 }
404
Saurav Das7bcbe702017-06-13 15:35:54 -0700405 // Take snapshots of the topology
sangho45b009c2015-05-07 13:30:57 -0700406 updatedEcmpSpgMap = new HashMap<>();
Saurav Das7bcbe702017-06-13 15:35:54 -0700407 Set<EdgePair> edgePairs = new HashSet<>();
sangho45b009c2015-05-07 13:30:57 -0700408 for (Device sw : srManager.deviceService.getDevices()) {
Shashikanth VH013a7bc2015-12-11 01:32:44 +0530409 EcmpShortestPathGraph ecmpSpgUpdated =
410 new EcmpShortestPathGraph(sw.id(), srManager);
sangho45b009c2015-05-07 13:30:57 -0700411 updatedEcmpSpgMap.put(sw.id(), ecmpSpgUpdated);
Saurav Das7bcbe702017-06-13 15:35:54 -0700412 DeviceId pairDev = getPairDev(sw.id());
413 if (pairDev != null) {
414 // pairDev may not be available yet, but we still need to add
415 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev, srManager);
416 updatedEcmpSpgMap.put(pairDev, ecmpSpgUpdated);
417 edgePairs.add(new EdgePair(sw.id(), pairDev));
418 }
sangho45b009c2015-05-07 13:30:57 -0700419 }
420
Saurav Dasc568c342018-01-25 09:49:01 -0800421 log.info("Starting to populate routing rules from Topology change");
sangho52abe3a2015-05-05 14:13:34 -0700422
sangho20eff1d2015-04-13 15:15:58 -0700423 Set<ArrayList<DeviceId>> routeChanges;
Saurav Dasc88d4662017-05-15 15:34:25 -0700424 log.debug("populateRoutingRulesForLinkStatusChange: "
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700425 + "populationStatus is STARTED");
sangho20eff1d2015-04-13 15:15:58 -0700426 populationStatus = Status.STARTED;
Saurav Dasc568c342018-01-25 09:49:01 -0800427 rulePopulator.resetCounter(); //XXX maybe useful to have a rehash ctr
428 boolean hashGroupsChanged = false;
Saurav Das4e3224f2016-11-29 14:27:25 -0800429 // try optimized re-routing
Saurav Dasc88d4662017-05-15 15:34:25 -0700430 if (linkDown == null) {
431 // either a linkUp or a switchDown - compute all route changes by
432 // comparing all routes of existing ECMP SPG to new ECMP SPG
sangho20eff1d2015-04-13 15:15:58 -0700433 routeChanges = computeRouteChange();
Saurav Dasc88d4662017-05-15 15:34:25 -0700434
Saurav Das9df5b7c2017-08-14 16:44:43 -0700435 // deal with linkUp of a seen-before link
Saurav Das45f48152018-01-18 12:07:33 -0800436 if (linkUp != null && srManager.linkHandler.isSeenLink(linkUp)) {
437 if (!srManager.linkHandler.isBidirectional(linkUp)) {
Saurav Das9df5b7c2017-08-14 16:44:43 -0700438 log.warn("Not a bidirectional link yet .. not "
439 + "processing link {}", linkUp);
Saurav Das45f48152018-01-18 12:07:33 -0800440 srManager.linkHandler.updateSeenLink(linkUp, true);
Saurav Das9df5b7c2017-08-14 16:44:43 -0700441 populationStatus = Status.ABORTED;
442 return;
Saurav Dasc88d4662017-05-15 15:34:25 -0700443 }
Saurav Das9df5b7c2017-08-14 16:44:43 -0700444 // link previously seen before
445 // do hash-bucket changes instead of a re-route
446 processHashGroupChange(routeChanges, false, null);
447 // clear out routesChanges so a re-route is not attempted
448 routeChanges = ImmutableSet.of();
Saurav Dasc568c342018-01-25 09:49:01 -0800449 hashGroupsChanged = true;
Saurav Dasc88d4662017-05-15 15:34:25 -0700450 }
Saurav Das9df5b7c2017-08-14 16:44:43 -0700451 // for a linkUp of a never-seen-before link
452 // let it fall through to a reroute of the routeChanges
Saurav Dasc88d4662017-05-15 15:34:25 -0700453
454 // now that we are past the check for a previously seen link
455 // it is safe to update the store for the linkUp
456 if (linkUp != null) {
Saurav Das45f48152018-01-18 12:07:33 -0800457 srManager.linkHandler.updateSeenLink(linkUp, true);
Saurav Dasc88d4662017-05-15 15:34:25 -0700458 }
459
Saurav Das9df5b7c2017-08-14 16:44:43 -0700460 //deal with switchDown
461 if (switchDown != null) {
462 processHashGroupChange(routeChanges, true, switchDown);
463 // clear out routesChanges so a re-route is not attempted
464 routeChanges = ImmutableSet.of();
Saurav Dasc568c342018-01-25 09:49:01 -0800465 hashGroupsChanged = true;
Saurav Das9df5b7c2017-08-14 16:44:43 -0700466 }
sangho20eff1d2015-04-13 15:15:58 -0700467 } else {
Saurav Dasc88d4662017-05-15 15:34:25 -0700468 // link has gone down
469 // Compare existing ECMP SPG only with the link that went down
470 routeChanges = computeDamagedRoutes(linkDown);
471 if (routeChanges != null) {
472 processHashGroupChange(routeChanges, true, null);
473 // clear out routesChanges so a re-route is not attempted
474 routeChanges = ImmutableSet.of();
Saurav Dasc568c342018-01-25 09:49:01 -0800475 hashGroupsChanged = true;
Saurav Dasc88d4662017-05-15 15:34:25 -0700476 }
sangho20eff1d2015-04-13 15:15:58 -0700477 }
478
Saurav Das4e3224f2016-11-29 14:27:25 -0800479 // do full re-routing if optimized routing returns null routeChanges
Saurav Dasb5c236e2016-06-07 10:08:06 -0700480 if (routeChanges == null) {
Saurav Dasc568c342018-01-25 09:49:01 -0800481 log.warn("Optimized routing failed... opting for full reroute");
Saurav Das7bcbe702017-06-13 15:35:54 -0700482 populationStatus = Status.ABORTED;
Saurav Dasc88d4662017-05-15 15:34:25 -0700483 populateAllRoutingRules();
484 return;
Saurav Dasb5c236e2016-06-07 10:08:06 -0700485 }
486
sangho20eff1d2015-04-13 15:15:58 -0700487 if (routeChanges.isEmpty()) {
Saurav Dasc568c342018-01-25 09:49:01 -0800488 if (hashGroupsChanged) {
489 log.info("Hash-groups changed for link status change");
490 } else {
491 log.info("No re-route or re-hash attempted for the link"
492 + " status change");
493 updatedEcmpSpgMap.keySet().forEach(devId -> {
494 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
495 log.debug("Updating ECMPspg for remaining dev:{}", devId);
496 });
497 }
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700498 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sangho20eff1d2015-04-13 15:15:58 -0700499 populationStatus = Status.SUCCEEDED;
Saurav Dasc88d4662017-05-15 15:34:25 -0700500 return;
sangho20eff1d2015-04-13 15:15:58 -0700501 }
502
Saurav Dasc88d4662017-05-15 15:34:25 -0700503 // reroute of routeChanges
Saurav Das7bcbe702017-06-13 15:35:54 -0700504 if (redoRouting(routeChanges, edgePairs, null)) {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700505 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sangho20eff1d2015-04-13 15:15:58 -0700506 populationStatus = Status.SUCCEEDED;
Saurav Das7bcbe702017-06-13 15:35:54 -0700507 log.info("Completed repopulation of rules for link-status change."
508 + " # of rules populated : {}", rulePopulator.getCounter());
Saurav Dasc88d4662017-05-15 15:34:25 -0700509 return;
sangho20eff1d2015-04-13 15:15:58 -0700510 } else {
Srikanth Vavilapalli23181912015-05-04 09:48:09 -0700511 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is ABORTED");
sangho20eff1d2015-04-13 15:15:58 -0700512 populationStatus = Status.ABORTED;
Saurav Das7bcbe702017-06-13 15:35:54 -0700513 log.warn("Failed to repopulate the rules for link status change.");
Saurav Dasc88d4662017-05-15 15:34:25 -0700514 return;
sangho20eff1d2015-04-13 15:15:58 -0700515 }
HIGUCHI Yuta84a25fc2015-09-08 16:16:31 +0900516 } finally {
517 statusLock.unlock();
sangho20eff1d2015-04-13 15:15:58 -0700518 }
519 }
520
Saurav Dasc88d4662017-05-15 15:34:25 -0700521 /**
Saurav Das7bcbe702017-06-13 15:35:54 -0700522 * Processes a set a route-path changes by reprogramming routing rules and
523 * creating new hash-groups or editing them if necessary. This method also
524 * determines the next-hops for the route-path from the src-switch (target)
525 * of the path towards the dst-switch of the path.
Saurav Dasc88d4662017-05-15 15:34:25 -0700526 *
Saurav Das7bcbe702017-06-13 15:35:54 -0700527 * @param routeChanges a set of route-path changes, where each route-path is
528 * a list with its first element the src-switch (target)
529 * of the path, and the second element the dst-switch of
530 * the path.
531 * @param edgePairs a set of edge-switches that are paired by configuration
532 * @param subnets a set of prefixes that need to be populated in the routing
533 * table of the target switch in the route-path. Can be null,
534 * in which case all the prefixes belonging to the dst-switch
535 * will be populated in the target switch
536 * @return true if successful in repopulating all routes
Saurav Dasc88d4662017-05-15 15:34:25 -0700537 */
Saurav Das7bcbe702017-06-13 15:35:54 -0700538 private boolean redoRouting(Set<ArrayList<DeviceId>> routeChanges,
539 Set<EdgePair> edgePairs, Set<IpPrefix> subnets) {
540 // first make every entry two-elements
541 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
542 for (ArrayList<DeviceId> route : routeChanges) {
543 if (route.size() == 1) {
544 DeviceId dstSw = route.get(0);
545 EcmpShortestPathGraph ec = updatedEcmpSpgMap.get(dstSw);
546 if (ec == null) {
547 log.warn("No graph found for {} .. aborting redoRouting", dstSw);
548 return false;
549 }
550 ec.getAllLearnedSwitchesAndVia().keySet().forEach(key -> {
551 ec.getAllLearnedSwitchesAndVia().get(key).keySet().forEach(target -> {
552 changedRoutes.add(Lists.newArrayList(target, dstSw));
553 });
554 });
555 } else {
556 DeviceId targetSw = route.get(0);
557 DeviceId dstSw = route.get(1);
558 changedRoutes.add(Lists.newArrayList(targetSw, dstSw));
559 }
560 }
561
562 // now process changedRoutes according to edgePairs
563 if (!redoRoutingEdgePairs(edgePairs, subnets, changedRoutes)) {
564 return false; //abort routing and fail fast
565 }
566
567 // whatever is left in changedRoutes is now processed for individual dsts.
Saurav Dasc568c342018-01-25 09:49:01 -0800568 Set<DeviceId> updatedDevices = Sets.newHashSet();
569 if (!redoRoutingIndividualDests(subnets, changedRoutes,
570 updatedDevices)) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700571 return false; //abort routing and fail fast
572 }
573
Saurav Das7bcbe702017-06-13 15:35:54 -0700574 // update ecmpSPG for all edge-pairs
575 for (EdgePair ep : edgePairs) {
576 currentEcmpSpgMap.put(ep.dev1, updatedEcmpSpgMap.get(ep.dev1));
577 currentEcmpSpgMap.put(ep.dev2, updatedEcmpSpgMap.get(ep.dev2));
578 log.debug("Updating ECMPspg for edge-pair:{}-{}", ep.dev1, ep.dev2);
579 }
Saurav Dasc568c342018-01-25 09:49:01 -0800580
581 // here is where we update all devices not touched by this instance
582 updatedEcmpSpgMap.keySet().stream()
583 .filter(devId -> !edgePairs.stream().anyMatch(ep -> ep.includes(devId)))
584 .filter(devId -> !updatedDevices.contains(devId))
585 .forEach(devId -> {
586 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
587 log.debug("Updating ECMPspg for remaining dev:{}", devId);
588 });
Saurav Das7bcbe702017-06-13 15:35:54 -0700589 return true;
590 }
591
592 /**
593 * Programs targetSw in the changedRoutes for given prefixes reachable by
594 * an edgePair. If no prefixes are given, the method will use configured
595 * subnets/prefixes. If some configured subnets belong only to a specific
596 * destination in the edgePair, then the target switch will be programmed
597 * only to that destination.
598 *
599 * @param edgePairs set of edge-pairs for which target will be programmed
600 * @param subnets a set of prefixes that need to be populated in the routing
601 * table of the target switch in the changedRoutes. Can be null,
602 * in which case all the configured prefixes belonging to the
603 * paired switches will be populated in the target switch
604 * @param changedRoutes a set of route-path changes, where each route-path is
605 * a list with its first element the src-switch (target)
606 * of the path, and the second element the dst-switch of
607 * the path.
608 * @return true if successful
609 */
610 private boolean redoRoutingEdgePairs(Set<EdgePair> edgePairs,
611 Set<IpPrefix> subnets,
612 Set<ArrayList<DeviceId>> changedRoutes) {
613 for (EdgePair ep : edgePairs) {
614 // temp store for a target's changedRoutes to this edge-pair
615 Map<DeviceId, Set<ArrayList<DeviceId>>> targetRoutes = new HashMap<>();
616 Iterator<ArrayList<DeviceId>> i = changedRoutes.iterator();
617 while (i.hasNext()) {
618 ArrayList<DeviceId> route = i.next();
619 DeviceId dstSw = route.get(1);
620 if (ep.includes(dstSw)) {
621 // routeChange for edge pair found
622 // sort by target iff target is edge and remove from changedRoutes
623 DeviceId targetSw = route.get(0);
624 try {
625 if (!srManager.deviceConfiguration.isEdgeDevice(targetSw)) {
626 continue;
627 }
628 } catch (DeviceConfigNotFoundException e) {
629 log.warn(e.getMessage() + "aborting redoRouting");
630 return false;
631 }
632 // route is from another edge to this edge-pair
633 if (targetRoutes.containsKey(targetSw)) {
634 targetRoutes.get(targetSw).add(route);
635 } else {
636 Set<ArrayList<DeviceId>> temp = new HashSet<>();
637 temp.add(route);
638 targetRoutes.put(targetSw, temp);
639 }
640 i.remove();
641 }
642 }
643 // so now for this edgepair we have a per target set of routechanges
644 // process target->edgePair route
645 for (Map.Entry<DeviceId, Set<ArrayList<DeviceId>>> entry :
646 targetRoutes.entrySet()) {
647 log.debug("* redoRoutingDstPair Target:{} -> edge-pair {}",
648 entry.getKey(), ep);
649 DeviceId targetSw = entry.getKey();
650 Map<DeviceId, Set<DeviceId>> perDstNextHops = new HashMap<>();
651 entry.getValue().forEach(route -> {
652 Set<DeviceId> nhops = getNextHops(route.get(0), route.get(1));
653 log.debug("route: target {} -> dst {} found with next-hops {}",
654 route.get(0), route.get(1), nhops);
655 perDstNextHops.put(route.get(1), nhops);
656 });
657 Set<IpPrefix> ipDev1 = (subnets == null) ? config.getSubnets(ep.dev1)
658 : subnets;
659 Set<IpPrefix> ipDev2 = (subnets == null) ? config.getSubnets(ep.dev2)
660 : subnets;
661 ipDev1 = (ipDev1 == null) ? Sets.newHashSet() : ipDev1;
662 ipDev2 = (ipDev2 == null) ? Sets.newHashSet() : ipDev2;
Saurav Dasc568c342018-01-25 09:49:01 -0800663 Set<DeviceId> nhDev1 = perDstNextHops.get(ep.dev1);
664 Set<DeviceId> nhDev2 = perDstNextHops.get(ep.dev2);
Saurav Das7bcbe702017-06-13 15:35:54 -0700665 // handle routing to subnets common to edge-pair
Saurav Dasc568c342018-01-25 09:49:01 -0800666 // only if the targetSw is not part of the edge-pair and there
667 // exists a next hop to at least one of the devices in the edge-pair
668 if (!ep.includes(targetSw)
669 && ((nhDev1 != null && !nhDev1.isEmpty())
670 || (nhDev2 != null && !nhDev2.isEmpty()))) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700671 if (!populateEcmpRoutingRulePartial(
672 targetSw,
673 ep.dev1, ep.dev2,
674 perDstNextHops,
675 Sets.intersection(ipDev1, ipDev2))) {
676 return false; // abort everything and fail fast
677 }
678 }
Saurav Dasc568c342018-01-25 09:49:01 -0800679 // handle routing to subnets that only belong to dev1 only if
680 // a next-hop exists from the target to dev1
Saurav Das7bcbe702017-06-13 15:35:54 -0700681 Set<IpPrefix> onlyDev1Subnets = Sets.difference(ipDev1, ipDev2);
Saurav Dasc568c342018-01-25 09:49:01 -0800682 if (!onlyDev1Subnets.isEmpty()
683 && nhDev1 != null && !nhDev1.isEmpty()) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700684 Map<DeviceId, Set<DeviceId>> onlyDev1NextHops = new HashMap<>();
Saurav Dasc568c342018-01-25 09:49:01 -0800685 onlyDev1NextHops.put(ep.dev1, nhDev1);
Saurav Das7bcbe702017-06-13 15:35:54 -0700686 if (!populateEcmpRoutingRulePartial(
687 targetSw,
688 ep.dev1, null,
689 onlyDev1NextHops,
690 onlyDev1Subnets)) {
691 return false; // abort everything and fail fast
692 }
693 }
Saurav Dasc568c342018-01-25 09:49:01 -0800694 // handle routing to subnets that only belong to dev2 only if
695 // a next-hop exists from the target to dev2
Saurav Das7bcbe702017-06-13 15:35:54 -0700696 Set<IpPrefix> onlyDev2Subnets = Sets.difference(ipDev2, ipDev1);
Saurav Dasc568c342018-01-25 09:49:01 -0800697 if (!onlyDev2Subnets.isEmpty()
698 && nhDev2 != null && !nhDev2.isEmpty()) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700699 Map<DeviceId, Set<DeviceId>> onlyDev2NextHops = new HashMap<>();
Saurav Dasc568c342018-01-25 09:49:01 -0800700 onlyDev2NextHops.put(ep.dev2, nhDev2);
Saurav Das7bcbe702017-06-13 15:35:54 -0700701 if (!populateEcmpRoutingRulePartial(
702 targetSw,
703 ep.dev2, null,
704 onlyDev2NextHops,
705 onlyDev2Subnets)) {
706 return false; // abort everything and fail fast
707 }
708 }
709 }
710 // if it gets here it has succeeded for all targets to this edge-pair
711 }
712 return true;
713 }
714
715 /**
716 * Programs targetSw in the changedRoutes for given prefixes reachable by
717 * a destination switch that is not part of an edge-pair.
718 * If no prefixes are given, the method will use configured subnets/prefixes.
719 *
720 * @param subnets a set of prefixes that need to be populated in the routing
721 * table of the target switch in the changedRoutes. Can be null,
722 * in which case all the configured prefixes belonging to the
723 * paired switches will be populated in the target switch
724 * @param changedRoutes a set of route-path changes, where each route-path is
725 * a list with its first element the src-switch (target)
726 * of the path, and the second element the dst-switch of
727 * the path.
728 * @return true if successful
729 */
730 private boolean redoRoutingIndividualDests(Set<IpPrefix> subnets,
Saurav Dasc568c342018-01-25 09:49:01 -0800731 Set<ArrayList<DeviceId>> changedRoutes,
732 Set<DeviceId> updatedDevices) {
Saurav Das7bcbe702017-06-13 15:35:54 -0700733 // aggregate route-path changes for each dst device
734 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> routesBydevice =
735 new HashMap<>();
736 for (ArrayList<DeviceId> route: changedRoutes) {
737 DeviceId dstSw = route.get(1);
738 ArrayList<ArrayList<DeviceId>> deviceRoutes =
739 routesBydevice.get(dstSw);
740 if (deviceRoutes == null) {
741 deviceRoutes = new ArrayList<>();
742 routesBydevice.put(dstSw, deviceRoutes);
743 }
744 deviceRoutes.add(route);
745 }
746 for (DeviceId impactedDstDevice : routesBydevice.keySet()) {
747 ArrayList<ArrayList<DeviceId>> deviceRoutes =
748 routesBydevice.get(impactedDstDevice);
749 for (ArrayList<DeviceId> route: deviceRoutes) {
750 log.debug("* redoRoutingIndiDst Target: {} -> dst: {}",
751 route.get(0), route.get(1));
752 DeviceId targetSw = route.get(0);
753 DeviceId dstSw = route.get(1); // same as impactedDstDevice
754 Set<DeviceId> nextHops = getNextHops(targetSw, dstSw);
Saurav Dasbd071d82018-01-09 17:38:44 -0800755 if (nextHops.isEmpty()) {
756 log.warn("Could not find next hop from target:{} --> dst {} "
757 + "skipping this route", targetSw, dstSw);
758 continue;
759 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700760 Map<DeviceId, Set<DeviceId>> nhops = new HashMap<>();
761 nhops.put(dstSw, nextHops);
762 if (!populateEcmpRoutingRulePartial(targetSw, dstSw, null, nhops,
763 (subnets == null) ? Sets.newHashSet() : subnets)) {
764 return false; // abort routing and fail fast
765 }
766 log.debug("Populating flow rules from target: {} to dst: {}"
767 + " is successful", targetSw, dstSw);
768 }
769 //Only if all the flows for all impacted routes to a
770 //specific target are pushed successfully, update the
771 //ECMP graph for that target. Or else the next event
772 //would not see any changes in the ECMP graphs.
773 //In another case, the target switch has gone away, so
774 //routes can't be installed. In that case, the current map
775 //is updated here, without any flows being pushed.
776 currentEcmpSpgMap.put(impactedDstDevice,
777 updatedEcmpSpgMap.get(impactedDstDevice));
Saurav Dasc568c342018-01-25 09:49:01 -0800778 updatedDevices.add(impactedDstDevice);
Saurav Das7bcbe702017-06-13 15:35:54 -0700779 log.debug("Updating ECMPspg for impacted dev:{}", impactedDstDevice);
780 }
781 return true;
782 }
783
784 /**
785 * Populate ECMP rules for subnets from target to destination via nexthops.
786 *
787 * @param targetSw Device ID of target switch in which rules will be programmed
788 * @param destSw1 Device ID of final destination switch to which the rules will forward
789 * @param destSw2 Device ID of paired destination switch to which the rules will forward
790 * A null deviceId indicates packets should only be sent to destSw1
791 * @param nextHops Map indication a list of next hops per destSw
792 * @param subnets Subnets to be populated. If empty, populate all configured subnets.
793 * @return true if it succeeds in populating rules
794 */ // refactor
795 private boolean populateEcmpRoutingRulePartial(DeviceId targetSw,
796 DeviceId destSw1,
797 DeviceId destSw2,
798 Map<DeviceId, Set<DeviceId>> nextHops,
799 Set<IpPrefix> subnets) {
800 boolean result;
801 // If both target switch and dest switch are edge routers, then set IP
802 // rule for both subnet and router IP.
803 boolean targetIsEdge;
804 boolean dest1IsEdge;
805 Ip4Address dest1RouterIpv4, dest2RouterIpv4 = null;
806 Ip6Address dest1RouterIpv6, dest2RouterIpv6 = null;
807
808 try {
809 targetIsEdge = config.isEdgeDevice(targetSw);
810 dest1IsEdge = config.isEdgeDevice(destSw1);
811 dest1RouterIpv4 = config.getRouterIpv4(destSw1);
812 dest1RouterIpv6 = config.getRouterIpv6(destSw1);
813 if (destSw2 != null) {
814 dest2RouterIpv4 = config.getRouterIpv4(destSw2);
815 dest2RouterIpv6 = config.getRouterIpv6(destSw2);
816 }
817 } catch (DeviceConfigNotFoundException e) {
818 log.warn(e.getMessage() + " Aborting populateEcmpRoutingRulePartial.");
Saurav Dasc88d4662017-05-15 15:34:25 -0700819 return false;
820 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700821
822 if (targetIsEdge && dest1IsEdge) {
823 subnets = (subnets != null && !subnets.isEmpty())
824 ? Sets.newHashSet(subnets)
825 : Sets.newHashSet(config.getSubnets(destSw1));
826 // XXX - Rethink this
827 /*subnets.add(dest1RouterIpv4.toIpPrefix());
828 if (dest1RouterIpv6 != null) {
829 subnets.add(dest1RouterIpv6.toIpPrefix());
830 }
831 if (destSw2 != null && dest2RouterIpv4 != null) {
832 subnets.add(dest2RouterIpv4.toIpPrefix());
833 if (dest2RouterIpv6 != null) {
834 subnets.add(dest2RouterIpv6.toIpPrefix());
835 }
836 }*/
837 log.debug(". populateEcmpRoutingRulePartial in device {} towards {} {} "
838 + "for subnets {}", targetSw, destSw1,
839 (destSw2 != null) ? ("& " + destSw2) : "",
840 subnets);
841 result = rulePopulator.populateIpRuleForSubnet(targetSw, subnets,
842 destSw1, destSw2,
843 nextHops);
844 if (!result) {
845 return false;
846 }
847 /* XXX rethink this
848 IpPrefix routerIpPrefix = destRouterIpv4.toIpPrefix();
849 log.debug("* populateEcmpRoutingRulePartial in device {} towards {} "
850 + "for router IP {}", targetSw, destSw, routerIpPrefix);
851 result = rulePopulator.populateIpRuleForRouter(targetSw, routerIpPrefix,
852 destSw, nextHops);
853 if (!result) {
854 return false;
855 }
856 // If present we deal with IPv6 loopback.
857 if (destRouterIpv6 != null) {
858 routerIpPrefix = destRouterIpv6.toIpPrefix();
859 log.debug("* populateEcmpRoutingRulePartial in device {} towards {}"
860 + " for v6 router IP {}", targetSw, destSw, routerIpPrefix);
861 result = rulePopulator.populateIpRuleForRouter(targetSw, routerIpPrefix,
862 destSw, nextHops);
863 if (!result) {
864 return false;
865 }
866 }*/
Saurav Dasc88d4662017-05-15 15:34:25 -0700867 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700868
869 if (!targetIsEdge && dest1IsEdge) {
870 // MPLS rules in all non-edge target devices. These rules are for
871 // individual destinations, even if the dsts are part of edge-pairs.
872 log.debug(". populateEcmpRoutingRulePartial in device{} towards {} for "
873 + "all MPLS rules", targetSw, destSw1);
874 result = rulePopulator.populateMplsRule(targetSw, destSw1,
875 nextHops.get(destSw1),
876 dest1RouterIpv4);
877 if (!result) {
878 return false;
879 }
880 if (dest1RouterIpv6 != null) {
881 result = rulePopulator.populateMplsRule(targetSw, destSw1,
882 nextHops.get(destSw1),
883 dest1RouterIpv6);
884 if (!result) {
885 return false;
886 }
887 }
888 }
889
890 // To save on ECMP groups
891 // avoid MPLS rules in non-edge-devices to non-edge-devices
892 // avoid MPLS transit rules in edge-devices
893 // avoid loopback IP rules in edge-devices to non-edge-devices
894 return true;
Saurav Dasc88d4662017-05-15 15:34:25 -0700895 }
896
897 /**
898 * Processes a set a route-path changes by editing hash groups.
899 *
900 * @param routeChanges a set of route-path changes, where each route-path is
901 * a list with its first element the src-switch of the path
902 * and the second element the dst-switch of the path.
903 * @param linkOrSwitchFailed true if the route changes are for a failed
904 * switch or linkDown event
905 * @param failedSwitch the switchId if the route changes are for a failed switch,
906 * otherwise null
907 */
908 private void processHashGroupChange(Set<ArrayList<DeviceId>> routeChanges,
909 boolean linkOrSwitchFailed,
910 DeviceId failedSwitch) {
Saurav Das9df5b7c2017-08-14 16:44:43 -0700911 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
912 // first, ensure each routeChanges entry has two elements
Saurav Dasc88d4662017-05-15 15:34:25 -0700913 for (ArrayList<DeviceId> route : routeChanges) {
Saurav Das9df5b7c2017-08-14 16:44:43 -0700914 if (route.size() == 1) {
915 // route-path changes are from everyone else to this switch
916 DeviceId dstSw = route.get(0);
917 srManager.deviceService.getAvailableDevices().forEach(sw -> {
918 if (!sw.id().equals(dstSw)) {
919 changedRoutes.add(Lists.newArrayList(sw.id(), dstSw));
920 }
921 });
922 } else {
923 changedRoutes.add(route);
Saurav Dasc88d4662017-05-15 15:34:25 -0700924 }
Saurav Das9df5b7c2017-08-14 16:44:43 -0700925 }
Saurav Dasc568c342018-01-25 09:49:01 -0800926 boolean someFailed = false;
927 Set<DeviceId> updatedDevices = Sets.newHashSet();
Saurav Das9df5b7c2017-08-14 16:44:43 -0700928 for (ArrayList<DeviceId> route : changedRoutes) {
929 DeviceId targetSw = route.get(0);
930 DeviceId dstSw = route.get(1);
Saurav Dasc88d4662017-05-15 15:34:25 -0700931 if (linkOrSwitchFailed) {
Saurav Das9df5b7c2017-08-14 16:44:43 -0700932 boolean success = fixHashGroupsForRoute(route, true);
Saurav Dasc88d4662017-05-15 15:34:25 -0700933 // it's possible that we cannot fix hash groups for a route
934 // if the target switch has failed. Nevertheless the ecmp graph
935 // for the impacted switch must still be updated.
Saurav Das9df5b7c2017-08-14 16:44:43 -0700936 if (!success && failedSwitch != null && targetSw.equals(failedSwitch)) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700937 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
938 currentEcmpSpgMap.remove(targetSw);
Saurav Das9df5b7c2017-08-14 16:44:43 -0700939 log.debug("Updating ECMPspg for dst:{} removing failed switch "
Saurav Dasc88d4662017-05-15 15:34:25 -0700940 + "target:{}", dstSw, targetSw);
Saurav Dasc568c342018-01-25 09:49:01 -0800941 updatedDevices.add(targetSw);
942 updatedDevices.add(dstSw);
Saurav Das9df5b7c2017-08-14 16:44:43 -0700943 continue;
Saurav Dasc88d4662017-05-15 15:34:25 -0700944 }
945 //linkfailed - update both sides
Saurav Dasc88d4662017-05-15 15:34:25 -0700946 if (success) {
947 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
Saurav Das9df5b7c2017-08-14 16:44:43 -0700948 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
Saurav Dasc568c342018-01-25 09:49:01 -0800949 log.debug("Updating ECMPspg for dst:{} and target:{} for linkdown"
950 + " or switchdown", dstSw, targetSw);
951 updatedDevices.add(targetSw);
952 updatedDevices.add(dstSw);
953 } else {
954 someFailed = true;
Saurav Das9df5b7c2017-08-14 16:44:43 -0700955 }
956 } else {
957 //linkup of seen before link
958 boolean success = fixHashGroupsForRoute(route, false);
959 if (success) {
960 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
961 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
962 log.debug("Updating ECMPspg for target:{} and dst:{} for linkup",
Saurav Dasc88d4662017-05-15 15:34:25 -0700963 targetSw, dstSw);
Saurav Dasc568c342018-01-25 09:49:01 -0800964 updatedDevices.add(targetSw);
965 updatedDevices.add(dstSw);
966 } else {
967 someFailed = true;
Saurav Dasc88d4662017-05-15 15:34:25 -0700968 }
969 }
970 }
Saurav Dasc568c342018-01-25 09:49:01 -0800971 if (!someFailed) {
972 // here is where we update all devices not touched by this instance
973 updatedEcmpSpgMap.keySet().stream()
974 .filter(devId -> !updatedDevices.contains(devId))
975 .forEach(devId -> {
976 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
977 log.debug("Updating ECMPspg for remaining dev:{}", devId);
978 });
979 }
Saurav Dasc88d4662017-05-15 15:34:25 -0700980 }
981
982 /**
983 * Edits hash groups in the src-switch (targetSw) of a route-path by
984 * calling the groupHandler to either add or remove buckets in an existing
985 * hash group.
986 *
987 * @param route a single list representing a route-path where the first element
988 * is the src-switch (targetSw) of the route-path and the
989 * second element is the dst-switch
990 * @param revoke true if buckets in the hash-groups need to be removed;
991 * false if buckets in the hash-groups need to be added
992 * @return true if the hash group editing is successful
993 */
994 private boolean fixHashGroupsForRoute(ArrayList<DeviceId> route,
995 boolean revoke) {
996 DeviceId targetSw = route.get(0);
997 if (route.size() < 2) {
998 log.warn("Cannot fixHashGroupsForRoute - no dstSw in route {}", route);
999 return false;
1000 }
1001 DeviceId destSw = route.get(1);
Saurav Das9df5b7c2017-08-14 16:44:43 -07001002 log.debug("* processing fixHashGroupsForRoute: Target {} -> Dest {}",
Saurav Dasc88d4662017-05-15 15:34:25 -07001003 targetSw, destSw);
Saurav Dasc88d4662017-05-15 15:34:25 -07001004 // figure out the new next hops at the targetSw towards the destSw
Saurav Das9df5b7c2017-08-14 16:44:43 -07001005 Set<DeviceId> nextHops = getNextHops(targetSw, destSw);
Saurav Dasc88d4662017-05-15 15:34:25 -07001006 // call group handler to change hash group at targetSw
1007 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
1008 if (grpHandler == null) {
1009 log.warn("Cannot find grouphandler for dev:{} .. aborting"
1010 + " {} hash group buckets for route:{} ", targetSw,
1011 (revoke) ? "revoke" : "repopulate", route);
1012 return false;
1013 }
1014 log.debug("{} hash-groups buckets For Route {} -> {} to next-hops {}",
1015 (revoke) ? "revoke" : "repopulating",
1016 targetSw, destSw, nextHops);
1017 return (revoke) ? grpHandler.fixHashGroups(targetSw, nextHops,
1018 destSw, true)
1019 : grpHandler.fixHashGroups(targetSw, nextHops,
1020 destSw, false);
1021 }
1022
1023 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001024 * Start the flow rule population process if it was never started. The
1025 * process finishes successfully when all flow rules are set and stops with
1026 * ABORTED status when any groups required for flows is not set yet.
Saurav Dasc88d4662017-05-15 15:34:25 -07001027 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001028 public void startPopulationProcess() {
1029 statusLock.lock();
1030 try {
1031 if (populationStatus == Status.IDLE
1032 || populationStatus == Status.SUCCEEDED
1033 || populationStatus == Status.ABORTED) {
1034 populateAllRoutingRules();
sangho45b009c2015-05-07 13:30:57 -07001035 } else {
Saurav Das7bcbe702017-06-13 15:35:54 -07001036 log.warn("Not initiating startPopulationProcess as populationStatus is {}",
1037 populationStatus);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001038 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001039 } finally {
1040 statusLock.unlock();
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001041 }
sangho20eff1d2015-04-13 15:15:58 -07001042 }
1043
Saurav Dasb5c236e2016-06-07 10:08:06 -07001044 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001045 * Revoke rules of given subnet in all edge switches.
1046 *
1047 * @param subnets subnet being removed
1048 * @return true if succeed
1049 */
1050 protected boolean revokeSubnet(Set<IpPrefix> subnets) {
1051 statusLock.lock();
1052 try {
1053 return srManager.routingRulePopulator.revokeIpRuleForSubnet(subnets);
1054 } finally {
1055 statusLock.unlock();
1056 }
1057 }
1058
1059 /**
Charles Chan2fde6d42017-08-23 14:46:43 -07001060 * Populates IP rules for a route that has direct connection to the switch
1061 * if the current instance is the master of the switch.
1062 *
1063 * @param deviceId device ID of the device that next hop attaches to
1064 * @param prefix IP prefix of the route
1065 * @param hostMac MAC address of the next hop
1066 * @param hostVlanId Vlan ID of the nexthop
1067 * @param outPort port where the next hop attaches to
1068 */
1069 void populateRoute(DeviceId deviceId, IpPrefix prefix,
1070 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
1071 if (srManager.mastershipService.isLocalMaster(deviceId)) {
1072 srManager.routingRulePopulator.populateRoute(deviceId, prefix, hostMac, hostVlanId, outPort);
1073 }
1074 }
1075
1076 /**
1077 * Removes IP rules for a route when the next hop is gone.
1078 * if the current instance is the master of the switch.
1079 *
1080 * @param deviceId device ID of the device that next hop attaches to
1081 * @param prefix IP prefix of the route
1082 * @param hostMac MAC address of the next hop
1083 * @param hostVlanId Vlan ID of the nexthop
1084 * @param outPort port that next hop attaches to
1085 */
1086 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
1087 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
1088 if (srManager.mastershipService.isLocalMaster(deviceId)) {
1089 srManager.routingRulePopulator.revokeRoute(deviceId, prefix, hostMac, hostVlanId, outPort);
1090 }
1091 }
1092
1093 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001094 * Remove ECMP graph entry for the given device. Typically called when
1095 * device is no longer available.
1096 *
1097 * @param deviceId the device for which graphs need to be purged
1098 */
1099 protected void purgeEcmpGraph(DeviceId deviceId) {
Saurav Dasc568c342018-01-25 09:49:01 -08001100 statusLock.lock();
1101 try {
1102
1103 if (populationStatus == Status.STARTED) {
1104 log.warn("Previous rule population is not finished. Cannot"
1105 + " proceeed with purgeEcmpGraph for {}", deviceId);
1106 return;
1107 }
1108 log.debug("Updating ECMPspg for unavailable dev:{}", deviceId);
1109 currentEcmpSpgMap.remove(deviceId);
1110 if (updatedEcmpSpgMap != null) {
1111 updatedEcmpSpgMap.remove(deviceId);
1112 }
1113 } finally {
1114 statusLock.unlock();
Saurav Das7bcbe702017-06-13 15:35:54 -07001115 }
1116 }
1117
1118 //////////////////////////////////////
1119 // Routing helper methods and classes
1120 //////////////////////////////////////
1121
1122 /**
Saurav Das4e3224f2016-11-29 14:27:25 -08001123 * Computes set of affected routes due to failed link. Assumes
Saurav Dasb5c236e2016-06-07 10:08:06 -07001124 * previous ecmp shortest-path graph exists for a switch in order to compute
1125 * affected routes. If such a graph does not exist, the method returns null.
1126 *
1127 * @param linkFail the failed link
1128 * @return the set of affected routes which may be empty if no routes were
1129 * affected, or null if no previous ecmp spg was found for comparison
1130 */
sangho20eff1d2015-04-13 15:15:58 -07001131 private Set<ArrayList<DeviceId>> computeDamagedRoutes(Link linkFail) {
sangho20eff1d2015-04-13 15:15:58 -07001132 Set<ArrayList<DeviceId>> routes = new HashSet<>();
1133
1134 for (Device sw : srManager.deviceService.getDevices()) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001135 log.debug("Computing the impacted routes for device {} due to link fail",
1136 sw.id());
Saurav Das9df5b7c2017-08-14 16:44:43 -07001137 DeviceId retId = shouldHandleRouting(sw.id());
1138 if (retId == null) {
sangho20eff1d2015-04-13 15:15:58 -07001139 continue;
1140 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001141 Set<DeviceId> devicesToProcess = Sets.newHashSet(retId, sw.id());
1142 for (DeviceId rootSw : devicesToProcess) {
1143 EcmpShortestPathGraph ecmpSpg = currentEcmpSpgMap.get(rootSw);
1144 if (ecmpSpg == null) {
1145 log.warn("No existing ECMP graph for switch {}. Aborting optimized"
1146 + " rerouting and opting for full-reroute", rootSw);
1147 return null;
1148 }
1149 if (log.isDebugEnabled()) {
1150 log.debug("Root switch: {}", rootSw);
1151 log.debug(" Current/Existing SPG: {}", ecmpSpg);
1152 log.debug(" New/Updated SPG: {}", updatedEcmpSpgMap.get(rootSw));
1153 }
1154 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>>
1155 switchVia = ecmpSpg.getAllLearnedSwitchesAndVia();
1156 // figure out if the broken link affected any route-paths in this graph
1157 for (Integer itrIdx : switchVia.keySet()) {
1158 log.trace("Current/Exiting SPG Iterindex# {}", itrIdx);
1159 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1160 switchVia.get(itrIdx);
1161 for (DeviceId targetSw : swViaMap.keySet()) {
1162 log.trace("TargetSwitch {} --> RootSwitch {}",
1163 targetSw, rootSw);
Saurav Dasb5c236e2016-06-07 10:08:06 -07001164 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1165 log.trace(" Via:");
Pier Ventree0ae7a32016-11-23 09:57:42 -08001166 via.forEach(e -> log.trace(" {}", e));
Saurav Dasb5c236e2016-06-07 10:08:06 -07001167 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001168 Set<ArrayList<DeviceId>> subLinks =
1169 computeLinks(targetSw, rootSw, swViaMap);
1170 for (ArrayList<DeviceId> alink: subLinks) {
1171 if ((alink.get(0).equals(linkFail.src().deviceId()) &&
1172 alink.get(1).equals(linkFail.dst().deviceId()))
1173 ||
1174 (alink.get(0).equals(linkFail.dst().deviceId()) &&
1175 alink.get(1).equals(linkFail.src().deviceId()))) {
1176 log.debug("Impacted route:{}->{}", targetSw, rootSw);
1177 ArrayList<DeviceId> aRoute = new ArrayList<>();
1178 aRoute.add(targetSw); // switch with rules to populate
1179 aRoute.add(rootSw); // towards this destination
1180 routes.add(aRoute);
1181 break;
1182 }
sangho20eff1d2015-04-13 15:15:58 -07001183 }
1184 }
1185 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001186
sangho20eff1d2015-04-13 15:15:58 -07001187 }
sangho45b009c2015-05-07 13:30:57 -07001188
sangho20eff1d2015-04-13 15:15:58 -07001189 }
sangho20eff1d2015-04-13 15:15:58 -07001190 return routes;
1191 }
1192
Saurav Das4e3224f2016-11-29 14:27:25 -08001193 /**
1194 * Computes set of affected routes due to new links or failed switches.
1195 *
1196 * @return the set of affected routes which may be empty if no routes were
1197 * affected
1198 */
sangho20eff1d2015-04-13 15:15:58 -07001199 private Set<ArrayList<DeviceId>> computeRouteChange() {
Saurav Das7bcbe702017-06-13 15:35:54 -07001200 ImmutableSet.Builder<ArrayList<DeviceId>> changedRtBldr =
Saurav Das4e3224f2016-11-29 14:27:25 -08001201 ImmutableSet.builder();
sangho20eff1d2015-04-13 15:15:58 -07001202
1203 for (Device sw : srManager.deviceService.getDevices()) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001204 log.debug("Computing the impacted routes for device {}", sw.id());
1205 DeviceId retId = shouldHandleRouting(sw.id());
1206 if (retId == null) {
sangho20eff1d2015-04-13 15:15:58 -07001207 continue;
1208 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001209 Set<DeviceId> devicesToProcess = Sets.newHashSet(retId, sw.id());
1210 for (DeviceId rootSw : devicesToProcess) {
1211 if (log.isTraceEnabled()) {
1212 log.trace("Device links for dev: {}", rootSw);
1213 for (Link link: srManager.linkService.getDeviceLinks(rootSw)) {
1214 log.trace("{} -> {} ", link.src().deviceId(),
1215 link.dst().deviceId());
1216 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001217 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001218 EcmpShortestPathGraph currEcmpSpg = currentEcmpSpgMap.get(rootSw);
1219 if (currEcmpSpg == null) {
1220 log.debug("No existing ECMP graph for device {}.. adding self as "
1221 + "changed route", rootSw);
1222 changedRtBldr.add(Lists.newArrayList(rootSw));
1223 continue;
1224 }
1225 EcmpShortestPathGraph newEcmpSpg = updatedEcmpSpgMap.get(rootSw);
1226 if (log.isDebugEnabled()) {
1227 log.debug("Root switch: {}", rootSw);
1228 log.debug(" Current/Existing SPG: {}", currEcmpSpg);
1229 log.debug(" New/Updated SPG: {}", newEcmpSpg);
1230 }
1231 // first use the updated/new map to compare to current/existing map
1232 // as new links may have come up
1233 changedRtBldr.addAll(compareGraphs(newEcmpSpg, currEcmpSpg, rootSw));
1234 // then use the current/existing map to compare to updated/new map
1235 // as switch may have been removed
1236 changedRtBldr.addAll(compareGraphs(currEcmpSpg, newEcmpSpg, rootSw));
sangho45b009c2015-05-07 13:30:57 -07001237 }
Saurav Das4e3224f2016-11-29 14:27:25 -08001238 }
sangho20eff1d2015-04-13 15:15:58 -07001239
Saurav Das7bcbe702017-06-13 15:35:54 -07001240 Set<ArrayList<DeviceId>> changedRoutes = changedRtBldr.build();
Saurav Das4e3224f2016-11-29 14:27:25 -08001241 for (ArrayList<DeviceId> route: changedRoutes) {
1242 log.debug("Route changes Target -> Root");
1243 if (route.size() == 1) {
1244 log.debug(" : all -> {}", route.get(0));
1245 } else {
1246 log.debug(" : {} -> {}", route.get(0), route.get(1));
1247 }
1248 }
1249 return changedRoutes;
1250 }
1251
1252 /**
1253 * For the root switch, searches all the target nodes reachable in the base
1254 * graph, and compares paths to the ones in the comp graph.
1255 *
1256 * @param base the graph that is indexed for all reachable target nodes
1257 * from the root node
1258 * @param comp the graph that the base graph is compared to
1259 * @param rootSw both ecmp graphs are calculated for the root node
1260 * @return all the routes that have changed in the base graph
1261 */
1262 private Set<ArrayList<DeviceId>> compareGraphs(EcmpShortestPathGraph base,
1263 EcmpShortestPathGraph comp,
1264 DeviceId rootSw) {
1265 ImmutableSet.Builder<ArrayList<DeviceId>> changedRoutesBuilder =
1266 ImmutableSet.builder();
1267 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> baseMap =
1268 base.getAllLearnedSwitchesAndVia();
1269 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> compMap =
1270 comp.getAllLearnedSwitchesAndVia();
1271 for (Integer itrIdx : baseMap.keySet()) {
1272 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> baseViaMap =
1273 baseMap.get(itrIdx);
1274 for (DeviceId targetSw : baseViaMap.keySet()) {
1275 ArrayList<ArrayList<DeviceId>> basePath = baseViaMap.get(targetSw);
1276 ArrayList<ArrayList<DeviceId>> compPath = getVia(compMap, targetSw);
1277 if ((compPath == null) || !basePath.equals(compPath)) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001278 log.trace("Impacted route:{} -> {}", targetSw, rootSw);
Saurav Das4e3224f2016-11-29 14:27:25 -08001279 ArrayList<DeviceId> route = new ArrayList<>();
Saurav Das7bcbe702017-06-13 15:35:54 -07001280 route.add(targetSw); // switch with rules to populate
1281 route.add(rootSw); // towards this destination
Saurav Das4e3224f2016-11-29 14:27:25 -08001282 changedRoutesBuilder.add(route);
sangho20eff1d2015-04-13 15:15:58 -07001283 }
1284 }
sangho45b009c2015-05-07 13:30:57 -07001285 }
Saurav Das4e3224f2016-11-29 14:27:25 -08001286 return changedRoutesBuilder.build();
sangho20eff1d2015-04-13 15:15:58 -07001287 }
1288
Saurav Das7bcbe702017-06-13 15:35:54 -07001289 /**
1290 * Returns the ECMP paths traversed to reach the target switch.
1291 *
1292 * @param switchVia a per-iteration view of the ECMP graph for a root switch
1293 * @param targetSw the switch to reach from the root switch
1294 * @return the nodes traversed on ECMP paths to the target switch
1295 */
sangho20eff1d2015-04-13 15:15:58 -07001296 private ArrayList<ArrayList<DeviceId>> getVia(HashMap<Integer, HashMap<DeviceId,
Saurav Das4e3224f2016-11-29 14:27:25 -08001297 ArrayList<ArrayList<DeviceId>>>> switchVia, DeviceId targetSw) {
sangho20eff1d2015-04-13 15:15:58 -07001298 for (Integer itrIdx : switchVia.keySet()) {
1299 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1300 switchVia.get(itrIdx);
Saurav Das4e3224f2016-11-29 14:27:25 -08001301 if (swViaMap.get(targetSw) == null) {
sangho20eff1d2015-04-13 15:15:58 -07001302 continue;
1303 } else {
Saurav Das4e3224f2016-11-29 14:27:25 -08001304 return swViaMap.get(targetSw);
sangho20eff1d2015-04-13 15:15:58 -07001305 }
1306 }
1307
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001308 return null;
sangho20eff1d2015-04-13 15:15:58 -07001309 }
1310
Saurav Das7bcbe702017-06-13 15:35:54 -07001311 /**
1312 * Utility method to break down a path from src to dst device into a collection
1313 * of links.
1314 *
1315 * @param src src device of the path
1316 * @param dst dst device of the path
1317 * @param viaMap path taken from src to dst device
1318 * @return collection of links in the path
1319 */
sangho20eff1d2015-04-13 15:15:58 -07001320 private Set<ArrayList<DeviceId>> computeLinks(DeviceId src,
1321 DeviceId dst,
1322 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> viaMap) {
1323 Set<ArrayList<DeviceId>> subLinks = Sets.newHashSet();
1324 for (ArrayList<DeviceId> via : viaMap.get(src)) {
1325 DeviceId linkSrc = src;
1326 DeviceId linkDst = dst;
1327 for (DeviceId viaDevice: via) {
1328 ArrayList<DeviceId> link = new ArrayList<>();
1329 linkDst = viaDevice;
1330 link.add(linkSrc);
1331 link.add(linkDst);
1332 subLinks.add(link);
1333 linkSrc = viaDevice;
1334 }
1335 ArrayList<DeviceId> link = new ArrayList<>();
1336 link.add(linkSrc);
1337 link.add(dst);
1338 subLinks.add(link);
1339 }
1340
1341 return subLinks;
1342 }
1343
Charles Chan93e71ba2016-04-29 14:38:22 -07001344 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001345 * Determines whether this controller instance should handle routing for the
1346 * given {@code deviceId}, based on mastership and pairDeviceId if one exists.
1347 * Returns null if this instance should not handle routing for given {@code deviceId}.
1348 * Otherwise the returned value could be the given deviceId itself, or the
1349 * deviceId for the paired edge device. In the latter case, this instance
1350 * should handle routing for both the given device and the paired device.
Charles Chan93e71ba2016-04-29 14:38:22 -07001351 *
Saurav Das7bcbe702017-06-13 15:35:54 -07001352 * @param deviceId device identifier to consider for routing
1353 * @return null or deviceId which could be the same as the given deviceId
1354 * or the deviceId of a paired edge device
Charles Chan93e71ba2016-04-29 14:38:22 -07001355 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001356 private DeviceId shouldHandleRouting(DeviceId deviceId) {
1357 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1358 log.debug("Not master for dev:{} .. skipping routing, may get handled "
1359 + "elsewhere as part of paired devices", deviceId);
1360 return null;
1361 }
1362 NodeId myNode = srManager.mastershipService.getMasterFor(deviceId);
1363 DeviceId pairDev = getPairDev(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001364
Saurav Das7bcbe702017-06-13 15:35:54 -07001365 if (pairDev != null) {
1366 if (!srManager.deviceService.isAvailable(pairDev)) {
1367 log.warn("pairedDev {} not available .. routing this dev:{} "
1368 + "without mastership check",
1369 pairDev, deviceId);
1370 return pairDev; // handle both temporarily
1371 }
1372 NodeId pairMasterNode = srManager.mastershipService.getMasterFor(pairDev);
1373 if (myNode.compareTo(pairMasterNode) <= 0) {
1374 log.debug("Handling routing for both dev:{} pair-dev:{}; myNode: {}"
1375 + " pairMaster:{} compare:{}", deviceId, pairDev,
1376 myNode, pairMasterNode,
1377 myNode.compareTo(pairMasterNode));
1378 return pairDev; // handle both
1379 } else {
1380 log.debug("PairDev node: {} should handle routing for dev:{} and "
1381 + "pair-dev:{}", pairMasterNode, deviceId, pairDev);
1382 return null; // handle neither
sanghob35a6192015-04-01 13:05:26 -07001383 }
1384 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001385 return deviceId; // not paired, just handle given device
sanghob35a6192015-04-01 13:05:26 -07001386 }
1387
Charles Chan93e71ba2016-04-29 14:38:22 -07001388 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001389 * Returns the configured paired DeviceId for the given Device, or null
1390 * if no such paired device has been configured.
Charles Chan93e71ba2016-04-29 14:38:22 -07001391 *
Saurav Das7bcbe702017-06-13 15:35:54 -07001392 * @param deviceId
1393 * @return configured pair deviceId or null
Charles Chan93e71ba2016-04-29 14:38:22 -07001394 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001395 private DeviceId getPairDev(DeviceId deviceId) {
1396 DeviceId pairDev;
Charles Chan0b4e6182015-11-03 10:42:14 -08001397 try {
Saurav Das7bcbe702017-06-13 15:35:54 -07001398 pairDev = srManager.deviceConfiguration.getPairDeviceId(deviceId);
Charles Chan0b4e6182015-11-03 10:42:14 -08001399 } catch (DeviceConfigNotFoundException e) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001400 log.warn(e.getMessage() + " .. cannot continue routing for dev: {}");
1401 return null;
Charles Chan0b4e6182015-11-03 10:42:14 -08001402 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001403 return pairDev;
sanghob35a6192015-04-01 13:05:26 -07001404 }
1405
1406 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001407 * Returns the set of deviceIds which are the next hops from the targetSw
1408 * to the dstSw according to the latest ECMP spg.
1409 *
1410 * @param targetSw the switch for which the next-hops are desired
1411 * @param dstSw the switch to which the next-hops lead to from the targetSw
1412 * @return set of next hop deviceIds, could be empty if no next hops are found
1413 */
1414 private Set<DeviceId> getNextHops(DeviceId targetSw, DeviceId dstSw) {
1415 boolean targetIsEdge = false;
1416 try {
1417 targetIsEdge = srManager.deviceConfiguration.isEdgeDevice(targetSw);
1418 } catch (DeviceConfigNotFoundException e) {
1419 log.warn(e.getMessage() + "Cannot determine if targetIsEdge {}.. "
1420 + "continuing to getNextHops", targetSw);
1421 }
1422
1423 EcmpShortestPathGraph ecmpSpg = updatedEcmpSpgMap.get(dstSw);
1424 if (ecmpSpg == null) {
1425 log.debug("No ecmpSpg found for dstSw: {}", dstSw);
1426 return ImmutableSet.of();
1427 }
1428 HashMap<Integer,
1429 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> switchVia =
1430 ecmpSpg.getAllLearnedSwitchesAndVia();
1431 for (Integer itrIdx : switchVia.keySet()) {
1432 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1433 switchVia.get(itrIdx);
1434 for (DeviceId target : swViaMap.keySet()) {
1435 if (!target.equals(targetSw)) {
1436 continue;
1437 }
1438 if (!targetIsEdge && itrIdx > 1) {
1439 // optimization for spines to not use other leaves to get
1440 // to a leaf to avoid loops
1441 log.debug("Avoiding {} hop path for non-edge targetSw:{}"
1442 + " --> dstSw:{}", itrIdx, targetSw, dstSw);
1443 break;
1444 }
1445 Set<DeviceId> nextHops = new HashSet<>();
1446 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1447 if (via.isEmpty()) {
1448 // the dstSw is the next-hop from the targetSw
1449 nextHops.add(dstSw);
1450 } else {
1451 // first elem is next-hop in each ECMP path
1452 nextHops.add(via.get(0));
1453 }
1454 }
1455 return nextHops;
1456 }
1457 }
1458 return ImmutableSet.of(); //no next-hops found
1459 }
1460
1461 /**
1462 * Represents two devices that are paired by configuration. An EdgePair for
1463 * (dev1, dev2) is the same as as EdgePair for (dev2, dev1)
1464 */
1465 protected final class EdgePair {
1466 DeviceId dev1;
1467 DeviceId dev2;
1468
1469 EdgePair(DeviceId dev1, DeviceId dev2) {
1470 this.dev1 = dev1;
1471 this.dev2 = dev2;
1472 }
1473
1474 boolean includes(DeviceId dev) {
1475 return dev1.equals(dev) || dev2.equals(dev);
1476 }
1477
1478 @Override
1479 public boolean equals(Object o) {
1480 if (this == o) {
1481 return true;
1482 }
1483 if (!(o instanceof EdgePair)) {
1484 return false;
1485 }
1486 EdgePair that = (EdgePair) o;
1487 return ((this.dev1.equals(that.dev1) && this.dev2.equals(that.dev2)) ||
1488 (this.dev1.equals(that.dev2) && this.dev2.equals(that.dev1)));
1489 }
1490
1491 @Override
1492 public int hashCode() {
1493 if (dev1.toString().compareTo(dev2.toString()) <= 0) {
1494 return Objects.hash(dev1, dev2);
1495 } else {
1496 return Objects.hash(dev2, dev1);
1497 }
1498 }
1499
1500 @Override
1501 public String toString() {
1502 return toStringHelper(this)
1503 .add("Dev1", dev1)
1504 .add("Dev2", dev2)
1505 .toString();
1506 }
1507 }
1508
1509 //////////////////////////////////////
1510 // Filtering rule creation
1511 //////////////////////////////////////
1512
1513 /**
Saurav Das018605f2017-02-18 14:05:44 -08001514 * Populates filtering rules for port, and punting rules
1515 * for gateway IPs, loopback IPs and arp/ndp traffic.
1516 * Should only be called by the master instance for this device/port.
sanghob35a6192015-04-01 13:05:26 -07001517 *
1518 * @param deviceId Switch ID to set the rules
1519 */
Saurav Das822c4e22015-10-23 10:51:11 -07001520 public void populatePortAddressingRules(DeviceId deviceId) {
Saurav Das59232cf2016-04-27 18:35:50 -07001521 // Although device is added, sometimes device store does not have the
1522 // ports for this device yet. It results in missing filtering rules in the
1523 // switch. We will attempt it a few times. If it still does not work,
1524 // user can manually repopulate using CLI command sr-reroute-network
Charles Chanf6ec1532017-02-08 16:10:40 -08001525 PortFilterInfo firstRun = rulePopulator.populateVlanMacFilters(deviceId);
Saurav Dasd2fded02016-12-02 15:43:47 -08001526 if (firstRun == null) {
1527 firstRun = new PortFilterInfo(0, 0, 0);
Saurav Das59232cf2016-04-27 18:35:50 -07001528 }
Saurav Dasd2fded02016-12-02 15:43:47 -08001529 executorService.schedule(new RetryFilters(deviceId, firstRun),
1530 RETRY_INTERVAL_MS, TimeUnit.MILLISECONDS);
sanghob35a6192015-04-01 13:05:26 -07001531 }
1532
1533 /**
Saurav Dasd2fded02016-12-02 15:43:47 -08001534 * Utility class used to temporarily store information about the ports on a
1535 * device processed for filtering objectives.
Saurav Dasd2fded02016-12-02 15:43:47 -08001536 */
1537 public final class PortFilterInfo {
Saurav Das018605f2017-02-18 14:05:44 -08001538 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das59232cf2016-04-27 18:35:50 -07001539
Saurav Das018605f2017-02-18 14:05:44 -08001540 public PortFilterInfo(int disabledPorts, int errorPorts,
Saurav Dasd2fded02016-12-02 15:43:47 -08001541 int filteredPorts) {
1542 this.disabledPorts = disabledPorts;
1543 this.filteredPorts = filteredPorts;
Saurav Das018605f2017-02-18 14:05:44 -08001544 this.errorPorts = errorPorts;
Saurav Dasd2fded02016-12-02 15:43:47 -08001545 }
1546
1547 @Override
1548 public int hashCode() {
Saurav Das018605f2017-02-18 14:05:44 -08001549 return Objects.hash(disabledPorts, filteredPorts, errorPorts);
Saurav Dasd2fded02016-12-02 15:43:47 -08001550 }
1551
1552 @Override
1553 public boolean equals(Object obj) {
1554 if (this == obj) {
1555 return true;
1556 }
1557 if ((obj == null) || (!(obj instanceof PortFilterInfo))) {
1558 return false;
1559 }
1560 PortFilterInfo other = (PortFilterInfo) obj;
1561 return ((disabledPorts == other.disabledPorts) &&
1562 (filteredPorts == other.filteredPorts) &&
Saurav Das018605f2017-02-18 14:05:44 -08001563 (errorPorts == other.errorPorts));
Saurav Dasd2fded02016-12-02 15:43:47 -08001564 }
1565
1566 @Override
1567 public String toString() {
1568 MoreObjects.ToStringHelper helper = toStringHelper(this)
1569 .add("disabledPorts", disabledPorts)
Saurav Das018605f2017-02-18 14:05:44 -08001570 .add("errorPorts", errorPorts)
Saurav Dasd2fded02016-12-02 15:43:47 -08001571 .add("filteredPorts", filteredPorts);
1572 return helper.toString();
1573 }
1574 }
1575
1576 /**
1577 * RetryFilters populates filtering objectives for a device and keeps retrying
1578 * till the number of ports filtered are constant for a predefined number
1579 * of attempts.
1580 */
1581 protected final class RetryFilters implements Runnable {
1582 int constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS;
1583 DeviceId devId;
1584 int counter;
1585 PortFilterInfo prevRun;
1586
1587 private RetryFilters(DeviceId deviceId, PortFilterInfo previousRun) {
Saurav Das59232cf2016-04-27 18:35:50 -07001588 devId = deviceId;
Saurav Dasd2fded02016-12-02 15:43:47 -08001589 prevRun = previousRun;
1590 counter = 0;
Saurav Das59232cf2016-04-27 18:35:50 -07001591 }
1592
1593 @Override
1594 public void run() {
Charles Chan7f9737b2017-06-22 14:27:17 -07001595 log.debug("RETRY FILTER ATTEMPT {} ** dev:{}", ++counter, devId);
Charles Chanf6ec1532017-02-08 16:10:40 -08001596 PortFilterInfo thisRun = rulePopulator.populateVlanMacFilters(devId);
Saurav Dasd2fded02016-12-02 15:43:47 -08001597 boolean sameResult = prevRun.equals(thisRun);
1598 log.debug("dev:{} prevRun:{} thisRun:{} sameResult:{}", devId, prevRun,
1599 thisRun, sameResult);
1600 if (thisRun == null || !sameResult || (sameResult && --constantAttempts > 0)) {
Saurav Das018605f2017-02-18 14:05:44 -08001601 // exponentially increasing intervals for retries
1602 executorService.schedule(this,
1603 RETRY_INTERVAL_MS * (int) Math.pow(counter, RETRY_INTERVAL_SCALE),
1604 TimeUnit.MILLISECONDS);
Saurav Dasd2fded02016-12-02 15:43:47 -08001605 if (!sameResult) {
1606 constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS; //reset
1607 }
Saurav Das59232cf2016-04-27 18:35:50 -07001608 }
Saurav Dasd2fded02016-12-02 15:43:47 -08001609 prevRun = (thisRun == null) ? prevRun : thisRun;
Saurav Das59232cf2016-04-27 18:35:50 -07001610 }
Saurav Das59232cf2016-04-27 18:35:50 -07001611 }
1612
sanghob35a6192015-04-01 13:05:26 -07001613}