blob: 709d05eb060e08472580c901784cd32443278813 [file] [log] [blame]
sangho80f11cb2015-04-01 13:05:26 -07001/*
Brian O'Connor0947d7e2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho80f11cb2015-04-01 13:05:26 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.segmentrouting;
17
Saurav Dasd1872b02016-12-02 15:43:47 -080018import com.google.common.base.MoreObjects;
Saurav Das62ae6792017-05-15 15:34:25 -070019import com.google.common.collect.ImmutableMap;
20import com.google.common.collect.ImmutableMap.Builder;
Charles Chanc22cef32016-04-29 14:38:22 -070021import com.google.common.collect.ImmutableSet;
Saurav Das1b391d52016-11-29 14:27:25 -080022import com.google.common.collect.Lists;
sanghofb7c7292015-04-13 15:15:58 -070023import com.google.common.collect.Maps;
24import com.google.common.collect.Sets;
Saurav Dasfbe74572017-08-03 18:30:35 -070025
26import org.joda.time.DateTime;
sangho9b169e32015-04-14 16:27:13 -070027import org.onlab.packet.Ip4Address;
Pier Ventreadb4ae62016-11-23 09:57:42 -080028import org.onlab.packet.Ip6Address;
sangho80f11cb2015-04-01 13:05:26 -070029import org.onlab.packet.IpPrefix;
Charles Chan910be6a2017-08-23 14:46:43 -070030import org.onlab.packet.MacAddress;
31import org.onlab.packet.VlanId;
Saurav Das261c3002017-06-13 15:35:54 -070032import org.onosproject.cluster.NodeId;
Charles Chanc22cef32016-04-29 14:38:22 -070033import org.onosproject.net.ConnectPoint;
sangho80f11cb2015-04-01 13:05:26 -070034import org.onosproject.net.Device;
35import org.onosproject.net.DeviceId;
sanghofb7c7292015-04-13 15:15:58 -070036import org.onosproject.net.Link;
Charles Chan910be6a2017-08-23 14:46:43 -070037import org.onosproject.net.PortNumber;
Charles Chan319d1a22015-11-03 10:42:14 -080038import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
39import org.onosproject.segmentrouting.config.DeviceConfiguration;
Saurav Das62ae6792017-05-15 15:34:25 -070040import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
sangho80f11cb2015-04-01 13:05:26 -070041import org.slf4j.Logger;
42import org.slf4j.LoggerFactory;
43
44import java.util.ArrayList;
45import java.util.HashMap;
46import java.util.HashSet;
Saurav Das261c3002017-06-13 15:35:54 -070047import java.util.Iterator;
48import java.util.Map;
Saurav Dasd1872b02016-12-02 15:43:47 -080049import java.util.Objects;
sangho80f11cb2015-04-01 13:05:26 -070050import java.util.Set;
Saurav Das07c74602016-04-27 18:35:50 -070051import java.util.concurrent.ScheduledExecutorService;
52import java.util.concurrent.TimeUnit;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +090053import java.util.concurrent.locks.Lock;
54import java.util.concurrent.locks.ReentrantLock;
sangho80f11cb2015-04-01 13:05:26 -070055
Saurav Dasd1872b02016-12-02 15:43:47 -080056import static com.google.common.base.MoreObjects.toStringHelper;
Pier Ventreadb4ae62016-11-23 09:57:42 -080057import static com.google.common.base.Preconditions.checkNotNull;
58import static java.util.concurrent.Executors.newScheduledThreadPool;
59import static org.onlab.util.Tools.groupedThreads;
sangho80f11cb2015-04-01 13:05:26 -070060
Charles Chanb7f75ac2016-01-11 18:28:54 -080061/**
62 * Default routing handler that is responsible for route computing and
63 * routing rule population.
64 */
sangho80f11cb2015-04-01 13:05:26 -070065public class DefaultRoutingHandler {
Saurav Dasf9332192017-02-18 14:05:44 -080066 private static final int MAX_CONSTANT_RETRY_ATTEMPTS = 5;
67 private static final int RETRY_INTERVAL_MS = 250;
68 private static final int RETRY_INTERVAL_SCALE = 1;
Saurav Dasfbe74572017-08-03 18:30:35 -070069 private static final long STABLITY_THRESHOLD = 10; //secs
Saurav Dasfe0b05e2017-08-14 16:44:43 -070070 private static final int UPDATE_INTERVAL = 5; //secs
Charles Chanc22cef32016-04-29 14:38:22 -070071 private static Logger log = LoggerFactory.getLogger(DefaultRoutingHandler.class);
sangho80f11cb2015-04-01 13:05:26 -070072
73 private SegmentRoutingManager srManager;
74 private RoutingRulePopulator rulePopulator;
Shashikanth VH0637b162015-12-11 01:32:44 +053075 private HashMap<DeviceId, EcmpShortestPathGraph> currentEcmpSpgMap;
76 private HashMap<DeviceId, EcmpShortestPathGraph> updatedEcmpSpgMap;
sangho9b169e32015-04-14 16:27:13 -070077 private DeviceConfiguration config;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +090078 private final Lock statusLock = new ReentrantLock();
79 private volatile Status populationStatus;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -070080 private ScheduledExecutorService executorService
Saurav Dasd1872b02016-12-02 15:43:47 -080081 = newScheduledThreadPool(1, groupedThreads("retryftr", "retry-%d", log));
Saurav Dasfbe74572017-08-03 18:30:35 -070082 private DateTime lastRoutingChange;
sangho80f11cb2015-04-01 13:05:26 -070083
84 /**
85 * Represents the default routing population status.
86 */
87 public enum Status {
88 // population process is not started yet.
89 IDLE,
90
91 // population process started.
92 STARTED,
93
Srikanth Vavilapalli64505482015-04-21 13:04:13 -070094 // population process was aborted due to errors, mostly for groups not
95 // found.
sangho80f11cb2015-04-01 13:05:26 -070096 ABORTED,
97
98 // population process was finished successfully.
99 SUCCEEDED
100 }
101
102 /**
103 * Creates a DefaultRoutingHandler object.
104 *
105 * @param srManager SegmentRoutingManager object
106 */
107 public DefaultRoutingHandler(SegmentRoutingManager srManager) {
108 this.srManager = srManager;
109 this.rulePopulator = checkNotNull(srManager.routingRulePopulator);
sangho9b169e32015-04-14 16:27:13 -0700110 this.config = checkNotNull(srManager.deviceConfiguration);
sangho80f11cb2015-04-01 13:05:26 -0700111 this.populationStatus = Status.IDLE;
sanghofb7c7292015-04-13 15:15:58 -0700112 this.currentEcmpSpgMap = Maps.newHashMap();
sangho80f11cb2015-04-01 13:05:26 -0700113 }
114
115 /**
Saurav Das62ae6792017-05-15 15:34:25 -0700116 * Returns an immutable copy of the current ECMP shortest-path graph as
117 * computed by this controller instance.
118 *
Saurav Das261c3002017-06-13 15:35:54 -0700119 * @return immutable copy of the current ECMP graph
Saurav Das62ae6792017-05-15 15:34:25 -0700120 */
121 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEmcpSpgMap() {
122 Builder<DeviceId, EcmpShortestPathGraph> builder = ImmutableMap.builder();
123 currentEcmpSpgMap.entrySet().forEach(entry -> {
124 if (entry.getValue() != null) {
125 builder.put(entry.getKey(), entry.getValue());
126 }
127 });
128 return builder.build();
129 }
130
Saurav Dasfbe74572017-08-03 18:30:35 -0700131 /**
132 * Acquires the lock used when making routing changes.
133 */
134 public void acquireRoutingLock() {
135 statusLock.lock();
136 }
137
138 /**
139 * Releases the lock used when making routing changes.
140 */
141 public void releaseRoutingLock() {
142 statusLock.unlock();
143 }
144
145 /**
146 * Determines if routing in the network has been stable in the last
147 * STABLITY_THRESHOLD seconds, by comparing the current time to the last
148 * routing change timestamp.
149 *
150 * @return true if stable
151 */
152 public boolean isRoutingStable() {
153 long last = (long) (lastRoutingChange.getMillis() / 1000.0);
154 long now = (long) (DateTime.now().getMillis() / 1000.0);
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700155 log.trace("Routing stable since {}s", now - last);
Saurav Dasfbe74572017-08-03 18:30:35 -0700156 return (now - last) > STABLITY_THRESHOLD;
157 }
158
159
Saurav Das261c3002017-06-13 15:35:54 -0700160 //////////////////////////////////////
161 // Route path handling
162 //////////////////////////////////////
163
164 /* The following three methods represent the three major ways in routing
165 * is triggered in the network
166 * a) due to configuration change
167 * b) due to route-added event
168 * c) due to change in the topology
169 */
170
Saurav Das62ae6792017-05-15 15:34:25 -0700171 /**
Saurav Das261c3002017-06-13 15:35:54 -0700172 * Populates all routing rules to all switches. Typically triggered at
173 * startup or after a configuration event.
sangho80f11cb2015-04-01 13:05:26 -0700174 */
Saurav Das62ae6792017-05-15 15:34:25 -0700175 public void populateAllRoutingRules() {
Saurav Dasfbe74572017-08-03 18:30:35 -0700176 lastRoutingChange = DateTime.now();
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900177 statusLock.lock();
178 try {
Saurav Das261c3002017-06-13 15:35:54 -0700179 if (populationStatus == Status.STARTED) {
180 log.warn("Previous rule population is not finished. Cannot"
181 + " proceed with populateAllRoutingRules");
182 return;
183 }
184
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900185 populationStatus = Status.STARTED;
186 rulePopulator.resetCounter();
Saurav Das261c3002017-06-13 15:35:54 -0700187 log.info("Starting to populate all routing rules");
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900188 log.debug("populateAllRoutingRules: populationStatus is STARTED");
sangho80f11cb2015-04-01 13:05:26 -0700189
Saurav Das261c3002017-06-13 15:35:54 -0700190 // take a snapshot of the topology
191 updatedEcmpSpgMap = new HashMap<>();
192 Set<EdgePair> edgePairs = new HashSet<>();
193 Set<ArrayList<DeviceId>> routeChanges = new HashSet<>();
194 for (Device dstSw : srManager.deviceService.getDevices()) {
195 EcmpShortestPathGraph ecmpSpgUpdated =
196 new EcmpShortestPathGraph(dstSw.id(), srManager);
197 updatedEcmpSpgMap.put(dstSw.id(), ecmpSpgUpdated);
198 DeviceId pairDev = getPairDev(dstSw.id());
199 if (pairDev != null) {
200 // pairDev may not be available yet, but we still need to add
201 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev, srManager);
202 updatedEcmpSpgMap.put(pairDev, ecmpSpgUpdated);
203 edgePairs.add(new EdgePair(dstSw.id(), pairDev));
204 }
205 DeviceId ret = shouldHandleRouting(dstSw.id());
206 if (ret == null) {
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900207 continue;
208 }
Saurav Das261c3002017-06-13 15:35:54 -0700209 Set<DeviceId> devsToProcess = Sets.newHashSet(dstSw.id(), ret);
210 // To do a full reroute, assume all routes have changed
211 for (DeviceId dev : devsToProcess) {
212 for (Device targetSw : srManager.deviceService.getDevices()) {
213 if (targetSw.id().equals(dev)) {
214 continue;
215 }
216 routeChanges.add(Lists.newArrayList(targetSw.id(), dev));
217 }
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900218 }
Saurav Das261c3002017-06-13 15:35:54 -0700219 }
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900220
Saurav Das261c3002017-06-13 15:35:54 -0700221 if (!redoRouting(routeChanges, edgePairs, null)) {
222 log.debug("populateAllRoutingRules: populationStatus is ABORTED");
223 populationStatus = Status.ABORTED;
224 log.warn("Failed to repopulate all routing rules.");
225 return;
sangho80f11cb2015-04-01 13:05:26 -0700226 }
227
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900228 log.debug("populateAllRoutingRules: populationStatus is SUCCEEDED");
229 populationStatus = Status.SUCCEEDED;
Saurav Das261c3002017-06-13 15:35:54 -0700230 log.info("Completed all routing rule population. Total # of rules pushed : {}",
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900231 rulePopulator.getCounter());
Saurav Das62ae6792017-05-15 15:34:25 -0700232 return;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900233 } finally {
234 statusLock.unlock();
sangho80f11cb2015-04-01 13:05:26 -0700235 }
sangho80f11cb2015-04-01 13:05:26 -0700236 }
237
sanghofb7c7292015-04-13 15:15:58 -0700238 /**
Saurav Das261c3002017-06-13 15:35:54 -0700239 * Populate rules from all other edge devices to the connect-point(s)
240 * specified for the given subnets.
241 *
242 * @param cpts connect point(s) of the subnets being added
243 * @param subnets subnets being added
Charles Chan910be6a2017-08-23 14:46:43 -0700244 */
245 // XXX refactor
Saurav Das261c3002017-06-13 15:35:54 -0700246 protected void populateSubnet(Set<ConnectPoint> cpts, Set<IpPrefix> subnets) {
Charles Chan6db55b92017-09-11 15:21:57 -0700247 if (cpts == null || cpts.size() < 1 || cpts.size() > 2) {
248 log.warn("Skipping populateSubnet due to illegal size of connect points. {}", cpts);
249 return;
250 }
251
Saurav Dasfbe74572017-08-03 18:30:35 -0700252 lastRoutingChange = DateTime.now();
Saurav Das261c3002017-06-13 15:35:54 -0700253 statusLock.lock();
254 try {
255 if (populationStatus == Status.STARTED) {
256 log.warn("Previous rule population is not finished. Cannot"
257 + " proceed with routing rules for added routes");
258 return;
259 }
260 populationStatus = Status.STARTED;
261 rulePopulator.resetCounter();
Charles Chan910be6a2017-08-23 14:46:43 -0700262 log.info("Starting to populate routing rules for added routes, subnets={}, cpts={}",
263 subnets, cpts);
Saurav Das261c3002017-06-13 15:35:54 -0700264 // Take snapshots of the topology
265 updatedEcmpSpgMap = new HashMap<>();
266 Set<EdgePair> edgePairs = new HashSet<>();
267 Set<ArrayList<DeviceId>> routeChanges = new HashSet<>();
268 boolean handleRouting = false;
269
270 if (cpts.size() == 2) {
271 // ensure connect points are edge-pairs
272 Iterator<ConnectPoint> iter = cpts.iterator();
273 DeviceId dev1 = iter.next().deviceId();
274 DeviceId pairDev = getPairDev(dev1);
275 if (iter.next().deviceId().equals(pairDev)) {
276 edgePairs.add(new EdgePair(dev1, pairDev));
277 } else {
278 log.warn("Connectpoints {} for subnets {} not on "
279 + "pair-devices.. aborting populateSubnet", cpts, subnets);
280 populationStatus = Status.ABORTED;
281 return;
282 }
283 for (ConnectPoint cp : cpts) {
284 EcmpShortestPathGraph ecmpSpgUpdated =
285 new EcmpShortestPathGraph(cp.deviceId(), srManager);
286 updatedEcmpSpgMap.put(cp.deviceId(), ecmpSpgUpdated);
287 DeviceId retId = shouldHandleRouting(cp.deviceId());
288 if (retId == null) {
289 continue;
290 }
291 handleRouting = true;
292 }
293 } else {
294 // single connect point
295 DeviceId dstSw = cpts.iterator().next().deviceId();
296 EcmpShortestPathGraph ecmpSpgUpdated =
297 new EcmpShortestPathGraph(dstSw, srManager);
298 updatedEcmpSpgMap.put(dstSw, ecmpSpgUpdated);
299 if (srManager.mastershipService.isLocalMaster(dstSw)) {
300 handleRouting = true;
301 }
302 }
303
304 if (!handleRouting) {
305 log.debug("This instance is not handling ecmp routing to the "
306 + "connectPoint(s) {}", cpts);
307 populationStatus = Status.ABORTED;
308 return;
309 }
310
311 // if it gets here, this instance should handle routing for the
312 // connectpoint(s). Assume all route-paths have to be updated to
313 // the connectpoint(s) with the following exceptions
314 // 1. if target is non-edge no need for routing rules
315 // 2. if target is one of the connectpoints
316 for (ConnectPoint cp : cpts) {
317 DeviceId dstSw = cp.deviceId();
318 for (Device targetSw : srManager.deviceService.getDevices()) {
319 boolean isEdge = false;
320 try {
321 isEdge = config.isEdgeDevice(targetSw.id());
322 } catch (DeviceConfigNotFoundException e) {
323 log.warn(e.getMessage() + "aborting populateSubnet");
324 populationStatus = Status.ABORTED;
325 return;
326 }
327 if (dstSw.equals(targetSw.id()) || !isEdge ||
328 (cpts.size() == 2 &&
329 targetSw.id().equals(getPairDev(dstSw)))) {
330 continue;
331 }
332 routeChanges.add(Lists.newArrayList(targetSw.id(), dstSw));
333 }
334 }
335
336 if (!redoRouting(routeChanges, edgePairs, subnets)) {
337 log.debug("populateSubnet: populationStatus is ABORTED");
338 populationStatus = Status.ABORTED;
339 log.warn("Failed to repopulate the rules for subnet.");
340 return;
341 }
342
343 log.debug("populateSubnet: populationStatus is SUCCEEDED");
344 populationStatus = Status.SUCCEEDED;
345 log.info("Completed subnet population. Total # of rules pushed : {}",
346 rulePopulator.getCounter());
347 return;
348
349 } finally {
350 statusLock.unlock();
351 }
352 }
353
354 /**
Saurav Das62ae6792017-05-15 15:34:25 -0700355 * Populates the routing rules or makes hash group changes according to the
356 * route-path changes due to link failure, switch failure or link up. This
357 * method should only be called for one of these three possible event-types.
358 * Note that when a switch goes away, all of its links fail as well,
359 * but this is handled as a single switch removal event.
sanghofb7c7292015-04-13 15:15:58 -0700360 *
Saurav Das62ae6792017-05-15 15:34:25 -0700361 * @param linkDown the single failed link, or null for other conditions
362 * such as link-up or a removed switch
363 * @param linkUp the single link up, or null for other conditions such as
364 * link-down or a removed switch
365 * @param switchDown the removed switch, or null for other conditions such as
366 * link-down or link-up
Saurav Das261c3002017-06-13 15:35:54 -0700367 */ // refactor
Saurav Das62ae6792017-05-15 15:34:25 -0700368 public void populateRoutingRulesForLinkStatusChange(Link linkDown,
369 Link linkUp,
370 DeviceId switchDown) {
371 if ((linkDown != null && (linkUp != null || switchDown != null)) ||
372 (linkUp != null && (linkDown != null || switchDown != null)) ||
373 (switchDown != null && (linkUp != null || linkDown != null))) {
374 log.warn("Only one event can be handled for link status change .. aborting");
375 return;
376 }
Saurav Dasfbe74572017-08-03 18:30:35 -0700377 lastRoutingChange = DateTime.now();
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700378 executorService.schedule(new UpdateMaps(), UPDATE_INTERVAL,
379 TimeUnit.SECONDS);
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900380 statusLock.lock();
381 try {
sanghofb7c7292015-04-13 15:15:58 -0700382
383 if (populationStatus == Status.STARTED) {
Saurav Das261c3002017-06-13 15:35:54 -0700384 log.warn("Previous rule population is not finished. Cannot"
385 + " proceeed with routingRules for Link Status change");
Saurav Das62ae6792017-05-15 15:34:25 -0700386 return;
sanghofb7c7292015-04-13 15:15:58 -0700387 }
388
Saurav Das261c3002017-06-13 15:35:54 -0700389 // Take snapshots of the topology
sangho28d0b6d2015-05-07 13:30:57 -0700390 updatedEcmpSpgMap = new HashMap<>();
Saurav Das261c3002017-06-13 15:35:54 -0700391 Set<EdgePair> edgePairs = new HashSet<>();
sangho28d0b6d2015-05-07 13:30:57 -0700392 for (Device sw : srManager.deviceService.getDevices()) {
Shashikanth VH0637b162015-12-11 01:32:44 +0530393 EcmpShortestPathGraph ecmpSpgUpdated =
394 new EcmpShortestPathGraph(sw.id(), srManager);
sangho28d0b6d2015-05-07 13:30:57 -0700395 updatedEcmpSpgMap.put(sw.id(), ecmpSpgUpdated);
Saurav Das261c3002017-06-13 15:35:54 -0700396 DeviceId pairDev = getPairDev(sw.id());
397 if (pairDev != null) {
398 // pairDev may not be available yet, but we still need to add
399 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev, srManager);
400 updatedEcmpSpgMap.put(pairDev, ecmpSpgUpdated);
401 edgePairs.add(new EdgePair(sw.id(), pairDev));
402 }
sangho28d0b6d2015-05-07 13:30:57 -0700403 }
404
Saurav Das261c3002017-06-13 15:35:54 -0700405 log.info("Starting to populate routing rules from link status change");
sanghodf0153f2015-05-05 14:13:34 -0700406
sanghofb7c7292015-04-13 15:15:58 -0700407 Set<ArrayList<DeviceId>> routeChanges;
Saurav Das62ae6792017-05-15 15:34:25 -0700408 log.debug("populateRoutingRulesForLinkStatusChange: "
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700409 + "populationStatus is STARTED");
sanghofb7c7292015-04-13 15:15:58 -0700410 populationStatus = Status.STARTED;
Saurav Das261c3002017-06-13 15:35:54 -0700411 rulePopulator.resetCounter();
Saurav Das1b391d52016-11-29 14:27:25 -0800412 // try optimized re-routing
Saurav Das62ae6792017-05-15 15:34:25 -0700413 if (linkDown == null) {
414 // either a linkUp or a switchDown - compute all route changes by
415 // comparing all routes of existing ECMP SPG to new ECMP SPG
sanghofb7c7292015-04-13 15:15:58 -0700416 routeChanges = computeRouteChange();
Saurav Das62ae6792017-05-15 15:34:25 -0700417
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700418 // deal with linkUp of a seen-before link
419 if (linkUp != null && srManager.isSeenLink(linkUp)) {
420 if (!srManager.isBidirectional(linkUp)) {
421 log.warn("Not a bidirectional link yet .. not "
422 + "processing link {}", linkUp);
423 srManager.updateSeenLink(linkUp, true);
424 populationStatus = Status.ABORTED;
425 return;
Saurav Das62ae6792017-05-15 15:34:25 -0700426 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700427 // link previously seen before
428 // do hash-bucket changes instead of a re-route
429 processHashGroupChange(routeChanges, false, null);
430 // clear out routesChanges so a re-route is not attempted
431 routeChanges = ImmutableSet.of();
Saurav Das62ae6792017-05-15 15:34:25 -0700432 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700433 // for a linkUp of a never-seen-before link
434 // let it fall through to a reroute of the routeChanges
Saurav Das62ae6792017-05-15 15:34:25 -0700435
436 // now that we are past the check for a previously seen link
437 // it is safe to update the store for the linkUp
438 if (linkUp != null) {
439 srManager.updateSeenLink(linkUp, true);
440 }
441
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700442 //deal with switchDown
443 if (switchDown != null) {
444 processHashGroupChange(routeChanges, true, switchDown);
445 // clear out routesChanges so a re-route is not attempted
446 routeChanges = ImmutableSet.of();
447 }
sanghofb7c7292015-04-13 15:15:58 -0700448 } else {
Saurav Das62ae6792017-05-15 15:34:25 -0700449 // link has gone down
450 // Compare existing ECMP SPG only with the link that went down
451 routeChanges = computeDamagedRoutes(linkDown);
452 if (routeChanges != null) {
453 processHashGroupChange(routeChanges, true, null);
454 // clear out routesChanges so a re-route is not attempted
455 routeChanges = ImmutableSet.of();
456 }
sanghofb7c7292015-04-13 15:15:58 -0700457 }
458
Saurav Das1b391d52016-11-29 14:27:25 -0800459 // do full re-routing if optimized routing returns null routeChanges
Saurav Dasb149be12016-06-07 10:08:06 -0700460 if (routeChanges == null) {
Saurav Das261c3002017-06-13 15:35:54 -0700461 log.info("Optimized routing failed... opting for full reroute");
462 populationStatus = Status.ABORTED;
Saurav Das62ae6792017-05-15 15:34:25 -0700463 populateAllRoutingRules();
464 return;
Saurav Dasb149be12016-06-07 10:08:06 -0700465 }
466
sanghofb7c7292015-04-13 15:15:58 -0700467 if (routeChanges.isEmpty()) {
Saurav Das62ae6792017-05-15 15:34:25 -0700468 log.info("No re-route attempted for the link status change");
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700469 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sanghofb7c7292015-04-13 15:15:58 -0700470 populationStatus = Status.SUCCEEDED;
Saurav Das62ae6792017-05-15 15:34:25 -0700471 return;
sanghofb7c7292015-04-13 15:15:58 -0700472 }
473
Saurav Das62ae6792017-05-15 15:34:25 -0700474 // reroute of routeChanges
Saurav Das261c3002017-06-13 15:35:54 -0700475 if (redoRouting(routeChanges, edgePairs, null)) {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700476 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sanghofb7c7292015-04-13 15:15:58 -0700477 populationStatus = Status.SUCCEEDED;
Saurav Das261c3002017-06-13 15:35:54 -0700478 log.info("Completed repopulation of rules for link-status change."
479 + " # of rules populated : {}", rulePopulator.getCounter());
Saurav Das62ae6792017-05-15 15:34:25 -0700480 return;
sanghofb7c7292015-04-13 15:15:58 -0700481 } else {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700482 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is ABORTED");
sanghofb7c7292015-04-13 15:15:58 -0700483 populationStatus = Status.ABORTED;
Saurav Das261c3002017-06-13 15:35:54 -0700484 log.warn("Failed to repopulate the rules for link status change.");
Saurav Das62ae6792017-05-15 15:34:25 -0700485 return;
sanghofb7c7292015-04-13 15:15:58 -0700486 }
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900487 } finally {
488 statusLock.unlock();
sanghofb7c7292015-04-13 15:15:58 -0700489 }
490 }
491
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700492
Saurav Das62ae6792017-05-15 15:34:25 -0700493 /**
Saurav Das261c3002017-06-13 15:35:54 -0700494 * Processes a set a route-path changes by reprogramming routing rules and
495 * creating new hash-groups or editing them if necessary. This method also
496 * determines the next-hops for the route-path from the src-switch (target)
497 * of the path towards the dst-switch of the path.
Saurav Das62ae6792017-05-15 15:34:25 -0700498 *
Saurav Das261c3002017-06-13 15:35:54 -0700499 * @param routeChanges a set of route-path changes, where each route-path is
500 * a list with its first element the src-switch (target)
501 * of the path, and the second element the dst-switch of
502 * the path.
503 * @param edgePairs a set of edge-switches that are paired by configuration
504 * @param subnets a set of prefixes that need to be populated in the routing
505 * table of the target switch in the route-path. Can be null,
506 * in which case all the prefixes belonging to the dst-switch
507 * will be populated in the target switch
508 * @return true if successful in repopulating all routes
Saurav Das62ae6792017-05-15 15:34:25 -0700509 */
Saurav Das261c3002017-06-13 15:35:54 -0700510 private boolean redoRouting(Set<ArrayList<DeviceId>> routeChanges,
511 Set<EdgePair> edgePairs, Set<IpPrefix> subnets) {
512 // first make every entry two-elements
513 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
514 for (ArrayList<DeviceId> route : routeChanges) {
515 if (route.size() == 1) {
516 DeviceId dstSw = route.get(0);
517 EcmpShortestPathGraph ec = updatedEcmpSpgMap.get(dstSw);
518 if (ec == null) {
519 log.warn("No graph found for {} .. aborting redoRouting", dstSw);
520 return false;
521 }
522 ec.getAllLearnedSwitchesAndVia().keySet().forEach(key -> {
523 ec.getAllLearnedSwitchesAndVia().get(key).keySet().forEach(target -> {
524 changedRoutes.add(Lists.newArrayList(target, dstSw));
525 });
526 });
527 } else {
528 DeviceId targetSw = route.get(0);
529 DeviceId dstSw = route.get(1);
530 changedRoutes.add(Lists.newArrayList(targetSw, dstSw));
531 }
532 }
533
534 // now process changedRoutes according to edgePairs
535 if (!redoRoutingEdgePairs(edgePairs, subnets, changedRoutes)) {
536 return false; //abort routing and fail fast
537 }
538
539 // whatever is left in changedRoutes is now processed for individual dsts.
540 if (!redoRoutingIndividualDests(subnets, changedRoutes)) {
541 return false; //abort routing and fail fast
542 }
543
Saurav Das261c3002017-06-13 15:35:54 -0700544 // update ecmpSPG for all edge-pairs
545 for (EdgePair ep : edgePairs) {
546 currentEcmpSpgMap.put(ep.dev1, updatedEcmpSpgMap.get(ep.dev1));
547 currentEcmpSpgMap.put(ep.dev2, updatedEcmpSpgMap.get(ep.dev2));
548 log.debug("Updating ECMPspg for edge-pair:{}-{}", ep.dev1, ep.dev2);
549 }
550 return true;
551 }
552
553 /**
554 * Programs targetSw in the changedRoutes for given prefixes reachable by
555 * an edgePair. If no prefixes are given, the method will use configured
556 * subnets/prefixes. If some configured subnets belong only to a specific
557 * destination in the edgePair, then the target switch will be programmed
558 * only to that destination.
559 *
560 * @param edgePairs set of edge-pairs for which target will be programmed
561 * @param subnets a set of prefixes that need to be populated in the routing
562 * table of the target switch in the changedRoutes. Can be null,
563 * in which case all the configured prefixes belonging to the
564 * paired switches will be populated in the target switch
565 * @param changedRoutes a set of route-path changes, where each route-path is
566 * a list with its first element the src-switch (target)
567 * of the path, and the second element the dst-switch of
568 * the path.
569 * @return true if successful
570 */
571 private boolean redoRoutingEdgePairs(Set<EdgePair> edgePairs,
572 Set<IpPrefix> subnets,
573 Set<ArrayList<DeviceId>> changedRoutes) {
574 for (EdgePair ep : edgePairs) {
575 // temp store for a target's changedRoutes to this edge-pair
576 Map<DeviceId, Set<ArrayList<DeviceId>>> targetRoutes = new HashMap<>();
577 Iterator<ArrayList<DeviceId>> i = changedRoutes.iterator();
578 while (i.hasNext()) {
579 ArrayList<DeviceId> route = i.next();
580 DeviceId dstSw = route.get(1);
581 if (ep.includes(dstSw)) {
582 // routeChange for edge pair found
583 // sort by target iff target is edge and remove from changedRoutes
584 DeviceId targetSw = route.get(0);
585 try {
586 if (!srManager.deviceConfiguration.isEdgeDevice(targetSw)) {
587 continue;
588 }
589 } catch (DeviceConfigNotFoundException e) {
590 log.warn(e.getMessage() + "aborting redoRouting");
591 return false;
592 }
593 // route is from another edge to this edge-pair
594 if (targetRoutes.containsKey(targetSw)) {
595 targetRoutes.get(targetSw).add(route);
596 } else {
597 Set<ArrayList<DeviceId>> temp = new HashSet<>();
598 temp.add(route);
599 targetRoutes.put(targetSw, temp);
600 }
601 i.remove();
602 }
603 }
604 // so now for this edgepair we have a per target set of routechanges
605 // process target->edgePair route
606 for (Map.Entry<DeviceId, Set<ArrayList<DeviceId>>> entry :
607 targetRoutes.entrySet()) {
608 log.debug("* redoRoutingDstPair Target:{} -> edge-pair {}",
609 entry.getKey(), ep);
610 DeviceId targetSw = entry.getKey();
611 Map<DeviceId, Set<DeviceId>> perDstNextHops = new HashMap<>();
612 entry.getValue().forEach(route -> {
613 Set<DeviceId> nhops = getNextHops(route.get(0), route.get(1));
614 log.debug("route: target {} -> dst {} found with next-hops {}",
615 route.get(0), route.get(1), nhops);
616 perDstNextHops.put(route.get(1), nhops);
617 });
618 Set<IpPrefix> ipDev1 = (subnets == null) ? config.getSubnets(ep.dev1)
619 : subnets;
620 Set<IpPrefix> ipDev2 = (subnets == null) ? config.getSubnets(ep.dev2)
621 : subnets;
622 ipDev1 = (ipDev1 == null) ? Sets.newHashSet() : ipDev1;
623 ipDev2 = (ipDev2 == null) ? Sets.newHashSet() : ipDev2;
624 // handle routing to subnets common to edge-pair
625 // only if the targetSw is not part of the edge-pair
626 if (!ep.includes(targetSw)) {
627 if (!populateEcmpRoutingRulePartial(
628 targetSw,
629 ep.dev1, ep.dev2,
630 perDstNextHops,
631 Sets.intersection(ipDev1, ipDev2))) {
632 return false; // abort everything and fail fast
633 }
634 }
635 // handle routing to subnets that only belong to dev1
636 Set<IpPrefix> onlyDev1Subnets = Sets.difference(ipDev1, ipDev2);
637 if (!onlyDev1Subnets.isEmpty() && perDstNextHops.get(ep.dev1) != null) {
638 Map<DeviceId, Set<DeviceId>> onlyDev1NextHops = new HashMap<>();
639 onlyDev1NextHops.put(ep.dev1, perDstNextHops.get(ep.dev1));
640 if (!populateEcmpRoutingRulePartial(
641 targetSw,
642 ep.dev1, null,
643 onlyDev1NextHops,
644 onlyDev1Subnets)) {
645 return false; // abort everything and fail fast
646 }
647 }
648 // handle routing to subnets that only belong to dev2
649 Set<IpPrefix> onlyDev2Subnets = Sets.difference(ipDev2, ipDev1);
650 if (!onlyDev2Subnets.isEmpty() && perDstNextHops.get(ep.dev2) != null) {
651 Map<DeviceId, Set<DeviceId>> onlyDev2NextHops = new HashMap<>();
652 onlyDev2NextHops.put(ep.dev2, perDstNextHops.get(ep.dev2));
653 if (!populateEcmpRoutingRulePartial(
654 targetSw,
655 ep.dev2, null,
656 onlyDev2NextHops,
657 onlyDev2Subnets)) {
658 return false; // abort everything and fail fast
659 }
660 }
661 }
662 // if it gets here it has succeeded for all targets to this edge-pair
663 }
664 return true;
665 }
666
667 /**
668 * Programs targetSw in the changedRoutes for given prefixes reachable by
669 * a destination switch that is not part of an edge-pair.
670 * If no prefixes are given, the method will use configured subnets/prefixes.
671 *
672 * @param subnets a set of prefixes that need to be populated in the routing
673 * table of the target switch in the changedRoutes. Can be null,
674 * in which case all the configured prefixes belonging to the
675 * paired switches will be populated in the target switch
676 * @param changedRoutes a set of route-path changes, where each route-path is
677 * a list with its first element the src-switch (target)
678 * of the path, and the second element the dst-switch of
679 * the path.
680 * @return true if successful
681 */
682 private boolean redoRoutingIndividualDests(Set<IpPrefix> subnets,
683 Set<ArrayList<DeviceId>> changedRoutes) {
684 // aggregate route-path changes for each dst device
685 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> routesBydevice =
686 new HashMap<>();
687 for (ArrayList<DeviceId> route: changedRoutes) {
688 DeviceId dstSw = route.get(1);
689 ArrayList<ArrayList<DeviceId>> deviceRoutes =
690 routesBydevice.get(dstSw);
691 if (deviceRoutes == null) {
692 deviceRoutes = new ArrayList<>();
693 routesBydevice.put(dstSw, deviceRoutes);
694 }
695 deviceRoutes.add(route);
696 }
697 for (DeviceId impactedDstDevice : routesBydevice.keySet()) {
698 ArrayList<ArrayList<DeviceId>> deviceRoutes =
699 routesBydevice.get(impactedDstDevice);
700 for (ArrayList<DeviceId> route: deviceRoutes) {
701 log.debug("* redoRoutingIndiDst Target: {} -> dst: {}",
702 route.get(0), route.get(1));
703 DeviceId targetSw = route.get(0);
704 DeviceId dstSw = route.get(1); // same as impactedDstDevice
705 Set<DeviceId> nextHops = getNextHops(targetSw, dstSw);
706 Map<DeviceId, Set<DeviceId>> nhops = new HashMap<>();
707 nhops.put(dstSw, nextHops);
708 if (!populateEcmpRoutingRulePartial(targetSw, dstSw, null, nhops,
709 (subnets == null) ? Sets.newHashSet() : subnets)) {
710 return false; // abort routing and fail fast
711 }
712 log.debug("Populating flow rules from target: {} to dst: {}"
713 + " is successful", targetSw, dstSw);
714 }
715 //Only if all the flows for all impacted routes to a
716 //specific target are pushed successfully, update the
717 //ECMP graph for that target. Or else the next event
718 //would not see any changes in the ECMP graphs.
719 //In another case, the target switch has gone away, so
720 //routes can't be installed. In that case, the current map
721 //is updated here, without any flows being pushed.
722 currentEcmpSpgMap.put(impactedDstDevice,
723 updatedEcmpSpgMap.get(impactedDstDevice));
724 log.debug("Updating ECMPspg for impacted dev:{}", impactedDstDevice);
725 }
726 return true;
727 }
728
729 /**
730 * Populate ECMP rules for subnets from target to destination via nexthops.
731 *
732 * @param targetSw Device ID of target switch in which rules will be programmed
733 * @param destSw1 Device ID of final destination switch to which the rules will forward
734 * @param destSw2 Device ID of paired destination switch to which the rules will forward
735 * A null deviceId indicates packets should only be sent to destSw1
736 * @param nextHops Map indication a list of next hops per destSw
737 * @param subnets Subnets to be populated. If empty, populate all configured subnets.
738 * @return true if it succeeds in populating rules
739 */ // refactor
740 private boolean populateEcmpRoutingRulePartial(DeviceId targetSw,
741 DeviceId destSw1,
742 DeviceId destSw2,
743 Map<DeviceId, Set<DeviceId>> nextHops,
744 Set<IpPrefix> subnets) {
745 boolean result;
746 // If both target switch and dest switch are edge routers, then set IP
747 // rule for both subnet and router IP.
748 boolean targetIsEdge;
749 boolean dest1IsEdge;
750 Ip4Address dest1RouterIpv4, dest2RouterIpv4 = null;
751 Ip6Address dest1RouterIpv6, dest2RouterIpv6 = null;
752
753 try {
754 targetIsEdge = config.isEdgeDevice(targetSw);
755 dest1IsEdge = config.isEdgeDevice(destSw1);
756 dest1RouterIpv4 = config.getRouterIpv4(destSw1);
757 dest1RouterIpv6 = config.getRouterIpv6(destSw1);
758 if (destSw2 != null) {
759 dest2RouterIpv4 = config.getRouterIpv4(destSw2);
760 dest2RouterIpv6 = config.getRouterIpv6(destSw2);
761 }
762 } catch (DeviceConfigNotFoundException e) {
763 log.warn(e.getMessage() + " Aborting populateEcmpRoutingRulePartial.");
Saurav Das62ae6792017-05-15 15:34:25 -0700764 return false;
765 }
Saurav Das261c3002017-06-13 15:35:54 -0700766
767 if (targetIsEdge && dest1IsEdge) {
768 subnets = (subnets != null && !subnets.isEmpty())
769 ? Sets.newHashSet(subnets)
770 : Sets.newHashSet(config.getSubnets(destSw1));
771 // XXX - Rethink this
772 /*subnets.add(dest1RouterIpv4.toIpPrefix());
773 if (dest1RouterIpv6 != null) {
774 subnets.add(dest1RouterIpv6.toIpPrefix());
775 }
776 if (destSw2 != null && dest2RouterIpv4 != null) {
777 subnets.add(dest2RouterIpv4.toIpPrefix());
778 if (dest2RouterIpv6 != null) {
779 subnets.add(dest2RouterIpv6.toIpPrefix());
780 }
781 }*/
782 log.debug(". populateEcmpRoutingRulePartial in device {} towards {} {} "
783 + "for subnets {}", targetSw, destSw1,
784 (destSw2 != null) ? ("& " + destSw2) : "",
785 subnets);
786 result = rulePopulator.populateIpRuleForSubnet(targetSw, subnets,
787 destSw1, destSw2,
788 nextHops);
789 if (!result) {
790 return false;
791 }
792 /* XXX rethink this
793 IpPrefix routerIpPrefix = destRouterIpv4.toIpPrefix();
794 log.debug("* populateEcmpRoutingRulePartial in device {} towards {} "
795 + "for router IP {}", targetSw, destSw, routerIpPrefix);
796 result = rulePopulator.populateIpRuleForRouter(targetSw, routerIpPrefix,
797 destSw, nextHops);
798 if (!result) {
799 return false;
800 }
801 // If present we deal with IPv6 loopback.
802 if (destRouterIpv6 != null) {
803 routerIpPrefix = destRouterIpv6.toIpPrefix();
804 log.debug("* populateEcmpRoutingRulePartial in device {} towards {}"
805 + " for v6 router IP {}", targetSw, destSw, routerIpPrefix);
806 result = rulePopulator.populateIpRuleForRouter(targetSw, routerIpPrefix,
807 destSw, nextHops);
808 if (!result) {
809 return false;
810 }
811 }*/
Saurav Das62ae6792017-05-15 15:34:25 -0700812 }
Saurav Das261c3002017-06-13 15:35:54 -0700813
814 if (!targetIsEdge && dest1IsEdge) {
815 // MPLS rules in all non-edge target devices. These rules are for
816 // individual destinations, even if the dsts are part of edge-pairs.
817 log.debug(". populateEcmpRoutingRulePartial in device{} towards {} for "
818 + "all MPLS rules", targetSw, destSw1);
819 result = rulePopulator.populateMplsRule(targetSw, destSw1,
820 nextHops.get(destSw1),
821 dest1RouterIpv4);
822 if (!result) {
823 return false;
824 }
825 if (dest1RouterIpv6 != null) {
826 result = rulePopulator.populateMplsRule(targetSw, destSw1,
827 nextHops.get(destSw1),
828 dest1RouterIpv6);
829 if (!result) {
830 return false;
831 }
832 }
833 }
834
835 // To save on ECMP groups
836 // avoid MPLS rules in non-edge-devices to non-edge-devices
837 // avoid MPLS transit rules in edge-devices
838 // avoid loopback IP rules in edge-devices to non-edge-devices
839 return true;
Saurav Das62ae6792017-05-15 15:34:25 -0700840 }
841
842 /**
843 * Processes a set a route-path changes by editing hash groups.
844 *
845 * @param routeChanges a set of route-path changes, where each route-path is
846 * a list with its first element the src-switch of the path
847 * and the second element the dst-switch of the path.
848 * @param linkOrSwitchFailed true if the route changes are for a failed
849 * switch or linkDown event
850 * @param failedSwitch the switchId if the route changes are for a failed switch,
851 * otherwise null
852 */
853 private void processHashGroupChange(Set<ArrayList<DeviceId>> routeChanges,
854 boolean linkOrSwitchFailed,
855 DeviceId failedSwitch) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700856 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
857 // first, ensure each routeChanges entry has two elements
Saurav Das62ae6792017-05-15 15:34:25 -0700858 for (ArrayList<DeviceId> route : routeChanges) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700859 if (route.size() == 1) {
860 // route-path changes are from everyone else to this switch
861 DeviceId dstSw = route.get(0);
862 srManager.deviceService.getAvailableDevices().forEach(sw -> {
863 if (!sw.id().equals(dstSw)) {
864 changedRoutes.add(Lists.newArrayList(sw.id(), dstSw));
865 }
866 });
867 } else {
868 changedRoutes.add(route);
Saurav Das62ae6792017-05-15 15:34:25 -0700869 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700870 }
Saurav Das62ae6792017-05-15 15:34:25 -0700871
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700872 for (ArrayList<DeviceId> route : changedRoutes) {
873 DeviceId targetSw = route.get(0);
874 DeviceId dstSw = route.get(1);
Saurav Das62ae6792017-05-15 15:34:25 -0700875 if (linkOrSwitchFailed) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700876 boolean success = fixHashGroupsForRoute(route, true);
Saurav Das62ae6792017-05-15 15:34:25 -0700877 // it's possible that we cannot fix hash groups for a route
878 // if the target switch has failed. Nevertheless the ecmp graph
879 // for the impacted switch must still be updated.
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700880 if (!success && failedSwitch != null && targetSw.equals(failedSwitch)) {
Saurav Das62ae6792017-05-15 15:34:25 -0700881 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
882 currentEcmpSpgMap.remove(targetSw);
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700883 log.debug("Updating ECMPspg for dst:{} removing failed switch "
Saurav Das62ae6792017-05-15 15:34:25 -0700884 + "target:{}", dstSw, targetSw);
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700885 continue;
Saurav Das62ae6792017-05-15 15:34:25 -0700886 }
887 //linkfailed - update both sides
Saurav Das62ae6792017-05-15 15:34:25 -0700888 if (success) {
889 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700890 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
891 log.debug("Updating ECMPspg for dst:{} and target:{} for linkdown",
892 dstSw, targetSw);
893 }
894 } else {
895 //linkup of seen before link
896 boolean success = fixHashGroupsForRoute(route, false);
897 if (success) {
898 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
899 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
900 log.debug("Updating ECMPspg for target:{} and dst:{} for linkup",
Saurav Das62ae6792017-05-15 15:34:25 -0700901 targetSw, dstSw);
902 }
903 }
904 }
905 }
906
907 /**
908 * Edits hash groups in the src-switch (targetSw) of a route-path by
909 * calling the groupHandler to either add or remove buckets in an existing
910 * hash group.
911 *
912 * @param route a single list representing a route-path where the first element
913 * is the src-switch (targetSw) of the route-path and the
914 * second element is the dst-switch
915 * @param revoke true if buckets in the hash-groups need to be removed;
916 * false if buckets in the hash-groups need to be added
917 * @return true if the hash group editing is successful
918 */
919 private boolean fixHashGroupsForRoute(ArrayList<DeviceId> route,
920 boolean revoke) {
921 DeviceId targetSw = route.get(0);
922 if (route.size() < 2) {
923 log.warn("Cannot fixHashGroupsForRoute - no dstSw in route {}", route);
924 return false;
925 }
926 DeviceId destSw = route.get(1);
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700927 log.debug("* processing fixHashGroupsForRoute: Target {} -> Dest {}",
Saurav Das62ae6792017-05-15 15:34:25 -0700928 targetSw, destSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700929 // figure out the new next hops at the targetSw towards the destSw
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700930 Set<DeviceId> nextHops = getNextHops(targetSw, destSw);
Saurav Das62ae6792017-05-15 15:34:25 -0700931 // call group handler to change hash group at targetSw
932 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
933 if (grpHandler == null) {
934 log.warn("Cannot find grouphandler for dev:{} .. aborting"
935 + " {} hash group buckets for route:{} ", targetSw,
936 (revoke) ? "revoke" : "repopulate", route);
937 return false;
938 }
939 log.debug("{} hash-groups buckets For Route {} -> {} to next-hops {}",
940 (revoke) ? "revoke" : "repopulating",
941 targetSw, destSw, nextHops);
942 return (revoke) ? grpHandler.fixHashGroups(targetSw, nextHops,
943 destSw, true)
944 : grpHandler.fixHashGroups(targetSw, nextHops,
945 destSw, false);
946 }
947
948 /**
Saurav Das261c3002017-06-13 15:35:54 -0700949 * Start the flow rule population process if it was never started. The
950 * process finishes successfully when all flow rules are set and stops with
951 * ABORTED status when any groups required for flows is not set yet.
Saurav Das62ae6792017-05-15 15:34:25 -0700952 */
Saurav Das261c3002017-06-13 15:35:54 -0700953 public void startPopulationProcess() {
954 statusLock.lock();
955 try {
956 if (populationStatus == Status.IDLE
957 || populationStatus == Status.SUCCEEDED
958 || populationStatus == Status.ABORTED) {
959 populateAllRoutingRules();
sangho28d0b6d2015-05-07 13:30:57 -0700960 } else {
Saurav Das261c3002017-06-13 15:35:54 -0700961 log.warn("Not initiating startPopulationProcess as populationStatus is {}",
962 populationStatus);
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -0700963 }
Saurav Das261c3002017-06-13 15:35:54 -0700964 } finally {
965 statusLock.unlock();
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -0700966 }
sanghofb7c7292015-04-13 15:15:58 -0700967 }
968
Saurav Dasb149be12016-06-07 10:08:06 -0700969 /**
Saurav Das261c3002017-06-13 15:35:54 -0700970 * Revoke rules of given subnet in all edge switches.
971 *
972 * @param subnets subnet being removed
973 * @return true if succeed
974 */
975 protected boolean revokeSubnet(Set<IpPrefix> subnets) {
976 statusLock.lock();
977 try {
978 return srManager.routingRulePopulator.revokeIpRuleForSubnet(subnets);
979 } finally {
980 statusLock.unlock();
981 }
982 }
983
984 /**
Charles Chan910be6a2017-08-23 14:46:43 -0700985 * Populates IP rules for a route that has direct connection to the switch
986 * if the current instance is the master of the switch.
987 *
988 * @param deviceId device ID of the device that next hop attaches to
989 * @param prefix IP prefix of the route
990 * @param hostMac MAC address of the next hop
991 * @param hostVlanId Vlan ID of the nexthop
992 * @param outPort port where the next hop attaches to
993 */
994 void populateRoute(DeviceId deviceId, IpPrefix prefix,
995 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
996 if (srManager.mastershipService.isLocalMaster(deviceId)) {
997 srManager.routingRulePopulator.populateRoute(deviceId, prefix, hostMac, hostVlanId, outPort);
998 }
999 }
1000
1001 /**
1002 * Removes IP rules for a route when the next hop is gone.
1003 * if the current instance is the master of the switch.
1004 *
1005 * @param deviceId device ID of the device that next hop attaches to
1006 * @param prefix IP prefix of the route
1007 * @param hostMac MAC address of the next hop
1008 * @param hostVlanId Vlan ID of the nexthop
1009 * @param outPort port that next hop attaches to
1010 */
1011 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
1012 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
1013 if (srManager.mastershipService.isLocalMaster(deviceId)) {
1014 srManager.routingRulePopulator.revokeRoute(deviceId, prefix, hostMac, hostVlanId, outPort);
1015 }
1016 }
1017
1018 /**
Saurav Das261c3002017-06-13 15:35:54 -07001019 * Remove ECMP graph entry for the given device. Typically called when
1020 * device is no longer available.
1021 *
1022 * @param deviceId the device for which graphs need to be purged
1023 */
1024 protected void purgeEcmpGraph(DeviceId deviceId) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001025 currentEcmpSpgMap.remove(deviceId); // XXX reconsider
Saurav Das261c3002017-06-13 15:35:54 -07001026 if (updatedEcmpSpgMap != null) {
1027 updatedEcmpSpgMap.remove(deviceId);
1028 }
1029 }
1030
1031 //////////////////////////////////////
1032 // Routing helper methods and classes
1033 //////////////////////////////////////
1034
1035 /**
Saurav Das1b391d52016-11-29 14:27:25 -08001036 * Computes set of affected routes due to failed link. Assumes
Saurav Dasb149be12016-06-07 10:08:06 -07001037 * previous ecmp shortest-path graph exists for a switch in order to compute
1038 * affected routes. If such a graph does not exist, the method returns null.
1039 *
1040 * @param linkFail the failed link
1041 * @return the set of affected routes which may be empty if no routes were
1042 * affected, or null if no previous ecmp spg was found for comparison
1043 */
sanghofb7c7292015-04-13 15:15:58 -07001044 private Set<ArrayList<DeviceId>> computeDamagedRoutes(Link linkFail) {
sanghofb7c7292015-04-13 15:15:58 -07001045 Set<ArrayList<DeviceId>> routes = new HashSet<>();
1046
1047 for (Device sw : srManager.deviceService.getDevices()) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001048 log.debug("Computing the impacted routes for device {} due to link fail",
1049 sw.id());
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001050 DeviceId retId = shouldHandleRouting(sw.id());
1051 if (retId == null) {
sanghofb7c7292015-04-13 15:15:58 -07001052 continue;
1053 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001054 Set<DeviceId> devicesToProcess = Sets.newHashSet(retId, sw.id());
1055 for (DeviceId rootSw : devicesToProcess) {
1056 EcmpShortestPathGraph ecmpSpg = currentEcmpSpgMap.get(rootSw);
1057 if (ecmpSpg == null) {
1058 log.warn("No existing ECMP graph for switch {}. Aborting optimized"
1059 + " rerouting and opting for full-reroute", rootSw);
1060 return null;
1061 }
1062 if (log.isDebugEnabled()) {
1063 log.debug("Root switch: {}", rootSw);
1064 log.debug(" Current/Existing SPG: {}", ecmpSpg);
1065 log.debug(" New/Updated SPG: {}", updatedEcmpSpgMap.get(rootSw));
1066 }
1067 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>>
1068 switchVia = ecmpSpg.getAllLearnedSwitchesAndVia();
1069 // figure out if the broken link affected any route-paths in this graph
1070 for (Integer itrIdx : switchVia.keySet()) {
1071 log.trace("Current/Exiting SPG Iterindex# {}", itrIdx);
1072 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1073 switchVia.get(itrIdx);
1074 for (DeviceId targetSw : swViaMap.keySet()) {
1075 log.trace("TargetSwitch {} --> RootSwitch {}",
1076 targetSw, rootSw);
Saurav Dasb149be12016-06-07 10:08:06 -07001077 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1078 log.trace(" Via:");
Pier Ventreadb4ae62016-11-23 09:57:42 -08001079 via.forEach(e -> log.trace(" {}", e));
Saurav Dasb149be12016-06-07 10:08:06 -07001080 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001081 Set<ArrayList<DeviceId>> subLinks =
1082 computeLinks(targetSw, rootSw, swViaMap);
1083 for (ArrayList<DeviceId> alink: subLinks) {
1084 if ((alink.get(0).equals(linkFail.src().deviceId()) &&
1085 alink.get(1).equals(linkFail.dst().deviceId()))
1086 ||
1087 (alink.get(0).equals(linkFail.dst().deviceId()) &&
1088 alink.get(1).equals(linkFail.src().deviceId()))) {
1089 log.debug("Impacted route:{}->{}", targetSw, rootSw);
1090 ArrayList<DeviceId> aRoute = new ArrayList<>();
1091 aRoute.add(targetSw); // switch with rules to populate
1092 aRoute.add(rootSw); // towards this destination
1093 routes.add(aRoute);
1094 break;
1095 }
sanghofb7c7292015-04-13 15:15:58 -07001096 }
1097 }
1098 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001099
sanghofb7c7292015-04-13 15:15:58 -07001100 }
sangho28d0b6d2015-05-07 13:30:57 -07001101
sanghofb7c7292015-04-13 15:15:58 -07001102 }
sanghofb7c7292015-04-13 15:15:58 -07001103 return routes;
1104 }
1105
Saurav Das1b391d52016-11-29 14:27:25 -08001106 /**
1107 * Computes set of affected routes due to new links or failed switches.
1108 *
1109 * @return the set of affected routes which may be empty if no routes were
1110 * affected
1111 */
sanghofb7c7292015-04-13 15:15:58 -07001112 private Set<ArrayList<DeviceId>> computeRouteChange() {
Saurav Das261c3002017-06-13 15:35:54 -07001113 ImmutableSet.Builder<ArrayList<DeviceId>> changedRtBldr =
Saurav Das1b391d52016-11-29 14:27:25 -08001114 ImmutableSet.builder();
sanghofb7c7292015-04-13 15:15:58 -07001115
1116 for (Device sw : srManager.deviceService.getDevices()) {
Saurav Das261c3002017-06-13 15:35:54 -07001117 log.debug("Computing the impacted routes for device {}", sw.id());
1118 DeviceId retId = shouldHandleRouting(sw.id());
1119 if (retId == null) {
sanghofb7c7292015-04-13 15:15:58 -07001120 continue;
1121 }
Saurav Das261c3002017-06-13 15:35:54 -07001122 Set<DeviceId> devicesToProcess = Sets.newHashSet(retId, sw.id());
1123 for (DeviceId rootSw : devicesToProcess) {
1124 if (log.isTraceEnabled()) {
1125 log.trace("Device links for dev: {}", rootSw);
1126 for (Link link: srManager.linkService.getDeviceLinks(rootSw)) {
1127 log.trace("{} -> {} ", link.src().deviceId(),
1128 link.dst().deviceId());
1129 }
Saurav Dasb149be12016-06-07 10:08:06 -07001130 }
Saurav Das261c3002017-06-13 15:35:54 -07001131 EcmpShortestPathGraph currEcmpSpg = currentEcmpSpgMap.get(rootSw);
1132 if (currEcmpSpg == null) {
1133 log.debug("No existing ECMP graph for device {}.. adding self as "
1134 + "changed route", rootSw);
1135 changedRtBldr.add(Lists.newArrayList(rootSw));
1136 continue;
1137 }
1138 EcmpShortestPathGraph newEcmpSpg = updatedEcmpSpgMap.get(rootSw);
1139 if (log.isDebugEnabled()) {
1140 log.debug("Root switch: {}", rootSw);
1141 log.debug(" Current/Existing SPG: {}", currEcmpSpg);
1142 log.debug(" New/Updated SPG: {}", newEcmpSpg);
1143 }
1144 // first use the updated/new map to compare to current/existing map
1145 // as new links may have come up
1146 changedRtBldr.addAll(compareGraphs(newEcmpSpg, currEcmpSpg, rootSw));
1147 // then use the current/existing map to compare to updated/new map
1148 // as switch may have been removed
1149 changedRtBldr.addAll(compareGraphs(currEcmpSpg, newEcmpSpg, rootSw));
sangho28d0b6d2015-05-07 13:30:57 -07001150 }
Saurav Das1b391d52016-11-29 14:27:25 -08001151 }
sanghofb7c7292015-04-13 15:15:58 -07001152
Saurav Das261c3002017-06-13 15:35:54 -07001153 Set<ArrayList<DeviceId>> changedRoutes = changedRtBldr.build();
Saurav Das1b391d52016-11-29 14:27:25 -08001154 for (ArrayList<DeviceId> route: changedRoutes) {
1155 log.debug("Route changes Target -> Root");
1156 if (route.size() == 1) {
1157 log.debug(" : all -> {}", route.get(0));
1158 } else {
1159 log.debug(" : {} -> {}", route.get(0), route.get(1));
1160 }
1161 }
1162 return changedRoutes;
1163 }
1164
1165 /**
1166 * For the root switch, searches all the target nodes reachable in the base
1167 * graph, and compares paths to the ones in the comp graph.
1168 *
1169 * @param base the graph that is indexed for all reachable target nodes
1170 * from the root node
1171 * @param comp the graph that the base graph is compared to
1172 * @param rootSw both ecmp graphs are calculated for the root node
1173 * @return all the routes that have changed in the base graph
1174 */
1175 private Set<ArrayList<DeviceId>> compareGraphs(EcmpShortestPathGraph base,
1176 EcmpShortestPathGraph comp,
1177 DeviceId rootSw) {
1178 ImmutableSet.Builder<ArrayList<DeviceId>> changedRoutesBuilder =
1179 ImmutableSet.builder();
1180 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> baseMap =
1181 base.getAllLearnedSwitchesAndVia();
1182 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> compMap =
1183 comp.getAllLearnedSwitchesAndVia();
1184 for (Integer itrIdx : baseMap.keySet()) {
1185 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> baseViaMap =
1186 baseMap.get(itrIdx);
1187 for (DeviceId targetSw : baseViaMap.keySet()) {
1188 ArrayList<ArrayList<DeviceId>> basePath = baseViaMap.get(targetSw);
1189 ArrayList<ArrayList<DeviceId>> compPath = getVia(compMap, targetSw);
1190 if ((compPath == null) || !basePath.equals(compPath)) {
Saurav Das62ae6792017-05-15 15:34:25 -07001191 log.trace("Impacted route:{} -> {}", targetSw, rootSw);
Saurav Das1b391d52016-11-29 14:27:25 -08001192 ArrayList<DeviceId> route = new ArrayList<>();
Saurav Das261c3002017-06-13 15:35:54 -07001193 route.add(targetSw); // switch with rules to populate
1194 route.add(rootSw); // towards this destination
Saurav Das1b391d52016-11-29 14:27:25 -08001195 changedRoutesBuilder.add(route);
sanghofb7c7292015-04-13 15:15:58 -07001196 }
1197 }
sangho28d0b6d2015-05-07 13:30:57 -07001198 }
Saurav Das1b391d52016-11-29 14:27:25 -08001199 return changedRoutesBuilder.build();
sanghofb7c7292015-04-13 15:15:58 -07001200 }
1201
Saurav Das261c3002017-06-13 15:35:54 -07001202 /**
1203 * Returns the ECMP paths traversed to reach the target switch.
1204 *
1205 * @param switchVia a per-iteration view of the ECMP graph for a root switch
1206 * @param targetSw the switch to reach from the root switch
1207 * @return the nodes traversed on ECMP paths to the target switch
1208 */
sanghofb7c7292015-04-13 15:15:58 -07001209 private ArrayList<ArrayList<DeviceId>> getVia(HashMap<Integer, HashMap<DeviceId,
Saurav Das1b391d52016-11-29 14:27:25 -08001210 ArrayList<ArrayList<DeviceId>>>> switchVia, DeviceId targetSw) {
sanghofb7c7292015-04-13 15:15:58 -07001211 for (Integer itrIdx : switchVia.keySet()) {
1212 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1213 switchVia.get(itrIdx);
Saurav Das1b391d52016-11-29 14:27:25 -08001214 if (swViaMap.get(targetSw) == null) {
sanghofb7c7292015-04-13 15:15:58 -07001215 continue;
1216 } else {
Saurav Das1b391d52016-11-29 14:27:25 -08001217 return swViaMap.get(targetSw);
sanghofb7c7292015-04-13 15:15:58 -07001218 }
1219 }
1220
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001221 return null;
sanghofb7c7292015-04-13 15:15:58 -07001222 }
1223
Saurav Das261c3002017-06-13 15:35:54 -07001224 /**
1225 * Utility method to break down a path from src to dst device into a collection
1226 * of links.
1227 *
1228 * @param src src device of the path
1229 * @param dst dst device of the path
1230 * @param viaMap path taken from src to dst device
1231 * @return collection of links in the path
1232 */
sanghofb7c7292015-04-13 15:15:58 -07001233 private Set<ArrayList<DeviceId>> computeLinks(DeviceId src,
1234 DeviceId dst,
1235 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> viaMap) {
1236 Set<ArrayList<DeviceId>> subLinks = Sets.newHashSet();
1237 for (ArrayList<DeviceId> via : viaMap.get(src)) {
1238 DeviceId linkSrc = src;
1239 DeviceId linkDst = dst;
1240 for (DeviceId viaDevice: via) {
1241 ArrayList<DeviceId> link = new ArrayList<>();
1242 linkDst = viaDevice;
1243 link.add(linkSrc);
1244 link.add(linkDst);
1245 subLinks.add(link);
1246 linkSrc = viaDevice;
1247 }
1248 ArrayList<DeviceId> link = new ArrayList<>();
1249 link.add(linkSrc);
1250 link.add(dst);
1251 subLinks.add(link);
1252 }
1253
1254 return subLinks;
1255 }
1256
Charles Chanc22cef32016-04-29 14:38:22 -07001257 /**
Saurav Das261c3002017-06-13 15:35:54 -07001258 * Determines whether this controller instance should handle routing for the
1259 * given {@code deviceId}, based on mastership and pairDeviceId if one exists.
1260 * Returns null if this instance should not handle routing for given {@code deviceId}.
1261 * Otherwise the returned value could be the given deviceId itself, or the
1262 * deviceId for the paired edge device. In the latter case, this instance
1263 * should handle routing for both the given device and the paired device.
Charles Chanc22cef32016-04-29 14:38:22 -07001264 *
Saurav Das261c3002017-06-13 15:35:54 -07001265 * @param deviceId device identifier to consider for routing
1266 * @return null or deviceId which could be the same as the given deviceId
1267 * or the deviceId of a paired edge device
Charles Chanc22cef32016-04-29 14:38:22 -07001268 */
Saurav Das261c3002017-06-13 15:35:54 -07001269 private DeviceId shouldHandleRouting(DeviceId deviceId) {
1270 if (!srManager.mastershipService.isLocalMaster(deviceId)) {
1271 log.debug("Not master for dev:{} .. skipping routing, may get handled "
1272 + "elsewhere as part of paired devices", deviceId);
1273 return null;
1274 }
1275 NodeId myNode = srManager.mastershipService.getMasterFor(deviceId);
1276 DeviceId pairDev = getPairDev(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001277
Saurav Das261c3002017-06-13 15:35:54 -07001278 if (pairDev != null) {
1279 if (!srManager.deviceService.isAvailable(pairDev)) {
1280 log.warn("pairedDev {} not available .. routing this dev:{} "
1281 + "without mastership check",
1282 pairDev, deviceId);
1283 return pairDev; // handle both temporarily
1284 }
1285 NodeId pairMasterNode = srManager.mastershipService.getMasterFor(pairDev);
1286 if (myNode.compareTo(pairMasterNode) <= 0) {
1287 log.debug("Handling routing for both dev:{} pair-dev:{}; myNode: {}"
1288 + " pairMaster:{} compare:{}", deviceId, pairDev,
1289 myNode, pairMasterNode,
1290 myNode.compareTo(pairMasterNode));
1291 return pairDev; // handle both
1292 } else {
1293 log.debug("PairDev node: {} should handle routing for dev:{} and "
1294 + "pair-dev:{}", pairMasterNode, deviceId, pairDev);
1295 return null; // handle neither
sangho80f11cb2015-04-01 13:05:26 -07001296 }
1297 }
Saurav Das261c3002017-06-13 15:35:54 -07001298 return deviceId; // not paired, just handle given device
sangho80f11cb2015-04-01 13:05:26 -07001299 }
1300
Charles Chanc22cef32016-04-29 14:38:22 -07001301 /**
Saurav Das261c3002017-06-13 15:35:54 -07001302 * Returns the configured paired DeviceId for the given Device, or null
1303 * if no such paired device has been configured.
Charles Chanc22cef32016-04-29 14:38:22 -07001304 *
Saurav Das261c3002017-06-13 15:35:54 -07001305 * @param deviceId
1306 * @return configured pair deviceId or null
Charles Chanc22cef32016-04-29 14:38:22 -07001307 */
Saurav Das261c3002017-06-13 15:35:54 -07001308 private DeviceId getPairDev(DeviceId deviceId) {
1309 DeviceId pairDev;
Charles Chan319d1a22015-11-03 10:42:14 -08001310 try {
Saurav Das261c3002017-06-13 15:35:54 -07001311 pairDev = srManager.deviceConfiguration.getPairDeviceId(deviceId);
Charles Chan319d1a22015-11-03 10:42:14 -08001312 } catch (DeviceConfigNotFoundException e) {
Saurav Das261c3002017-06-13 15:35:54 -07001313 log.warn(e.getMessage() + " .. cannot continue routing for dev: {}");
1314 return null;
Charles Chan319d1a22015-11-03 10:42:14 -08001315 }
Saurav Das261c3002017-06-13 15:35:54 -07001316 return pairDev;
sangho80f11cb2015-04-01 13:05:26 -07001317 }
1318
1319 /**
Saurav Das261c3002017-06-13 15:35:54 -07001320 * Returns the set of deviceIds which are the next hops from the targetSw
1321 * to the dstSw according to the latest ECMP spg.
1322 *
1323 * @param targetSw the switch for which the next-hops are desired
1324 * @param dstSw the switch to which the next-hops lead to from the targetSw
1325 * @return set of next hop deviceIds, could be empty if no next hops are found
1326 */
1327 private Set<DeviceId> getNextHops(DeviceId targetSw, DeviceId dstSw) {
1328 boolean targetIsEdge = false;
1329 try {
1330 targetIsEdge = srManager.deviceConfiguration.isEdgeDevice(targetSw);
1331 } catch (DeviceConfigNotFoundException e) {
1332 log.warn(e.getMessage() + "Cannot determine if targetIsEdge {}.. "
1333 + "continuing to getNextHops", targetSw);
1334 }
1335
1336 EcmpShortestPathGraph ecmpSpg = updatedEcmpSpgMap.get(dstSw);
1337 if (ecmpSpg == null) {
1338 log.debug("No ecmpSpg found for dstSw: {}", dstSw);
1339 return ImmutableSet.of();
1340 }
1341 HashMap<Integer,
1342 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> switchVia =
1343 ecmpSpg.getAllLearnedSwitchesAndVia();
1344 for (Integer itrIdx : switchVia.keySet()) {
1345 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1346 switchVia.get(itrIdx);
1347 for (DeviceId target : swViaMap.keySet()) {
1348 if (!target.equals(targetSw)) {
1349 continue;
1350 }
1351 if (!targetIsEdge && itrIdx > 1) {
1352 // optimization for spines to not use other leaves to get
1353 // to a leaf to avoid loops
1354 log.debug("Avoiding {} hop path for non-edge targetSw:{}"
1355 + " --> dstSw:{}", itrIdx, targetSw, dstSw);
1356 break;
1357 }
1358 Set<DeviceId> nextHops = new HashSet<>();
1359 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1360 if (via.isEmpty()) {
1361 // the dstSw is the next-hop from the targetSw
1362 nextHops.add(dstSw);
1363 } else {
1364 // first elem is next-hop in each ECMP path
1365 nextHops.add(via.get(0));
1366 }
1367 }
1368 return nextHops;
1369 }
1370 }
1371 return ImmutableSet.of(); //no next-hops found
1372 }
1373
1374 /**
1375 * Represents two devices that are paired by configuration. An EdgePair for
1376 * (dev1, dev2) is the same as as EdgePair for (dev2, dev1)
1377 */
1378 protected final class EdgePair {
1379 DeviceId dev1;
1380 DeviceId dev2;
1381
1382 EdgePair(DeviceId dev1, DeviceId dev2) {
1383 this.dev1 = dev1;
1384 this.dev2 = dev2;
1385 }
1386
1387 boolean includes(DeviceId dev) {
1388 return dev1.equals(dev) || dev2.equals(dev);
1389 }
1390
1391 @Override
1392 public boolean equals(Object o) {
1393 if (this == o) {
1394 return true;
1395 }
1396 if (!(o instanceof EdgePair)) {
1397 return false;
1398 }
1399 EdgePair that = (EdgePair) o;
1400 return ((this.dev1.equals(that.dev1) && this.dev2.equals(that.dev2)) ||
1401 (this.dev1.equals(that.dev2) && this.dev2.equals(that.dev1)));
1402 }
1403
1404 @Override
1405 public int hashCode() {
1406 if (dev1.toString().compareTo(dev2.toString()) <= 0) {
1407 return Objects.hash(dev1, dev2);
1408 } else {
1409 return Objects.hash(dev2, dev1);
1410 }
1411 }
1412
1413 @Override
1414 public String toString() {
1415 return toStringHelper(this)
1416 .add("Dev1", dev1)
1417 .add("Dev2", dev2)
1418 .toString();
1419 }
1420 }
1421
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001422 /**
1423 * Updates the currentEcmpSpgGraph for all devices.
1424 */
1425 private void updateEcmpSpgMaps() {
1426 for (Device sw : srManager.deviceService.getDevices()) {
1427 EcmpShortestPathGraph ecmpSpgUpdated =
1428 new EcmpShortestPathGraph(sw.id(), srManager);
1429 currentEcmpSpgMap.put(sw.id(), ecmpSpgUpdated);
1430 }
1431 }
1432
1433 /**
1434 * Ensures routing is stable before updating all ECMP SPG graphs.
1435 *
1436 * TODO: CORD-1843 will ensure maps are updated faster, potentially while
1437 * topology/routing is still unstable
1438 */
1439 private final class UpdateMaps implements Runnable {
1440 @Override
1441 public void run() {
1442 if (isRoutingStable()) {
1443 updateEcmpSpgMaps();
1444 } else {
1445 executorService.schedule(new UpdateMaps(), UPDATE_INTERVAL,
1446 TimeUnit.SECONDS);
1447 }
1448 }
1449 }
1450
Saurav Das261c3002017-06-13 15:35:54 -07001451 //////////////////////////////////////
1452 // Filtering rule creation
1453 //////////////////////////////////////
1454
1455 /**
Saurav Dasf9332192017-02-18 14:05:44 -08001456 * Populates filtering rules for port, and punting rules
1457 * for gateway IPs, loopback IPs and arp/ndp traffic.
1458 * Should only be called by the master instance for this device/port.
sangho80f11cb2015-04-01 13:05:26 -07001459 *
1460 * @param deviceId Switch ID to set the rules
1461 */
Saurav Das9f1c42e2015-10-23 10:51:11 -07001462 public void populatePortAddressingRules(DeviceId deviceId) {
Saurav Das07c74602016-04-27 18:35:50 -07001463 // Although device is added, sometimes device store does not have the
1464 // ports for this device yet. It results in missing filtering rules in the
1465 // switch. We will attempt it a few times. If it still does not work,
1466 // user can manually repopulate using CLI command sr-reroute-network
Charles Chan18fa4252017-02-08 16:10:40 -08001467 PortFilterInfo firstRun = rulePopulator.populateVlanMacFilters(deviceId);
Saurav Dasd1872b02016-12-02 15:43:47 -08001468 if (firstRun == null) {
1469 firstRun = new PortFilterInfo(0, 0, 0);
Saurav Das07c74602016-04-27 18:35:50 -07001470 }
Saurav Dasd1872b02016-12-02 15:43:47 -08001471 executorService.schedule(new RetryFilters(deviceId, firstRun),
1472 RETRY_INTERVAL_MS, TimeUnit.MILLISECONDS);
sangho80f11cb2015-04-01 13:05:26 -07001473 }
1474
1475 /**
Saurav Dasd1872b02016-12-02 15:43:47 -08001476 * Utility class used to temporarily store information about the ports on a
1477 * device processed for filtering objectives.
Saurav Dasd1872b02016-12-02 15:43:47 -08001478 */
1479 public final class PortFilterInfo {
Saurav Dasf9332192017-02-18 14:05:44 -08001480 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das07c74602016-04-27 18:35:50 -07001481
Saurav Dasf9332192017-02-18 14:05:44 -08001482 public PortFilterInfo(int disabledPorts, int errorPorts,
Saurav Dasd1872b02016-12-02 15:43:47 -08001483 int filteredPorts) {
1484 this.disabledPorts = disabledPorts;
1485 this.filteredPorts = filteredPorts;
Saurav Dasf9332192017-02-18 14:05:44 -08001486 this.errorPorts = errorPorts;
Saurav Dasd1872b02016-12-02 15:43:47 -08001487 }
1488
1489 @Override
1490 public int hashCode() {
Saurav Dasf9332192017-02-18 14:05:44 -08001491 return Objects.hash(disabledPorts, filteredPorts, errorPorts);
Saurav Dasd1872b02016-12-02 15:43:47 -08001492 }
1493
1494 @Override
1495 public boolean equals(Object obj) {
1496 if (this == obj) {
1497 return true;
1498 }
1499 if ((obj == null) || (!(obj instanceof PortFilterInfo))) {
1500 return false;
1501 }
1502 PortFilterInfo other = (PortFilterInfo) obj;
1503 return ((disabledPorts == other.disabledPorts) &&
1504 (filteredPorts == other.filteredPorts) &&
Saurav Dasf9332192017-02-18 14:05:44 -08001505 (errorPorts == other.errorPorts));
Saurav Dasd1872b02016-12-02 15:43:47 -08001506 }
1507
1508 @Override
1509 public String toString() {
1510 MoreObjects.ToStringHelper helper = toStringHelper(this)
1511 .add("disabledPorts", disabledPorts)
Saurav Dasf9332192017-02-18 14:05:44 -08001512 .add("errorPorts", errorPorts)
Saurav Dasd1872b02016-12-02 15:43:47 -08001513 .add("filteredPorts", filteredPorts);
1514 return helper.toString();
1515 }
1516 }
1517
1518 /**
1519 * RetryFilters populates filtering objectives for a device and keeps retrying
1520 * till the number of ports filtered are constant for a predefined number
1521 * of attempts.
1522 */
1523 protected final class RetryFilters implements Runnable {
1524 int constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS;
1525 DeviceId devId;
1526 int counter;
1527 PortFilterInfo prevRun;
1528
1529 private RetryFilters(DeviceId deviceId, PortFilterInfo previousRun) {
Saurav Das07c74602016-04-27 18:35:50 -07001530 devId = deviceId;
Saurav Dasd1872b02016-12-02 15:43:47 -08001531 prevRun = previousRun;
1532 counter = 0;
Saurav Das07c74602016-04-27 18:35:50 -07001533 }
1534
1535 @Override
1536 public void run() {
Charles Chan077314e2017-06-22 14:27:17 -07001537 log.debug("RETRY FILTER ATTEMPT {} ** dev:{}", ++counter, devId);
Charles Chan18fa4252017-02-08 16:10:40 -08001538 PortFilterInfo thisRun = rulePopulator.populateVlanMacFilters(devId);
Saurav Dasd1872b02016-12-02 15:43:47 -08001539 boolean sameResult = prevRun.equals(thisRun);
1540 log.debug("dev:{} prevRun:{} thisRun:{} sameResult:{}", devId, prevRun,
1541 thisRun, sameResult);
1542 if (thisRun == null || !sameResult || (sameResult && --constantAttempts > 0)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001543 // exponentially increasing intervals for retries
1544 executorService.schedule(this,
1545 RETRY_INTERVAL_MS * (int) Math.pow(counter, RETRY_INTERVAL_SCALE),
1546 TimeUnit.MILLISECONDS);
Saurav Dasd1872b02016-12-02 15:43:47 -08001547 if (!sameResult) {
1548 constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS; //reset
1549 }
Saurav Das07c74602016-04-27 18:35:50 -07001550 }
Saurav Dasd1872b02016-12-02 15:43:47 -08001551 prevRun = (thisRun == null) ? prevRun : thisRun;
Saurav Das07c74602016-04-27 18:35:50 -07001552 }
Saurav Das07c74602016-04-27 18:35:50 -07001553 }
1554
sangho80f11cb2015-04-01 13:05:26 -07001555}