blob: 46d94ed2b7a1f0240842e67e5e4c99831f640c71 [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 Chan92726132018-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
Saurav Dasa4020382018-02-14 14:14:54 -0800790 * @param nextHops Map of a set of next hops per destSw
Saurav Das7bcbe702017-06-13 15:35:54 -0700791 * @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));
Saurav Dasa4020382018-02-14 14:14:54 -0800825 // XXX - Rethink this - ignoring routerIPs in all other switches
826 // even edge to edge switches
Saurav Das7bcbe702017-06-13 15:35:54 -0700827 /*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 }
Saurav Dasc88d4662017-05-15 15:34:25 -0700847 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700848
849 if (!targetIsEdge && dest1IsEdge) {
850 // MPLS rules in all non-edge target devices. These rules are for
851 // individual destinations, even if the dsts are part of edge-pairs.
852 log.debug(". populateEcmpRoutingRulePartial in device{} towards {} for "
853 + "all MPLS rules", targetSw, destSw1);
854 result = rulePopulator.populateMplsRule(targetSw, destSw1,
855 nextHops.get(destSw1),
856 dest1RouterIpv4);
857 if (!result) {
858 return false;
859 }
860 if (dest1RouterIpv6 != null) {
Saurav Dasa4020382018-02-14 14:14:54 -0800861 int v4sid = 0, v6sid = 0;
862 try {
863 v4sid = config.getIPv4SegmentId(destSw1);
864 v6sid = config.getIPv6SegmentId(destSw1);
865 } catch (DeviceConfigNotFoundException e) {
866 log.warn(e.getMessage());
867 }
868 if (v4sid != v6sid) {
869 result = rulePopulator.populateMplsRule(targetSw, destSw1,
870 nextHops.get(destSw1),
871 dest1RouterIpv6);
872 if (!result) {
873 return false;
874 }
Saurav Das7bcbe702017-06-13 15:35:54 -0700875 }
876 }
877 }
878
879 // To save on ECMP groups
880 // avoid MPLS rules in non-edge-devices to non-edge-devices
881 // avoid MPLS transit rules in edge-devices
882 // avoid loopback IP rules in edge-devices to non-edge-devices
883 return true;
Saurav Dasc88d4662017-05-15 15:34:25 -0700884 }
885
886 /**
887 * Processes a set a route-path changes by editing hash groups.
888 *
889 * @param routeChanges a set of route-path changes, where each route-path is
890 * a list with its first element the src-switch of the path
891 * and the second element the dst-switch of the path.
892 * @param linkOrSwitchFailed true if the route changes are for a failed
893 * switch or linkDown event
894 * @param failedSwitch the switchId if the route changes are for a failed switch,
895 * otherwise null
896 */
897 private void processHashGroupChange(Set<ArrayList<DeviceId>> routeChanges,
898 boolean linkOrSwitchFailed,
899 DeviceId failedSwitch) {
Saurav Das9df5b7c2017-08-14 16:44:43 -0700900 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
901 // first, ensure each routeChanges entry has two elements
Saurav Dasc88d4662017-05-15 15:34:25 -0700902 for (ArrayList<DeviceId> route : routeChanges) {
Saurav Das9df5b7c2017-08-14 16:44:43 -0700903 if (route.size() == 1) {
904 // route-path changes are from everyone else to this switch
905 DeviceId dstSw = route.get(0);
906 srManager.deviceService.getAvailableDevices().forEach(sw -> {
907 if (!sw.id().equals(dstSw)) {
908 changedRoutes.add(Lists.newArrayList(sw.id(), dstSw));
909 }
910 });
911 } else {
912 changedRoutes.add(route);
Saurav Dasc88d4662017-05-15 15:34:25 -0700913 }
Saurav Das9df5b7c2017-08-14 16:44:43 -0700914 }
Saurav Dasc568c342018-01-25 09:49:01 -0800915 boolean someFailed = false;
916 Set<DeviceId> updatedDevices = Sets.newHashSet();
Saurav Das9df5b7c2017-08-14 16:44:43 -0700917 for (ArrayList<DeviceId> route : changedRoutes) {
918 DeviceId targetSw = route.get(0);
919 DeviceId dstSw = route.get(1);
Saurav Dasc88d4662017-05-15 15:34:25 -0700920 if (linkOrSwitchFailed) {
Saurav Das9df5b7c2017-08-14 16:44:43 -0700921 boolean success = fixHashGroupsForRoute(route, true);
Saurav Dasc88d4662017-05-15 15:34:25 -0700922 // it's possible that we cannot fix hash groups for a route
923 // if the target switch has failed. Nevertheless the ecmp graph
924 // for the impacted switch must still be updated.
Saurav Das9df5b7c2017-08-14 16:44:43 -0700925 if (!success && failedSwitch != null && targetSw.equals(failedSwitch)) {
Saurav Dasc88d4662017-05-15 15:34:25 -0700926 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
927 currentEcmpSpgMap.remove(targetSw);
Saurav Das9df5b7c2017-08-14 16:44:43 -0700928 log.debug("Updating ECMPspg for dst:{} removing failed switch "
Saurav Dasc88d4662017-05-15 15:34:25 -0700929 + "target:{}", dstSw, targetSw);
Saurav Dasc568c342018-01-25 09:49:01 -0800930 updatedDevices.add(targetSw);
931 updatedDevices.add(dstSw);
Saurav Das9df5b7c2017-08-14 16:44:43 -0700932 continue;
Saurav Dasc88d4662017-05-15 15:34:25 -0700933 }
934 //linkfailed - update both sides
Saurav Dasc88d4662017-05-15 15:34:25 -0700935 if (success) {
936 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
Saurav Das9df5b7c2017-08-14 16:44:43 -0700937 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
Saurav Dasc568c342018-01-25 09:49:01 -0800938 log.debug("Updating ECMPspg for dst:{} and target:{} for linkdown"
939 + " or switchdown", dstSw, targetSw);
940 updatedDevices.add(targetSw);
941 updatedDevices.add(dstSw);
942 } else {
943 someFailed = true;
Saurav Das9df5b7c2017-08-14 16:44:43 -0700944 }
945 } else {
946 //linkup of seen before link
947 boolean success = fixHashGroupsForRoute(route, false);
948 if (success) {
949 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
950 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
951 log.debug("Updating ECMPspg for target:{} and dst:{} for linkup",
Saurav Dasc88d4662017-05-15 15:34:25 -0700952 targetSw, dstSw);
Saurav Dasc568c342018-01-25 09:49:01 -0800953 updatedDevices.add(targetSw);
954 updatedDevices.add(dstSw);
955 } else {
956 someFailed = true;
Saurav Dasc88d4662017-05-15 15:34:25 -0700957 }
958 }
959 }
Saurav Dasc568c342018-01-25 09:49:01 -0800960 if (!someFailed) {
961 // here is where we update all devices not touched by this instance
962 updatedEcmpSpgMap.keySet().stream()
963 .filter(devId -> !updatedDevices.contains(devId))
964 .forEach(devId -> {
965 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
966 log.debug("Updating ECMPspg for remaining dev:{}", devId);
967 });
968 }
Saurav Dasc88d4662017-05-15 15:34:25 -0700969 }
970
971 /**
972 * Edits hash groups in the src-switch (targetSw) of a route-path by
973 * calling the groupHandler to either add or remove buckets in an existing
974 * hash group.
975 *
976 * @param route a single list representing a route-path where the first element
977 * is the src-switch (targetSw) of the route-path and the
978 * second element is the dst-switch
979 * @param revoke true if buckets in the hash-groups need to be removed;
980 * false if buckets in the hash-groups need to be added
981 * @return true if the hash group editing is successful
982 */
983 private boolean fixHashGroupsForRoute(ArrayList<DeviceId> route,
984 boolean revoke) {
985 DeviceId targetSw = route.get(0);
986 if (route.size() < 2) {
987 log.warn("Cannot fixHashGroupsForRoute - no dstSw in route {}", route);
988 return false;
989 }
990 DeviceId destSw = route.get(1);
Saurav Das9df5b7c2017-08-14 16:44:43 -0700991 log.debug("* processing fixHashGroupsForRoute: Target {} -> Dest {}",
Saurav Dasc88d4662017-05-15 15:34:25 -0700992 targetSw, destSw);
Saurav Dasc88d4662017-05-15 15:34:25 -0700993 // figure out the new next hops at the targetSw towards the destSw
Saurav Das9df5b7c2017-08-14 16:44:43 -0700994 Set<DeviceId> nextHops = getNextHops(targetSw, destSw);
Saurav Dasc88d4662017-05-15 15:34:25 -0700995 // call group handler to change hash group at targetSw
996 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
997 if (grpHandler == null) {
998 log.warn("Cannot find grouphandler for dev:{} .. aborting"
999 + " {} hash group buckets for route:{} ", targetSw,
1000 (revoke) ? "revoke" : "repopulate", route);
1001 return false;
1002 }
1003 log.debug("{} hash-groups buckets For Route {} -> {} to next-hops {}",
1004 (revoke) ? "revoke" : "repopulating",
1005 targetSw, destSw, nextHops);
1006 return (revoke) ? grpHandler.fixHashGroups(targetSw, nextHops,
1007 destSw, true)
1008 : grpHandler.fixHashGroups(targetSw, nextHops,
1009 destSw, false);
1010 }
1011
1012 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001013 * Start the flow rule population process if it was never started. The
1014 * process finishes successfully when all flow rules are set and stops with
1015 * ABORTED status when any groups required for flows is not set yet.
Saurav Dasc88d4662017-05-15 15:34:25 -07001016 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001017 public void startPopulationProcess() {
1018 statusLock.lock();
1019 try {
1020 if (populationStatus == Status.IDLE
1021 || populationStatus == Status.SUCCEEDED
1022 || populationStatus == Status.ABORTED) {
1023 populateAllRoutingRules();
sangho45b009c2015-05-07 13:30:57 -07001024 } else {
Saurav Das7bcbe702017-06-13 15:35:54 -07001025 log.warn("Not initiating startPopulationProcess as populationStatus is {}",
1026 populationStatus);
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001027 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001028 } finally {
1029 statusLock.unlock();
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001030 }
sangho20eff1d2015-04-13 15:15:58 -07001031 }
1032
Saurav Dasb5c236e2016-06-07 10:08:06 -07001033 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001034 * Revoke rules of given subnet in all edge switches.
1035 *
1036 * @param subnets subnet being removed
1037 * @return true if succeed
1038 */
1039 protected boolean revokeSubnet(Set<IpPrefix> subnets) {
1040 statusLock.lock();
1041 try {
1042 return srManager.routingRulePopulator.revokeIpRuleForSubnet(subnets);
1043 } finally {
1044 statusLock.unlock();
1045 }
1046 }
1047
1048 /**
Charles Chan2fde6d42017-08-23 14:46:43 -07001049 * Populates IP rules for a route that has direct connection to the switch
1050 * if the current instance is the master of the switch.
1051 *
1052 * @param deviceId device ID of the device that next hop attaches to
1053 * @param prefix IP prefix of the route
1054 * @param hostMac MAC address of the next hop
1055 * @param hostVlanId Vlan ID of the nexthop
1056 * @param outPort port where the next hop attaches to
1057 */
1058 void populateRoute(DeviceId deviceId, IpPrefix prefix,
1059 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
1060 if (srManager.mastershipService.isLocalMaster(deviceId)) {
1061 srManager.routingRulePopulator.populateRoute(deviceId, prefix, hostMac, hostVlanId, outPort);
1062 }
1063 }
1064
1065 /**
1066 * Removes IP rules for a route when the next hop is gone.
1067 * if the current instance is the master of the switch.
1068 *
1069 * @param deviceId device ID of the device that next hop attaches to
1070 * @param prefix IP prefix of the route
1071 * @param hostMac MAC address of the next hop
1072 * @param hostVlanId Vlan ID of the nexthop
1073 * @param outPort port that next hop attaches to
1074 */
1075 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
1076 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
1077 if (srManager.mastershipService.isLocalMaster(deviceId)) {
1078 srManager.routingRulePopulator.revokeRoute(deviceId, prefix, hostMac, hostVlanId, outPort);
1079 }
1080 }
1081
1082 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001083 * Remove ECMP graph entry for the given device. Typically called when
1084 * device is no longer available.
1085 *
1086 * @param deviceId the device for which graphs need to be purged
1087 */
1088 protected void purgeEcmpGraph(DeviceId deviceId) {
Saurav Dasc568c342018-01-25 09:49:01 -08001089 statusLock.lock();
1090 try {
1091
1092 if (populationStatus == Status.STARTED) {
1093 log.warn("Previous rule population is not finished. Cannot"
1094 + " proceeed with purgeEcmpGraph for {}", deviceId);
1095 return;
1096 }
1097 log.debug("Updating ECMPspg for unavailable dev:{}", deviceId);
1098 currentEcmpSpgMap.remove(deviceId);
1099 if (updatedEcmpSpgMap != null) {
1100 updatedEcmpSpgMap.remove(deviceId);
1101 }
1102 } finally {
1103 statusLock.unlock();
Saurav Das7bcbe702017-06-13 15:35:54 -07001104 }
1105 }
1106
1107 //////////////////////////////////////
1108 // Routing helper methods and classes
1109 //////////////////////////////////////
1110
1111 /**
Saurav Das4e3224f2016-11-29 14:27:25 -08001112 * Computes set of affected routes due to failed link. Assumes
Saurav Dasb5c236e2016-06-07 10:08:06 -07001113 * previous ecmp shortest-path graph exists for a switch in order to compute
1114 * affected routes. If such a graph does not exist, the method returns null.
1115 *
1116 * @param linkFail the failed link
1117 * @return the set of affected routes which may be empty if no routes were
1118 * affected, or null if no previous ecmp spg was found for comparison
1119 */
sangho20eff1d2015-04-13 15:15:58 -07001120 private Set<ArrayList<DeviceId>> computeDamagedRoutes(Link linkFail) {
sangho20eff1d2015-04-13 15:15:58 -07001121 Set<ArrayList<DeviceId>> routes = new HashSet<>();
1122
1123 for (Device sw : srManager.deviceService.getDevices()) {
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001124 log.debug("Computing the impacted routes for device {} due to link fail",
1125 sw.id());
Saurav Das9df5b7c2017-08-14 16:44:43 -07001126 DeviceId retId = shouldHandleRouting(sw.id());
1127 if (retId == null) {
sangho20eff1d2015-04-13 15:15:58 -07001128 continue;
1129 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001130 Set<DeviceId> devicesToProcess = Sets.newHashSet(retId, sw.id());
1131 for (DeviceId rootSw : devicesToProcess) {
1132 EcmpShortestPathGraph ecmpSpg = currentEcmpSpgMap.get(rootSw);
1133 if (ecmpSpg == null) {
1134 log.warn("No existing ECMP graph for switch {}. Aborting optimized"
1135 + " rerouting and opting for full-reroute", rootSw);
1136 return null;
1137 }
1138 if (log.isDebugEnabled()) {
1139 log.debug("Root switch: {}", rootSw);
1140 log.debug(" Current/Existing SPG: {}", ecmpSpg);
1141 log.debug(" New/Updated SPG: {}", updatedEcmpSpgMap.get(rootSw));
1142 }
1143 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>>
1144 switchVia = ecmpSpg.getAllLearnedSwitchesAndVia();
1145 // figure out if the broken link affected any route-paths in this graph
1146 for (Integer itrIdx : switchVia.keySet()) {
1147 log.trace("Current/Exiting SPG Iterindex# {}", itrIdx);
1148 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1149 switchVia.get(itrIdx);
1150 for (DeviceId targetSw : swViaMap.keySet()) {
1151 log.trace("TargetSwitch {} --> RootSwitch {}",
1152 targetSw, rootSw);
Saurav Dasb5c236e2016-06-07 10:08:06 -07001153 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1154 log.trace(" Via:");
Pier Ventree0ae7a32016-11-23 09:57:42 -08001155 via.forEach(e -> log.trace(" {}", e));
Saurav Dasb5c236e2016-06-07 10:08:06 -07001156 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001157 Set<ArrayList<DeviceId>> subLinks =
1158 computeLinks(targetSw, rootSw, swViaMap);
1159 for (ArrayList<DeviceId> alink: subLinks) {
1160 if ((alink.get(0).equals(linkFail.src().deviceId()) &&
1161 alink.get(1).equals(linkFail.dst().deviceId()))
1162 ||
1163 (alink.get(0).equals(linkFail.dst().deviceId()) &&
1164 alink.get(1).equals(linkFail.src().deviceId()))) {
1165 log.debug("Impacted route:{}->{}", targetSw, rootSw);
1166 ArrayList<DeviceId> aRoute = new ArrayList<>();
1167 aRoute.add(targetSw); // switch with rules to populate
1168 aRoute.add(rootSw); // towards this destination
1169 routes.add(aRoute);
1170 break;
1171 }
sangho20eff1d2015-04-13 15:15:58 -07001172 }
1173 }
1174 }
Saurav Das9df5b7c2017-08-14 16:44:43 -07001175
sangho20eff1d2015-04-13 15:15:58 -07001176 }
sangho45b009c2015-05-07 13:30:57 -07001177
sangho20eff1d2015-04-13 15:15:58 -07001178 }
sangho20eff1d2015-04-13 15:15:58 -07001179 return routes;
1180 }
1181
Saurav Das4e3224f2016-11-29 14:27:25 -08001182 /**
1183 * Computes set of affected routes due to new links or failed switches.
1184 *
1185 * @return the set of affected routes which may be empty if no routes were
1186 * affected
1187 */
sangho20eff1d2015-04-13 15:15:58 -07001188 private Set<ArrayList<DeviceId>> computeRouteChange() {
Saurav Das7bcbe702017-06-13 15:35:54 -07001189 ImmutableSet.Builder<ArrayList<DeviceId>> changedRtBldr =
Saurav Das4e3224f2016-11-29 14:27:25 -08001190 ImmutableSet.builder();
sangho20eff1d2015-04-13 15:15:58 -07001191
1192 for (Device sw : srManager.deviceService.getDevices()) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001193 log.debug("Computing the impacted routes for device {}", sw.id());
1194 DeviceId retId = shouldHandleRouting(sw.id());
1195 if (retId == null) {
sangho20eff1d2015-04-13 15:15:58 -07001196 continue;
1197 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001198 Set<DeviceId> devicesToProcess = Sets.newHashSet(retId, sw.id());
1199 for (DeviceId rootSw : devicesToProcess) {
1200 if (log.isTraceEnabled()) {
1201 log.trace("Device links for dev: {}", rootSw);
1202 for (Link link: srManager.linkService.getDeviceLinks(rootSw)) {
1203 log.trace("{} -> {} ", link.src().deviceId(),
1204 link.dst().deviceId());
1205 }
Saurav Dasb5c236e2016-06-07 10:08:06 -07001206 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001207 EcmpShortestPathGraph currEcmpSpg = currentEcmpSpgMap.get(rootSw);
1208 if (currEcmpSpg == null) {
1209 log.debug("No existing ECMP graph for device {}.. adding self as "
1210 + "changed route", rootSw);
1211 changedRtBldr.add(Lists.newArrayList(rootSw));
1212 continue;
1213 }
1214 EcmpShortestPathGraph newEcmpSpg = updatedEcmpSpgMap.get(rootSw);
1215 if (log.isDebugEnabled()) {
1216 log.debug("Root switch: {}", rootSw);
1217 log.debug(" Current/Existing SPG: {}", currEcmpSpg);
1218 log.debug(" New/Updated SPG: {}", newEcmpSpg);
1219 }
1220 // first use the updated/new map to compare to current/existing map
1221 // as new links may have come up
1222 changedRtBldr.addAll(compareGraphs(newEcmpSpg, currEcmpSpg, rootSw));
1223 // then use the current/existing map to compare to updated/new map
1224 // as switch may have been removed
1225 changedRtBldr.addAll(compareGraphs(currEcmpSpg, newEcmpSpg, rootSw));
sangho45b009c2015-05-07 13:30:57 -07001226 }
Saurav Das4e3224f2016-11-29 14:27:25 -08001227 }
sangho20eff1d2015-04-13 15:15:58 -07001228
Saurav Das7bcbe702017-06-13 15:35:54 -07001229 Set<ArrayList<DeviceId>> changedRoutes = changedRtBldr.build();
Saurav Das4e3224f2016-11-29 14:27:25 -08001230 for (ArrayList<DeviceId> route: changedRoutes) {
1231 log.debug("Route changes Target -> Root");
1232 if (route.size() == 1) {
1233 log.debug(" : all -> {}", route.get(0));
1234 } else {
1235 log.debug(" : {} -> {}", route.get(0), route.get(1));
1236 }
1237 }
1238 return changedRoutes;
1239 }
1240
1241 /**
1242 * For the root switch, searches all the target nodes reachable in the base
1243 * graph, and compares paths to the ones in the comp graph.
1244 *
1245 * @param base the graph that is indexed for all reachable target nodes
1246 * from the root node
1247 * @param comp the graph that the base graph is compared to
1248 * @param rootSw both ecmp graphs are calculated for the root node
1249 * @return all the routes that have changed in the base graph
1250 */
1251 private Set<ArrayList<DeviceId>> compareGraphs(EcmpShortestPathGraph base,
1252 EcmpShortestPathGraph comp,
1253 DeviceId rootSw) {
1254 ImmutableSet.Builder<ArrayList<DeviceId>> changedRoutesBuilder =
1255 ImmutableSet.builder();
1256 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> baseMap =
1257 base.getAllLearnedSwitchesAndVia();
1258 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> compMap =
1259 comp.getAllLearnedSwitchesAndVia();
1260 for (Integer itrIdx : baseMap.keySet()) {
1261 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> baseViaMap =
1262 baseMap.get(itrIdx);
1263 for (DeviceId targetSw : baseViaMap.keySet()) {
1264 ArrayList<ArrayList<DeviceId>> basePath = baseViaMap.get(targetSw);
1265 ArrayList<ArrayList<DeviceId>> compPath = getVia(compMap, targetSw);
1266 if ((compPath == null) || !basePath.equals(compPath)) {
Saurav Dasc88d4662017-05-15 15:34:25 -07001267 log.trace("Impacted route:{} -> {}", targetSw, rootSw);
Saurav Das4e3224f2016-11-29 14:27:25 -08001268 ArrayList<DeviceId> route = new ArrayList<>();
Saurav Das7bcbe702017-06-13 15:35:54 -07001269 route.add(targetSw); // switch with rules to populate
1270 route.add(rootSw); // towards this destination
Saurav Das4e3224f2016-11-29 14:27:25 -08001271 changedRoutesBuilder.add(route);
sangho20eff1d2015-04-13 15:15:58 -07001272 }
1273 }
sangho45b009c2015-05-07 13:30:57 -07001274 }
Saurav Das4e3224f2016-11-29 14:27:25 -08001275 return changedRoutesBuilder.build();
sangho20eff1d2015-04-13 15:15:58 -07001276 }
1277
Saurav Das7bcbe702017-06-13 15:35:54 -07001278 /**
1279 * Returns the ECMP paths traversed to reach the target switch.
1280 *
1281 * @param switchVia a per-iteration view of the ECMP graph for a root switch
1282 * @param targetSw the switch to reach from the root switch
1283 * @return the nodes traversed on ECMP paths to the target switch
1284 */
sangho20eff1d2015-04-13 15:15:58 -07001285 private ArrayList<ArrayList<DeviceId>> getVia(HashMap<Integer, HashMap<DeviceId,
Saurav Das4e3224f2016-11-29 14:27:25 -08001286 ArrayList<ArrayList<DeviceId>>>> switchVia, DeviceId targetSw) {
sangho20eff1d2015-04-13 15:15:58 -07001287 for (Integer itrIdx : switchVia.keySet()) {
1288 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1289 switchVia.get(itrIdx);
Saurav Das4e3224f2016-11-29 14:27:25 -08001290 if (swViaMap.get(targetSw) == null) {
sangho20eff1d2015-04-13 15:15:58 -07001291 continue;
1292 } else {
Saurav Das4e3224f2016-11-29 14:27:25 -08001293 return swViaMap.get(targetSw);
sangho20eff1d2015-04-13 15:15:58 -07001294 }
1295 }
1296
Srikanth Vavilapalli5428b6c2015-05-14 20:22:47 -07001297 return null;
sangho20eff1d2015-04-13 15:15:58 -07001298 }
1299
Saurav Das7bcbe702017-06-13 15:35:54 -07001300 /**
1301 * Utility method to break down a path from src to dst device into a collection
1302 * of links.
1303 *
1304 * @param src src device of the path
1305 * @param dst dst device of the path
1306 * @param viaMap path taken from src to dst device
1307 * @return collection of links in the path
1308 */
sangho20eff1d2015-04-13 15:15:58 -07001309 private Set<ArrayList<DeviceId>> computeLinks(DeviceId src,
1310 DeviceId dst,
1311 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> viaMap) {
1312 Set<ArrayList<DeviceId>> subLinks = Sets.newHashSet();
1313 for (ArrayList<DeviceId> via : viaMap.get(src)) {
1314 DeviceId linkSrc = src;
1315 DeviceId linkDst = dst;
1316 for (DeviceId viaDevice: via) {
1317 ArrayList<DeviceId> link = new ArrayList<>();
1318 linkDst = viaDevice;
1319 link.add(linkSrc);
1320 link.add(linkDst);
1321 subLinks.add(link);
1322 linkSrc = viaDevice;
1323 }
1324 ArrayList<DeviceId> link = new ArrayList<>();
1325 link.add(linkSrc);
1326 link.add(dst);
1327 subLinks.add(link);
1328 }
1329
1330 return subLinks;
1331 }
1332
Charles Chan93e71ba2016-04-29 14:38:22 -07001333 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001334 * Determines whether this controller instance should handle routing for the
1335 * given {@code deviceId}, based on mastership and pairDeviceId if one exists.
1336 * Returns null if this instance should not handle routing for given {@code deviceId}.
1337 * Otherwise the returned value could be the given deviceId itself, or the
1338 * deviceId for the paired edge device. In the latter case, this instance
1339 * should handle routing for both the given device and the paired device.
Charles Chan93e71ba2016-04-29 14:38:22 -07001340 *
Saurav Das7bcbe702017-06-13 15:35:54 -07001341 * @param deviceId device identifier to consider for routing
1342 * @return null or deviceId which could be the same as the given deviceId
1343 * or the deviceId of a paired edge device
Charles Chan93e71ba2016-04-29 14:38:22 -07001344 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001345 private DeviceId shouldHandleRouting(DeviceId deviceId) {
1346 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1347 log.debug("Not master for dev:{} .. skipping routing, may get handled "
1348 + "elsewhere as part of paired devices", deviceId);
1349 return null;
1350 }
1351 NodeId myNode = srManager.mastershipService.getMasterFor(deviceId);
1352 DeviceId pairDev = getPairDev(deviceId);
sanghob35a6192015-04-01 13:05:26 -07001353
Saurav Das7bcbe702017-06-13 15:35:54 -07001354 if (pairDev != null) {
1355 if (!srManager.deviceService.isAvailable(pairDev)) {
1356 log.warn("pairedDev {} not available .. routing this dev:{} "
1357 + "without mastership check",
1358 pairDev, deviceId);
1359 return pairDev; // handle both temporarily
1360 }
1361 NodeId pairMasterNode = srManager.mastershipService.getMasterFor(pairDev);
1362 if (myNode.compareTo(pairMasterNode) <= 0) {
1363 log.debug("Handling routing for both dev:{} pair-dev:{}; myNode: {}"
1364 + " pairMaster:{} compare:{}", deviceId, pairDev,
1365 myNode, pairMasterNode,
1366 myNode.compareTo(pairMasterNode));
1367 return pairDev; // handle both
1368 } else {
1369 log.debug("PairDev node: {} should handle routing for dev:{} and "
1370 + "pair-dev:{}", pairMasterNode, deviceId, pairDev);
1371 return null; // handle neither
sanghob35a6192015-04-01 13:05:26 -07001372 }
1373 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001374 return deviceId; // not paired, just handle given device
sanghob35a6192015-04-01 13:05:26 -07001375 }
1376
Charles Chan93e71ba2016-04-29 14:38:22 -07001377 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001378 * Returns the configured paired DeviceId for the given Device, or null
1379 * if no such paired device has been configured.
Charles Chan93e71ba2016-04-29 14:38:22 -07001380 *
Saurav Das7bcbe702017-06-13 15:35:54 -07001381 * @param deviceId
1382 * @return configured pair deviceId or null
Charles Chan93e71ba2016-04-29 14:38:22 -07001383 */
Saurav Das7bcbe702017-06-13 15:35:54 -07001384 private DeviceId getPairDev(DeviceId deviceId) {
1385 DeviceId pairDev;
Charles Chan0b4e6182015-11-03 10:42:14 -08001386 try {
Saurav Das7bcbe702017-06-13 15:35:54 -07001387 pairDev = srManager.deviceConfiguration.getPairDeviceId(deviceId);
Charles Chan0b4e6182015-11-03 10:42:14 -08001388 } catch (DeviceConfigNotFoundException e) {
Saurav Das7bcbe702017-06-13 15:35:54 -07001389 log.warn(e.getMessage() + " .. cannot continue routing for dev: {}");
1390 return null;
Charles Chan0b4e6182015-11-03 10:42:14 -08001391 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001392 return pairDev;
sanghob35a6192015-04-01 13:05:26 -07001393 }
1394
1395 /**
Saurav Das7bcbe702017-06-13 15:35:54 -07001396 * Returns the set of deviceIds which are the next hops from the targetSw
1397 * to the dstSw according to the latest ECMP spg.
1398 *
1399 * @param targetSw the switch for which the next-hops are desired
1400 * @param dstSw the switch to which the next-hops lead to from the targetSw
1401 * @return set of next hop deviceIds, could be empty if no next hops are found
1402 */
1403 private Set<DeviceId> getNextHops(DeviceId targetSw, DeviceId dstSw) {
1404 boolean targetIsEdge = false;
1405 try {
1406 targetIsEdge = srManager.deviceConfiguration.isEdgeDevice(targetSw);
1407 } catch (DeviceConfigNotFoundException e) {
1408 log.warn(e.getMessage() + "Cannot determine if targetIsEdge {}.. "
1409 + "continuing to getNextHops", targetSw);
1410 }
1411
1412 EcmpShortestPathGraph ecmpSpg = updatedEcmpSpgMap.get(dstSw);
1413 if (ecmpSpg == null) {
1414 log.debug("No ecmpSpg found for dstSw: {}", dstSw);
1415 return ImmutableSet.of();
1416 }
1417 HashMap<Integer,
1418 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> switchVia =
1419 ecmpSpg.getAllLearnedSwitchesAndVia();
1420 for (Integer itrIdx : switchVia.keySet()) {
1421 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1422 switchVia.get(itrIdx);
1423 for (DeviceId target : swViaMap.keySet()) {
1424 if (!target.equals(targetSw)) {
1425 continue;
1426 }
1427 if (!targetIsEdge && itrIdx > 1) {
Saurav Dasa4020382018-02-14 14:14:54 -08001428 // optimization for spines to not use leaves to get
1429 // to a spine or other leaves
1430 boolean pathdevIsEdge = false;
1431 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1432 for (DeviceId pathdev : via) {
1433 try {
1434 pathdevIsEdge = srManager.deviceConfiguration
1435 .isEdgeDevice(pathdev);
1436 } catch (DeviceConfigNotFoundException e) {
1437 log.warn(e.getMessage());
1438 }
1439 if (pathdevIsEdge) {
1440 log.debug("Avoiding {} hop path for non-edge targetSw:{}"
1441 + " --> dstSw:{} which goes through an edge"
1442 + " device {} in path {}", itrIdx,
1443 targetSw, dstSw, pathdev, via);
1444 return ImmutableSet.of();
1445 }
1446 }
1447 }
Saurav Das7bcbe702017-06-13 15:35:54 -07001448 }
1449 Set<DeviceId> nextHops = new HashSet<>();
1450 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1451 if (via.isEmpty()) {
1452 // the dstSw is the next-hop from the targetSw
1453 nextHops.add(dstSw);
1454 } else {
1455 // first elem is next-hop in each ECMP path
1456 nextHops.add(via.get(0));
1457 }
1458 }
1459 return nextHops;
1460 }
1461 }
1462 return ImmutableSet.of(); //no next-hops found
1463 }
1464
1465 /**
1466 * Represents two devices that are paired by configuration. An EdgePair for
1467 * (dev1, dev2) is the same as as EdgePair for (dev2, dev1)
1468 */
1469 protected final class EdgePair {
1470 DeviceId dev1;
1471 DeviceId dev2;
1472
1473 EdgePair(DeviceId dev1, DeviceId dev2) {
1474 this.dev1 = dev1;
1475 this.dev2 = dev2;
1476 }
1477
1478 boolean includes(DeviceId dev) {
1479 return dev1.equals(dev) || dev2.equals(dev);
1480 }
1481
1482 @Override
1483 public boolean equals(Object o) {
1484 if (this == o) {
1485 return true;
1486 }
1487 if (!(o instanceof EdgePair)) {
1488 return false;
1489 }
1490 EdgePair that = (EdgePair) o;
1491 return ((this.dev1.equals(that.dev1) && this.dev2.equals(that.dev2)) ||
1492 (this.dev1.equals(that.dev2) && this.dev2.equals(that.dev1)));
1493 }
1494
1495 @Override
1496 public int hashCode() {
1497 if (dev1.toString().compareTo(dev2.toString()) <= 0) {
1498 return Objects.hash(dev1, dev2);
1499 } else {
1500 return Objects.hash(dev2, dev1);
1501 }
1502 }
1503
1504 @Override
1505 public String toString() {
1506 return toStringHelper(this)
1507 .add("Dev1", dev1)
1508 .add("Dev2", dev2)
1509 .toString();
1510 }
1511 }
1512
1513 //////////////////////////////////////
1514 // Filtering rule creation
1515 //////////////////////////////////////
1516
1517 /**
Saurav Das018605f2017-02-18 14:05:44 -08001518 * Populates filtering rules for port, and punting rules
1519 * for gateway IPs, loopback IPs and arp/ndp traffic.
1520 * Should only be called by the master instance for this device/port.
sanghob35a6192015-04-01 13:05:26 -07001521 *
1522 * @param deviceId Switch ID to set the rules
1523 */
Saurav Das822c4e22015-10-23 10:51:11 -07001524 public void populatePortAddressingRules(DeviceId deviceId) {
Saurav Das59232cf2016-04-27 18:35:50 -07001525 // Although device is added, sometimes device store does not have the
1526 // ports for this device yet. It results in missing filtering rules in the
1527 // switch. We will attempt it a few times. If it still does not work,
1528 // user can manually repopulate using CLI command sr-reroute-network
Charles Chanf6ec1532017-02-08 16:10:40 -08001529 PortFilterInfo firstRun = rulePopulator.populateVlanMacFilters(deviceId);
Saurav Dasd2fded02016-12-02 15:43:47 -08001530 if (firstRun == null) {
1531 firstRun = new PortFilterInfo(0, 0, 0);
Saurav Das59232cf2016-04-27 18:35:50 -07001532 }
Saurav Dasd2fded02016-12-02 15:43:47 -08001533 executorService.schedule(new RetryFilters(deviceId, firstRun),
1534 RETRY_INTERVAL_MS, TimeUnit.MILLISECONDS);
sanghob35a6192015-04-01 13:05:26 -07001535 }
1536
1537 /**
Saurav Dasd2fded02016-12-02 15:43:47 -08001538 * Utility class used to temporarily store information about the ports on a
1539 * device processed for filtering objectives.
Saurav Dasd2fded02016-12-02 15:43:47 -08001540 */
1541 public final class PortFilterInfo {
Saurav Das018605f2017-02-18 14:05:44 -08001542 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das59232cf2016-04-27 18:35:50 -07001543
Saurav Das018605f2017-02-18 14:05:44 -08001544 public PortFilterInfo(int disabledPorts, int errorPorts,
Saurav Dasd2fded02016-12-02 15:43:47 -08001545 int filteredPorts) {
1546 this.disabledPorts = disabledPorts;
1547 this.filteredPorts = filteredPorts;
Saurav Das018605f2017-02-18 14:05:44 -08001548 this.errorPorts = errorPorts;
Saurav Dasd2fded02016-12-02 15:43:47 -08001549 }
1550
1551 @Override
1552 public int hashCode() {
Saurav Das018605f2017-02-18 14:05:44 -08001553 return Objects.hash(disabledPorts, filteredPorts, errorPorts);
Saurav Dasd2fded02016-12-02 15:43:47 -08001554 }
1555
1556 @Override
1557 public boolean equals(Object obj) {
1558 if (this == obj) {
1559 return true;
1560 }
1561 if ((obj == null) || (!(obj instanceof PortFilterInfo))) {
1562 return false;
1563 }
1564 PortFilterInfo other = (PortFilterInfo) obj;
1565 return ((disabledPorts == other.disabledPorts) &&
1566 (filteredPorts == other.filteredPorts) &&
Saurav Das018605f2017-02-18 14:05:44 -08001567 (errorPorts == other.errorPorts));
Saurav Dasd2fded02016-12-02 15:43:47 -08001568 }
1569
1570 @Override
1571 public String toString() {
1572 MoreObjects.ToStringHelper helper = toStringHelper(this)
1573 .add("disabledPorts", disabledPorts)
Saurav Das018605f2017-02-18 14:05:44 -08001574 .add("errorPorts", errorPorts)
Saurav Dasd2fded02016-12-02 15:43:47 -08001575 .add("filteredPorts", filteredPorts);
1576 return helper.toString();
1577 }
1578 }
1579
1580 /**
1581 * RetryFilters populates filtering objectives for a device and keeps retrying
1582 * till the number of ports filtered are constant for a predefined number
1583 * of attempts.
1584 */
1585 protected final class RetryFilters implements Runnable {
1586 int constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS;
1587 DeviceId devId;
1588 int counter;
1589 PortFilterInfo prevRun;
1590
1591 private RetryFilters(DeviceId deviceId, PortFilterInfo previousRun) {
Saurav Das59232cf2016-04-27 18:35:50 -07001592 devId = deviceId;
Saurav Dasd2fded02016-12-02 15:43:47 -08001593 prevRun = previousRun;
1594 counter = 0;
Saurav Das59232cf2016-04-27 18:35:50 -07001595 }
1596
1597 @Override
1598 public void run() {
Charles Chan7f9737b2017-06-22 14:27:17 -07001599 log.debug("RETRY FILTER ATTEMPT {} ** dev:{}", ++counter, devId);
Charles Chanf6ec1532017-02-08 16:10:40 -08001600 PortFilterInfo thisRun = rulePopulator.populateVlanMacFilters(devId);
Saurav Dasd2fded02016-12-02 15:43:47 -08001601 boolean sameResult = prevRun.equals(thisRun);
1602 log.debug("dev:{} prevRun:{} thisRun:{} sameResult:{}", devId, prevRun,
1603 thisRun, sameResult);
Ray Milkeyc6c9b172018-02-26 09:36:31 -08001604 if (thisRun == null || !sameResult || (--constantAttempts > 0)) {
Saurav Das018605f2017-02-18 14:05:44 -08001605 // exponentially increasing intervals for retries
1606 executorService.schedule(this,
1607 RETRY_INTERVAL_MS * (int) Math.pow(counter, RETRY_INTERVAL_SCALE),
1608 TimeUnit.MILLISECONDS);
Saurav Dasd2fded02016-12-02 15:43:47 -08001609 if (!sameResult) {
1610 constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS; //reset
1611 }
Saurav Das59232cf2016-04-27 18:35:50 -07001612 }
Saurav Dasd2fded02016-12-02 15:43:47 -08001613 prevRun = (thisRun == null) ? prevRun : thisRun;
Saurav Das59232cf2016-04-27 18:35:50 -07001614 }
Saurav Das59232cf2016-04-27 18:35:50 -07001615 }
1616
sanghob35a6192015-04-01 13:05:26 -07001617}