blob: 31936e24ca5de4b11a1c5ea0e99c7013ed2705b0 [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
sangho9b169e32015-04-14 16:27:13 -070026import org.onlab.packet.Ip4Address;
Pier Ventreadb4ae62016-11-23 09:57:42 -080027import org.onlab.packet.Ip6Address;
sangho80f11cb2015-04-01 13:05:26 -070028import org.onlab.packet.IpPrefix;
Charles Chan910be6a2017-08-23 14:46:43 -070029import org.onlab.packet.MacAddress;
30import org.onlab.packet.VlanId;
Saurav Das261c3002017-06-13 15:35:54 -070031import org.onosproject.cluster.NodeId;
Saurav Das00e553b2018-04-21 17:19:48 -070032import org.onosproject.mastership.MastershipEvent;
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;
Charles Chand66d6712018-03-29 16:03:41 -070041import org.onosproject.store.serializers.KryoNamespaces;
42import org.onosproject.store.service.Serializer;
sangho80f11cb2015-04-01 13:05:26 -070043import org.slf4j.Logger;
44import org.slf4j.LoggerFactory;
45
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -070046import java.time.Instant;
sangho80f11cb2015-04-01 13:05:26 -070047import java.util.ArrayList;
Charles Chand66d6712018-03-29 16:03:41 -070048import java.util.Collections;
sangho80f11cb2015-04-01 13:05:26 -070049import java.util.HashMap;
50import java.util.HashSet;
Saurav Das261c3002017-06-13 15:35:54 -070051import java.util.Iterator;
Charles Chand66d6712018-03-29 16:03:41 -070052import java.util.List;
Saurav Das261c3002017-06-13 15:35:54 -070053import java.util.Map;
Saurav Dasd1872b02016-12-02 15:43:47 -080054import java.util.Objects;
Charles Chan6dbcd252018-04-02 11:46:38 -070055import java.util.Optional;
sangho80f11cb2015-04-01 13:05:26 -070056import java.util.Set;
Saurav Das07c74602016-04-27 18:35:50 -070057import java.util.concurrent.ScheduledExecutorService;
58import java.util.concurrent.TimeUnit;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +090059import java.util.concurrent.locks.Lock;
60import java.util.concurrent.locks.ReentrantLock;
Saurav Dasdc7f2752018-03-18 21:28:15 -070061import java.util.stream.Stream;
62
Saurav Dasd1872b02016-12-02 15:43:47 -080063import static com.google.common.base.MoreObjects.toStringHelper;
Pier Ventreadb4ae62016-11-23 09:57:42 -080064import static com.google.common.base.Preconditions.checkNotNull;
65import static java.util.concurrent.Executors.newScheduledThreadPool;
66import static org.onlab.util.Tools.groupedThreads;
sangho80f11cb2015-04-01 13:05:26 -070067
Charles Chanb7f75ac2016-01-11 18:28:54 -080068/**
69 * Default routing handler that is responsible for route computing and
70 * routing rule population.
71 */
sangho80f11cb2015-04-01 13:05:26 -070072public class DefaultRoutingHandler {
Saurav Dasf9332192017-02-18 14:05:44 -080073 private static final int MAX_CONSTANT_RETRY_ATTEMPTS = 5;
Ray Milkey092e9e22018-02-01 13:49:47 -080074 private static final long RETRY_INTERVAL_MS = 250L;
Saurav Dasf9332192017-02-18 14:05:44 -080075 private static final int RETRY_INTERVAL_SCALE = 1;
Saurav Dasfbe74572017-08-03 18:30:35 -070076 private static final long STABLITY_THRESHOLD = 10; //secs
Saurav Das00e553b2018-04-21 17:19:48 -070077 private static final long MASTER_CHANGE_DELAY = 1000; // ms
Charles Chanc22cef32016-04-29 14:38:22 -070078 private static Logger log = LoggerFactory.getLogger(DefaultRoutingHandler.class);
sangho80f11cb2015-04-01 13:05:26 -070079
80 private SegmentRoutingManager srManager;
81 private RoutingRulePopulator rulePopulator;
Shashikanth VH0637b162015-12-11 01:32:44 +053082 private HashMap<DeviceId, EcmpShortestPathGraph> currentEcmpSpgMap;
83 private HashMap<DeviceId, EcmpShortestPathGraph> updatedEcmpSpgMap;
sangho9b169e32015-04-14 16:27:13 -070084 private DeviceConfiguration config;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +090085 private final Lock statusLock = new ReentrantLock();
86 private volatile Status populationStatus;
Yuta HIGUCHIebee2f12016-07-21 16:54:33 -070087 private ScheduledExecutorService executorService
Saurav Dasd1872b02016-12-02 15:43:47 -080088 = newScheduledThreadPool(1, groupedThreads("retryftr", "retry-%d", log));
Saurav Das49368392018-04-23 18:42:12 -070089 private ScheduledExecutorService executorServiceMstChg
90 = newScheduledThreadPool(1, groupedThreads("masterChg", "mstch-%d", log));
91
Saurav Das00e553b2018-04-21 17:19:48 -070092 private Instant lastRoutingChange = Instant.EPOCH;
sangho80f11cb2015-04-01 13:05:26 -070093
Saurav Das00e553b2018-04-21 17:19:48 -070094 // Distributed store to keep track of ONOS instance that should program the
95 // device pair. There should be only one instance (the king) that programs the same pair.
Charles Chand66d6712018-03-29 16:03:41 -070096 Map<Set<DeviceId>, NodeId> shouldProgram;
Charles Chanfbcb8812018-04-18 18:41:05 -070097 Map<DeviceId, Boolean> shouldProgramCache;
Charles Chand66d6712018-03-29 16:03:41 -070098
Saurav Das00e553b2018-04-21 17:19:48 -070099 // Local store to keep track of all devices that this instance was responsible
100 // for programming in the last run. Helps to determine if mastership changed
101 // during a run - only relevant for programming as a result of topo change.
102 Set<DeviceId> lastProgrammed;
103
sangho80f11cb2015-04-01 13:05:26 -0700104 /**
105 * Represents the default routing population status.
106 */
107 public enum Status {
108 // population process is not started yet.
109 IDLE,
110
111 // population process started.
112 STARTED,
113
Srikanth Vavilapalli64505482015-04-21 13:04:13 -0700114 // population process was aborted due to errors, mostly for groups not
115 // found.
sangho80f11cb2015-04-01 13:05:26 -0700116 ABORTED,
117
118 // population process was finished successfully.
119 SUCCEEDED
120 }
121
122 /**
123 * Creates a DefaultRoutingHandler object.
124 *
125 * @param srManager SegmentRoutingManager object
126 */
Charles Chand66d6712018-03-29 16:03:41 -0700127 DefaultRoutingHandler(SegmentRoutingManager srManager) {
Charles Chanfbcb8812018-04-18 18:41:05 -0700128 this.shouldProgram = srManager.storageService.<Set<DeviceId>, NodeId>consistentMapBuilder()
129 .withName("sr-should-program")
130 .withSerializer(Serializer.using(KryoNamespaces.API))
131 .withRelaxedReadConsistency()
132 .build().asJavaMap();
133 this.shouldProgramCache = Maps.newConcurrentMap();
134 update(srManager);
135 }
136
137 /**
138 * Updates a DefaultRoutingHandler object.
139 *
140 * @param srManager SegmentRoutingManager object
141 */
142 void update(SegmentRoutingManager srManager) {
sangho80f11cb2015-04-01 13:05:26 -0700143 this.srManager = srManager;
144 this.rulePopulator = checkNotNull(srManager.routingRulePopulator);
sangho9b169e32015-04-14 16:27:13 -0700145 this.config = checkNotNull(srManager.deviceConfiguration);
sangho80f11cb2015-04-01 13:05:26 -0700146 this.populationStatus = Status.IDLE;
sanghofb7c7292015-04-13 15:15:58 -0700147 this.currentEcmpSpgMap = Maps.newHashMap();
Saurav Das00e553b2018-04-21 17:19:48 -0700148 this.lastProgrammed = Sets.newConcurrentHashSet();
sangho80f11cb2015-04-01 13:05:26 -0700149 }
150
151 /**
Saurav Das62ae6792017-05-15 15:34:25 -0700152 * Returns an immutable copy of the current ECMP shortest-path graph as
153 * computed by this controller instance.
154 *
Saurav Das261c3002017-06-13 15:35:54 -0700155 * @return immutable copy of the current ECMP graph
Saurav Das62ae6792017-05-15 15:34:25 -0700156 */
157 public ImmutableMap<DeviceId, EcmpShortestPathGraph> getCurrentEmcpSpgMap() {
158 Builder<DeviceId, EcmpShortestPathGraph> builder = ImmutableMap.builder();
159 currentEcmpSpgMap.entrySet().forEach(entry -> {
160 if (entry.getValue() != null) {
161 builder.put(entry.getKey(), entry.getValue());
162 }
163 });
164 return builder.build();
165 }
166
Saurav Dasfbe74572017-08-03 18:30:35 -0700167 /**
168 * Acquires the lock used when making routing changes.
169 */
170 public void acquireRoutingLock() {
171 statusLock.lock();
172 }
173
174 /**
175 * Releases the lock used when making routing changes.
176 */
177 public void releaseRoutingLock() {
178 statusLock.unlock();
179 }
180
181 /**
182 * Determines if routing in the network has been stable in the last
183 * STABLITY_THRESHOLD seconds, by comparing the current time to the last
184 * routing change timestamp.
185 *
186 * @return true if stable
187 */
188 public boolean isRoutingStable() {
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -0700189 long last = (long) (lastRoutingChange.toEpochMilli() / 1000.0);
190 long now = (long) (Instant.now().toEpochMilli() / 1000.0);
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700191 log.trace("Routing stable since {}s", now - last);
Saurav Dasfbe74572017-08-03 18:30:35 -0700192 return (now - last) > STABLITY_THRESHOLD;
193 }
194
Saurav Das49368392018-04-23 18:42:12 -0700195 /**
196 * Gracefully shuts down the defaultRoutingHandler. Typically called when
197 * the app is deactivated
198 */
199 public void shutdown() {
200 executorService.shutdown();
201 executorServiceMstChg.shutdown();
202 }
Saurav Dasfbe74572017-08-03 18:30:35 -0700203
Saurav Das261c3002017-06-13 15:35:54 -0700204 //////////////////////////////////////
205 // Route path handling
206 //////////////////////////////////////
207
Saurav Dase6c448a2018-01-18 12:07:33 -0800208 /* The following three methods represent the three major ways in which
209 * route-path handling is triggered in the network
Saurav Das261c3002017-06-13 15:35:54 -0700210 * a) due to configuration change
211 * b) due to route-added event
212 * c) due to change in the topology
213 */
214
Saurav Das62ae6792017-05-15 15:34:25 -0700215 /**
Saurav Das261c3002017-06-13 15:35:54 -0700216 * Populates all routing rules to all switches. Typically triggered at
217 * startup or after a configuration event.
sangho80f11cb2015-04-01 13:05:26 -0700218 */
Saurav Das62ae6792017-05-15 15:34:25 -0700219 public void populateAllRoutingRules() {
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -0700220 lastRoutingChange = Instant.now();
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900221 statusLock.lock();
222 try {
Saurav Das261c3002017-06-13 15:35:54 -0700223 if (populationStatus == Status.STARTED) {
224 log.warn("Previous rule population is not finished. Cannot"
225 + " proceed with populateAllRoutingRules");
226 return;
227 }
228
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900229 populationStatus = Status.STARTED;
230 rulePopulator.resetCounter();
Saurav Das261c3002017-06-13 15:35:54 -0700231 log.info("Starting to populate all routing rules");
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900232 log.debug("populateAllRoutingRules: populationStatus is STARTED");
sangho80f11cb2015-04-01 13:05:26 -0700233
Saurav Das261c3002017-06-13 15:35:54 -0700234 // take a snapshot of the topology
235 updatedEcmpSpgMap = new HashMap<>();
236 Set<EdgePair> edgePairs = new HashSet<>();
237 Set<ArrayList<DeviceId>> routeChanges = new HashSet<>();
Jonathan Hart61e24e12017-11-30 18:23:42 -0800238 for (DeviceId dstSw : srManager.deviceConfiguration.getRouters()) {
Saurav Das261c3002017-06-13 15:35:54 -0700239 EcmpShortestPathGraph ecmpSpgUpdated =
Jonathan Hart61e24e12017-11-30 18:23:42 -0800240 new EcmpShortestPathGraph(dstSw, srManager);
241 updatedEcmpSpgMap.put(dstSw, ecmpSpgUpdated);
Charles Chan6dbcd252018-04-02 11:46:38 -0700242 Optional<DeviceId> pairDev = srManager.getPairDeviceId(dstSw);
243 if (pairDev.isPresent()) {
Saurav Das261c3002017-06-13 15:35:54 -0700244 // pairDev may not be available yet, but we still need to add
Charles Chan6dbcd252018-04-02 11:46:38 -0700245 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev.get(), srManager);
246 updatedEcmpSpgMap.put(pairDev.get(), ecmpSpgUpdated);
247 edgePairs.add(new EdgePair(dstSw, pairDev.get()));
Saurav Das261c3002017-06-13 15:35:54 -0700248 }
Charles Chand66d6712018-03-29 16:03:41 -0700249
250 if (!shouldProgram(dstSw)) {
Saurav Das00e553b2018-04-21 17:19:48 -0700251 lastProgrammed.remove(dstSw);
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900252 continue;
Saurav Das00e553b2018-04-21 17:19:48 -0700253 } else {
254 lastProgrammed.add(dstSw);
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900255 }
Saurav Das00e553b2018-04-21 17:19:48 -0700256 // To do a full reroute, assume all route-paths have changed
Charles Chand66d6712018-03-29 16:03:41 -0700257 for (DeviceId dev : deviceAndItsPair(dstSw)) {
Jonathan Hart61e24e12017-11-30 18:23:42 -0800258 for (DeviceId targetSw : srManager.deviceConfiguration.getRouters()) {
259 if (targetSw.equals(dev)) {
Saurav Das261c3002017-06-13 15:35:54 -0700260 continue;
261 }
Jonathan Hart61e24e12017-11-30 18:23:42 -0800262 routeChanges.add(Lists.newArrayList(targetSw, dev));
Saurav Das261c3002017-06-13 15:35:54 -0700263 }
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900264 }
Saurav Das261c3002017-06-13 15:35:54 -0700265 }
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900266
Saurav Das261c3002017-06-13 15:35:54 -0700267 if (!redoRouting(routeChanges, edgePairs, null)) {
268 log.debug("populateAllRoutingRules: populationStatus is ABORTED");
269 populationStatus = Status.ABORTED;
270 log.warn("Failed to repopulate all routing rules.");
271 return;
sangho80f11cb2015-04-01 13:05:26 -0700272 }
273
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900274 log.debug("populateAllRoutingRules: populationStatus is SUCCEEDED");
275 populationStatus = Status.SUCCEEDED;
Saurav Das261c3002017-06-13 15:35:54 -0700276 log.info("Completed all routing rule population. Total # of rules pushed : {}",
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900277 rulePopulator.getCounter());
Saurav Das62ae6792017-05-15 15:34:25 -0700278 return;
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900279 } finally {
280 statusLock.unlock();
sangho80f11cb2015-04-01 13:05:26 -0700281 }
sangho80f11cb2015-04-01 13:05:26 -0700282 }
283
sanghofb7c7292015-04-13 15:15:58 -0700284 /**
Saurav Das261c3002017-06-13 15:35:54 -0700285 * Populate rules from all other edge devices to the connect-point(s)
286 * specified for the given subnets.
287 *
288 * @param cpts connect point(s) of the subnets being added
289 * @param subnets subnets being added
Charles Chan910be6a2017-08-23 14:46:43 -0700290 */
291 // XXX refactor
Saurav Das261c3002017-06-13 15:35:54 -0700292 protected void populateSubnet(Set<ConnectPoint> cpts, Set<IpPrefix> subnets) {
Charles Chan6db55b92017-09-11 15:21:57 -0700293 if (cpts == null || cpts.size() < 1 || cpts.size() > 2) {
294 log.warn("Skipping populateSubnet due to illegal size of connect points. {}", cpts);
295 return;
296 }
297
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -0700298 lastRoutingChange = Instant.now();
Saurav Das261c3002017-06-13 15:35:54 -0700299 statusLock.lock();
300 try {
301 if (populationStatus == Status.STARTED) {
302 log.warn("Previous rule population is not finished. Cannot"
303 + " proceed with routing rules for added routes");
304 return;
305 }
306 populationStatus = Status.STARTED;
307 rulePopulator.resetCounter();
Charles Chan910be6a2017-08-23 14:46:43 -0700308 log.info("Starting to populate routing rules for added routes, subnets={}, cpts={}",
309 subnets, cpts);
Saurav Das6430f412018-01-25 09:49:01 -0800310 // In principle an update to a subnet/prefix should not require a
311 // new ECMPspg calculation as it is not a topology event. As a
312 // result, we use the current/existing ECMPspg in the updated map
313 // used by the redoRouting method.
Saurav Das6de6ffd2018-02-09 09:15:03 -0800314 if (updatedEcmpSpgMap == null) {
315 updatedEcmpSpgMap = new HashMap<>();
316 }
Saurav Das6430f412018-01-25 09:49:01 -0800317 currentEcmpSpgMap.entrySet().forEach(entry -> {
318 updatedEcmpSpgMap.put(entry.getKey(), entry.getValue());
Saurav Dase321cff2018-02-09 17:26:45 -0800319 if (log.isTraceEnabled()) {
320 log.trace("Root switch: {}", entry.getKey());
321 log.trace(" Current/Existing SPG: {}", entry.getValue());
Saurav Das6430f412018-01-25 09:49:01 -0800322 }
323 });
Saurav Das261c3002017-06-13 15:35:54 -0700324 Set<EdgePair> edgePairs = new HashSet<>();
325 Set<ArrayList<DeviceId>> routeChanges = new HashSet<>();
326 boolean handleRouting = false;
327
328 if (cpts.size() == 2) {
329 // ensure connect points are edge-pairs
330 Iterator<ConnectPoint> iter = cpts.iterator();
331 DeviceId dev1 = iter.next().deviceId();
Charles Chan6dbcd252018-04-02 11:46:38 -0700332 Optional<DeviceId> pairDev = srManager.getPairDeviceId(dev1);
333 if (pairDev.isPresent() && iter.next().deviceId().equals(pairDev.get())) {
334 edgePairs.add(new EdgePair(dev1, pairDev.get()));
Saurav Das261c3002017-06-13 15:35:54 -0700335 } else {
336 log.warn("Connectpoints {} for subnets {} not on "
337 + "pair-devices.. aborting populateSubnet", cpts, subnets);
338 populationStatus = Status.ABORTED;
339 return;
340 }
341 for (ConnectPoint cp : cpts) {
Saurav Das6430f412018-01-25 09:49:01 -0800342 if (updatedEcmpSpgMap.get(cp.deviceId()) == null) {
343 EcmpShortestPathGraph ecmpSpgUpdated =
Saurav Das261c3002017-06-13 15:35:54 -0700344 new EcmpShortestPathGraph(cp.deviceId(), srManager);
Saurav Das6430f412018-01-25 09:49:01 -0800345 updatedEcmpSpgMap.put(cp.deviceId(), ecmpSpgUpdated);
346 log.warn("populateSubnet: no updated graph for dev:{}"
347 + " ... creating", cp.deviceId());
348 }
Charles Chand66d6712018-03-29 16:03:41 -0700349 if (!shouldProgram(cp.deviceId())) {
Saurav Das261c3002017-06-13 15:35:54 -0700350 continue;
351 }
352 handleRouting = true;
353 }
354 } else {
355 // single connect point
356 DeviceId dstSw = cpts.iterator().next().deviceId();
Saurav Das6430f412018-01-25 09:49:01 -0800357 if (updatedEcmpSpgMap.get(dstSw) == null) {
358 EcmpShortestPathGraph ecmpSpgUpdated =
Saurav Das261c3002017-06-13 15:35:54 -0700359 new EcmpShortestPathGraph(dstSw, srManager);
Saurav Das6430f412018-01-25 09:49:01 -0800360 updatedEcmpSpgMap.put(dstSw, ecmpSpgUpdated);
361 log.warn("populateSubnet: no updated graph for dev:{}"
362 + " ... creating", dstSw);
363 }
Charles Chand66d6712018-03-29 16:03:41 -0700364 handleRouting = shouldProgram(dstSw);
Saurav Das261c3002017-06-13 15:35:54 -0700365 }
366
367 if (!handleRouting) {
368 log.debug("This instance is not handling ecmp routing to the "
369 + "connectPoint(s) {}", cpts);
370 populationStatus = Status.ABORTED;
371 return;
372 }
373
374 // if it gets here, this instance should handle routing for the
375 // connectpoint(s). Assume all route-paths have to be updated to
376 // the connectpoint(s) with the following exceptions
377 // 1. if target is non-edge no need for routing rules
378 // 2. if target is one of the connectpoints
379 for (ConnectPoint cp : cpts) {
380 DeviceId dstSw = cp.deviceId();
381 for (Device targetSw : srManager.deviceService.getDevices()) {
382 boolean isEdge = false;
383 try {
384 isEdge = config.isEdgeDevice(targetSw.id());
385 } catch (DeviceConfigNotFoundException e) {
Charles Chaneaf3c9b2018-02-16 17:20:54 -0800386 log.warn(e.getMessage() + "aborting populateSubnet on targetSw {}", targetSw.id());
387 continue;
Saurav Das261c3002017-06-13 15:35:54 -0700388 }
Charles Chan6dbcd252018-04-02 11:46:38 -0700389 Optional<DeviceId> pairDev = srManager.getPairDeviceId(dstSw);
Saurav Das261c3002017-06-13 15:35:54 -0700390 if (dstSw.equals(targetSw.id()) || !isEdge ||
Charles Chan6dbcd252018-04-02 11:46:38 -0700391 (cpts.size() == 2 && pairDev.isPresent() && targetSw.id().equals(pairDev.get()))) {
Saurav Das261c3002017-06-13 15:35:54 -0700392 continue;
393 }
394 routeChanges.add(Lists.newArrayList(targetSw.id(), dstSw));
395 }
396 }
397
398 if (!redoRouting(routeChanges, edgePairs, subnets)) {
399 log.debug("populateSubnet: populationStatus is ABORTED");
400 populationStatus = Status.ABORTED;
401 log.warn("Failed to repopulate the rules for subnet.");
402 return;
403 }
404
405 log.debug("populateSubnet: populationStatus is SUCCEEDED");
406 populationStatus = Status.SUCCEEDED;
407 log.info("Completed subnet population. Total # of rules pushed : {}",
408 rulePopulator.getCounter());
409 return;
410
411 } finally {
412 statusLock.unlock();
413 }
414 }
415
416 /**
Saurav Das62ae6792017-05-15 15:34:25 -0700417 * Populates the routing rules or makes hash group changes according to the
418 * route-path changes due to link failure, switch failure or link up. This
419 * method should only be called for one of these three possible event-types.
Saurav Dasdc7f2752018-03-18 21:28:15 -0700420 * Note that when a switch goes away, all of its links fail as well, but
421 * this is handled as a single switch removal event.
sanghofb7c7292015-04-13 15:15:58 -0700422 *
Saurav Dasdc7f2752018-03-18 21:28:15 -0700423 * @param linkDown the single failed link, or null for other conditions such
424 * as link-up or a removed switch
Saurav Das62ae6792017-05-15 15:34:25 -0700425 * @param linkUp the single link up, or null for other conditions such as
Saurav Dasdc7f2752018-03-18 21:28:15 -0700426 * link-down or a removed switch
427 * @param switchDown the removed switch, or null for other conditions such
428 * as link-down or link-up
429 * @param seenBefore true if this event is for a linkUp or linkDown for a
430 * seen link
431 */
432 // TODO This method should be refactored into three separated methods
Saurav Das62ae6792017-05-15 15:34:25 -0700433 public void populateRoutingRulesForLinkStatusChange(Link linkDown,
434 Link linkUp,
Saurav Dasdc7f2752018-03-18 21:28:15 -0700435 DeviceId switchDown,
436 boolean seenBefore) {
437 if (Stream.of(linkDown, linkUp, switchDown).filter(Objects::nonNull)
438 .count() != 1) {
Saurav Das62ae6792017-05-15 15:34:25 -0700439 log.warn("Only one event can be handled for link status change .. aborting");
440 return;
441 }
Saurav Dasdc7f2752018-03-18 21:28:15 -0700442
Yuta HIGUCHIc9d93472017-08-18 23:16:35 -0700443 lastRoutingChange = Instant.now();
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900444 statusLock.lock();
445 try {
sanghofb7c7292015-04-13 15:15:58 -0700446
447 if (populationStatus == Status.STARTED) {
Saurav Das261c3002017-06-13 15:35:54 -0700448 log.warn("Previous rule population is not finished. Cannot"
Saurav Das6430f412018-01-25 09:49:01 -0800449 + " proceeed with routingRules for Topology change");
Saurav Das62ae6792017-05-15 15:34:25 -0700450 return;
sanghofb7c7292015-04-13 15:15:58 -0700451 }
452
Saurav Das261c3002017-06-13 15:35:54 -0700453 // Take snapshots of the topology
sangho28d0b6d2015-05-07 13:30:57 -0700454 updatedEcmpSpgMap = new HashMap<>();
Saurav Das261c3002017-06-13 15:35:54 -0700455 Set<EdgePair> edgePairs = new HashSet<>();
sangho28d0b6d2015-05-07 13:30:57 -0700456 for (Device sw : srManager.deviceService.getDevices()) {
Shashikanth VH0637b162015-12-11 01:32:44 +0530457 EcmpShortestPathGraph ecmpSpgUpdated =
458 new EcmpShortestPathGraph(sw.id(), srManager);
sangho28d0b6d2015-05-07 13:30:57 -0700459 updatedEcmpSpgMap.put(sw.id(), ecmpSpgUpdated);
Charles Chan6dbcd252018-04-02 11:46:38 -0700460 Optional<DeviceId> pairDev = srManager.getPairDeviceId(sw.id());
461 if (pairDev.isPresent()) {
Saurav Das261c3002017-06-13 15:35:54 -0700462 // pairDev may not be available yet, but we still need to add
Charles Chan6dbcd252018-04-02 11:46:38 -0700463 ecmpSpgUpdated = new EcmpShortestPathGraph(pairDev.get(), srManager);
464 updatedEcmpSpgMap.put(pairDev.get(), ecmpSpgUpdated);
465 edgePairs.add(new EdgePair(sw.id(), pairDev.get()));
Saurav Das261c3002017-06-13 15:35:54 -0700466 }
sangho28d0b6d2015-05-07 13:30:57 -0700467 }
468
Saurav Das6430f412018-01-25 09:49:01 -0800469 log.info("Starting to populate routing rules from Topology change");
sanghodf0153f2015-05-05 14:13:34 -0700470
sanghofb7c7292015-04-13 15:15:58 -0700471 Set<ArrayList<DeviceId>> routeChanges;
Saurav Das62ae6792017-05-15 15:34:25 -0700472 log.debug("populateRoutingRulesForLinkStatusChange: "
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700473 + "populationStatus is STARTED");
sanghofb7c7292015-04-13 15:15:58 -0700474 populationStatus = Status.STARTED;
Saurav Das6430f412018-01-25 09:49:01 -0800475 rulePopulator.resetCounter(); //XXX maybe useful to have a rehash ctr
476 boolean hashGroupsChanged = false;
Saurav Das1b391d52016-11-29 14:27:25 -0800477 // try optimized re-routing
Saurav Das62ae6792017-05-15 15:34:25 -0700478 if (linkDown == null) {
479 // either a linkUp or a switchDown - compute all route changes by
480 // comparing all routes of existing ECMP SPG to new ECMP SPG
Saurav Dascea556f2018-03-05 14:37:16 -0800481 routeChanges = computeRouteChange(switchDown);
Saurav Das62ae6792017-05-15 15:34:25 -0700482
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700483 // deal with linkUp of a seen-before link
Saurav Dasdc7f2752018-03-18 21:28:15 -0700484 if (linkUp != null && seenBefore) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700485 // link previously seen before
486 // do hash-bucket changes instead of a re-route
487 processHashGroupChange(routeChanges, false, null);
488 // clear out routesChanges so a re-route is not attempted
489 routeChanges = ImmutableSet.of();
Saurav Das6430f412018-01-25 09:49:01 -0800490 hashGroupsChanged = true;
Saurav Das62ae6792017-05-15 15:34:25 -0700491 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700492 // for a linkUp of a never-seen-before link
493 // let it fall through to a reroute of the routeChanges
Saurav Das62ae6792017-05-15 15:34:25 -0700494
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700495 //deal with switchDown
496 if (switchDown != null) {
497 processHashGroupChange(routeChanges, true, switchDown);
498 // clear out routesChanges so a re-route is not attempted
499 routeChanges = ImmutableSet.of();
Saurav Das6430f412018-01-25 09:49:01 -0800500 hashGroupsChanged = true;
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700501 }
sanghofb7c7292015-04-13 15:15:58 -0700502 } else {
Saurav Das62ae6792017-05-15 15:34:25 -0700503 // link has gone down
504 // Compare existing ECMP SPG only with the link that went down
505 routeChanges = computeDamagedRoutes(linkDown);
506 if (routeChanges != null) {
507 processHashGroupChange(routeChanges, true, null);
508 // clear out routesChanges so a re-route is not attempted
509 routeChanges = ImmutableSet.of();
Saurav Das6430f412018-01-25 09:49:01 -0800510 hashGroupsChanged = true;
Saurav Das62ae6792017-05-15 15:34:25 -0700511 }
sanghofb7c7292015-04-13 15:15:58 -0700512 }
513
Saurav Das1b391d52016-11-29 14:27:25 -0800514 // do full re-routing if optimized routing returns null routeChanges
Saurav Dasb149be12016-06-07 10:08:06 -0700515 if (routeChanges == null) {
Saurav Das6430f412018-01-25 09:49:01 -0800516 log.warn("Optimized routing failed... opting for full reroute");
Saurav Das261c3002017-06-13 15:35:54 -0700517 populationStatus = Status.ABORTED;
Saurav Das62ae6792017-05-15 15:34:25 -0700518 populateAllRoutingRules();
519 return;
Saurav Dasb149be12016-06-07 10:08:06 -0700520 }
521
sanghofb7c7292015-04-13 15:15:58 -0700522 if (routeChanges.isEmpty()) {
Saurav Das6430f412018-01-25 09:49:01 -0800523 if (hashGroupsChanged) {
524 log.info("Hash-groups changed for link status change");
525 } else {
526 log.info("No re-route or re-hash attempted for the link"
527 + " status change");
528 updatedEcmpSpgMap.keySet().forEach(devId -> {
529 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
530 log.debug("Updating ECMPspg for remaining dev:{}", devId);
531 });
532 }
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700533 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sanghofb7c7292015-04-13 15:15:58 -0700534 populationStatus = Status.SUCCEEDED;
Saurav Das62ae6792017-05-15 15:34:25 -0700535 return;
sanghofb7c7292015-04-13 15:15:58 -0700536 }
537
Saurav Das62ae6792017-05-15 15:34:25 -0700538 // reroute of routeChanges
Saurav Das261c3002017-06-13 15:35:54 -0700539 if (redoRouting(routeChanges, edgePairs, null)) {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700540 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is SUCCEEDED");
sanghofb7c7292015-04-13 15:15:58 -0700541 populationStatus = Status.SUCCEEDED;
Saurav Das261c3002017-06-13 15:35:54 -0700542 log.info("Completed repopulation of rules for link-status change."
543 + " # of rules populated : {}", rulePopulator.getCounter());
Saurav Das62ae6792017-05-15 15:34:25 -0700544 return;
sanghofb7c7292015-04-13 15:15:58 -0700545 } else {
Srikanth Vavilapalli7cd16712015-05-04 09:48:09 -0700546 log.debug("populateRoutingRulesForLinkStatusChange: populationStatus is ABORTED");
sanghofb7c7292015-04-13 15:15:58 -0700547 populationStatus = Status.ABORTED;
Saurav Das261c3002017-06-13 15:35:54 -0700548 log.warn("Failed to repopulate the rules for link status change.");
Saurav Das62ae6792017-05-15 15:34:25 -0700549 return;
sanghofb7c7292015-04-13 15:15:58 -0700550 }
HIGUCHI Yuta16d8fd52015-09-08 16:16:31 +0900551 } finally {
552 statusLock.unlock();
sanghofb7c7292015-04-13 15:15:58 -0700553 }
554 }
555
Saurav Das62ae6792017-05-15 15:34:25 -0700556 /**
Saurav Das261c3002017-06-13 15:35:54 -0700557 * Processes a set a route-path changes by reprogramming routing rules and
558 * creating new hash-groups or editing them if necessary. This method also
559 * determines the next-hops for the route-path from the src-switch (target)
560 * of the path towards the dst-switch of the path.
Saurav Das62ae6792017-05-15 15:34:25 -0700561 *
Saurav Das261c3002017-06-13 15:35:54 -0700562 * @param routeChanges a set of route-path changes, where each route-path is
563 * a list with its first element the src-switch (target)
564 * of the path, and the second element the dst-switch of
565 * the path.
566 * @param edgePairs a set of edge-switches that are paired by configuration
567 * @param subnets a set of prefixes that need to be populated in the routing
568 * table of the target switch in the route-path. Can be null,
569 * in which case all the prefixes belonging to the dst-switch
570 * will be populated in the target switch
571 * @return true if successful in repopulating all routes
Saurav Das62ae6792017-05-15 15:34:25 -0700572 */
Saurav Das261c3002017-06-13 15:35:54 -0700573 private boolean redoRouting(Set<ArrayList<DeviceId>> routeChanges,
574 Set<EdgePair> edgePairs, Set<IpPrefix> subnets) {
575 // first make every entry two-elements
576 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
577 for (ArrayList<DeviceId> route : routeChanges) {
578 if (route.size() == 1) {
579 DeviceId dstSw = route.get(0);
580 EcmpShortestPathGraph ec = updatedEcmpSpgMap.get(dstSw);
581 if (ec == null) {
582 log.warn("No graph found for {} .. aborting redoRouting", dstSw);
583 return false;
584 }
585 ec.getAllLearnedSwitchesAndVia().keySet().forEach(key -> {
586 ec.getAllLearnedSwitchesAndVia().get(key).keySet().forEach(target -> {
587 changedRoutes.add(Lists.newArrayList(target, dstSw));
588 });
589 });
590 } else {
591 DeviceId targetSw = route.get(0);
592 DeviceId dstSw = route.get(1);
593 changedRoutes.add(Lists.newArrayList(targetSw, dstSw));
594 }
595 }
596
597 // now process changedRoutes according to edgePairs
598 if (!redoRoutingEdgePairs(edgePairs, subnets, changedRoutes)) {
599 return false; //abort routing and fail fast
600 }
601
602 // whatever is left in changedRoutes is now processed for individual dsts.
Saurav Das6430f412018-01-25 09:49:01 -0800603 Set<DeviceId> updatedDevices = Sets.newHashSet();
604 if (!redoRoutingIndividualDests(subnets, changedRoutes,
605 updatedDevices)) {
Saurav Das261c3002017-06-13 15:35:54 -0700606 return false; //abort routing and fail fast
607 }
608
Saurav Das261c3002017-06-13 15:35:54 -0700609 // update ecmpSPG for all edge-pairs
610 for (EdgePair ep : edgePairs) {
611 currentEcmpSpgMap.put(ep.dev1, updatedEcmpSpgMap.get(ep.dev1));
612 currentEcmpSpgMap.put(ep.dev2, updatedEcmpSpgMap.get(ep.dev2));
613 log.debug("Updating ECMPspg for edge-pair:{}-{}", ep.dev1, ep.dev2);
614 }
Saurav Das6430f412018-01-25 09:49:01 -0800615
616 // here is where we update all devices not touched by this instance
617 updatedEcmpSpgMap.keySet().stream()
618 .filter(devId -> !edgePairs.stream().anyMatch(ep -> ep.includes(devId)))
619 .filter(devId -> !updatedDevices.contains(devId))
620 .forEach(devId -> {
621 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
622 log.debug("Updating ECMPspg for remaining dev:{}", devId);
623 });
Saurav Das261c3002017-06-13 15:35:54 -0700624 return true;
625 }
626
627 /**
628 * Programs targetSw in the changedRoutes for given prefixes reachable by
629 * an edgePair. If no prefixes are given, the method will use configured
630 * subnets/prefixes. If some configured subnets belong only to a specific
631 * destination in the edgePair, then the target switch will be programmed
632 * only to that destination.
633 *
634 * @param edgePairs set of edge-pairs for which target will be programmed
635 * @param subnets a set of prefixes that need to be populated in the routing
636 * table of the target switch in the changedRoutes. Can be null,
637 * in which case all the configured prefixes belonging to the
638 * paired switches will be populated in the target switch
639 * @param changedRoutes a set of route-path changes, where each route-path is
640 * a list with its first element the src-switch (target)
641 * of the path, and the second element the dst-switch of
642 * the path.
643 * @return true if successful
644 */
645 private boolean redoRoutingEdgePairs(Set<EdgePair> edgePairs,
646 Set<IpPrefix> subnets,
647 Set<ArrayList<DeviceId>> changedRoutes) {
648 for (EdgePair ep : edgePairs) {
649 // temp store for a target's changedRoutes to this edge-pair
650 Map<DeviceId, Set<ArrayList<DeviceId>>> targetRoutes = new HashMap<>();
651 Iterator<ArrayList<DeviceId>> i = changedRoutes.iterator();
652 while (i.hasNext()) {
653 ArrayList<DeviceId> route = i.next();
654 DeviceId dstSw = route.get(1);
655 if (ep.includes(dstSw)) {
656 // routeChange for edge pair found
657 // sort by target iff target is edge and remove from changedRoutes
658 DeviceId targetSw = route.get(0);
659 try {
660 if (!srManager.deviceConfiguration.isEdgeDevice(targetSw)) {
661 continue;
662 }
663 } catch (DeviceConfigNotFoundException e) {
664 log.warn(e.getMessage() + "aborting redoRouting");
665 return false;
666 }
667 // route is from another edge to this edge-pair
668 if (targetRoutes.containsKey(targetSw)) {
669 targetRoutes.get(targetSw).add(route);
670 } else {
671 Set<ArrayList<DeviceId>> temp = new HashSet<>();
672 temp.add(route);
673 targetRoutes.put(targetSw, temp);
674 }
675 i.remove();
676 }
677 }
678 // so now for this edgepair we have a per target set of routechanges
679 // process target->edgePair route
680 for (Map.Entry<DeviceId, Set<ArrayList<DeviceId>>> entry :
681 targetRoutes.entrySet()) {
682 log.debug("* redoRoutingDstPair Target:{} -> edge-pair {}",
683 entry.getKey(), ep);
684 DeviceId targetSw = entry.getKey();
685 Map<DeviceId, Set<DeviceId>> perDstNextHops = new HashMap<>();
686 entry.getValue().forEach(route -> {
687 Set<DeviceId> nhops = getNextHops(route.get(0), route.get(1));
688 log.debug("route: target {} -> dst {} found with next-hops {}",
689 route.get(0), route.get(1), nhops);
690 perDstNextHops.put(route.get(1), nhops);
691 });
692 Set<IpPrefix> ipDev1 = (subnets == null) ? config.getSubnets(ep.dev1)
693 : subnets;
694 Set<IpPrefix> ipDev2 = (subnets == null) ? config.getSubnets(ep.dev2)
695 : subnets;
696 ipDev1 = (ipDev1 == null) ? Sets.newHashSet() : ipDev1;
697 ipDev2 = (ipDev2 == null) ? Sets.newHashSet() : ipDev2;
Saurav Das6430f412018-01-25 09:49:01 -0800698 Set<DeviceId> nhDev1 = perDstNextHops.get(ep.dev1);
699 Set<DeviceId> nhDev2 = perDstNextHops.get(ep.dev2);
Saurav Das261c3002017-06-13 15:35:54 -0700700 // handle routing to subnets common to edge-pair
Saurav Das6430f412018-01-25 09:49:01 -0800701 // only if the targetSw is not part of the edge-pair and there
702 // exists a next hop to at least one of the devices in the edge-pair
703 if (!ep.includes(targetSw)
704 && ((nhDev1 != null && !nhDev1.isEmpty())
705 || (nhDev2 != null && !nhDev2.isEmpty()))) {
Saurav Das261c3002017-06-13 15:35:54 -0700706 if (!populateEcmpRoutingRulePartial(
707 targetSw,
708 ep.dev1, ep.dev2,
709 perDstNextHops,
710 Sets.intersection(ipDev1, ipDev2))) {
711 return false; // abort everything and fail fast
712 }
713 }
Saurav Das6430f412018-01-25 09:49:01 -0800714 // handle routing to subnets that only belong to dev1 only if
715 // a next-hop exists from the target to dev1
Saurav Das261c3002017-06-13 15:35:54 -0700716 Set<IpPrefix> onlyDev1Subnets = Sets.difference(ipDev1, ipDev2);
Saurav Das6430f412018-01-25 09:49:01 -0800717 if (!onlyDev1Subnets.isEmpty()
718 && nhDev1 != null && !nhDev1.isEmpty()) {
Saurav Das261c3002017-06-13 15:35:54 -0700719 Map<DeviceId, Set<DeviceId>> onlyDev1NextHops = new HashMap<>();
Saurav Das6430f412018-01-25 09:49:01 -0800720 onlyDev1NextHops.put(ep.dev1, nhDev1);
Saurav Das261c3002017-06-13 15:35:54 -0700721 if (!populateEcmpRoutingRulePartial(
722 targetSw,
723 ep.dev1, null,
724 onlyDev1NextHops,
725 onlyDev1Subnets)) {
726 return false; // abort everything and fail fast
727 }
728 }
Saurav Das6430f412018-01-25 09:49:01 -0800729 // handle routing to subnets that only belong to dev2 only if
730 // a next-hop exists from the target to dev2
Saurav Das261c3002017-06-13 15:35:54 -0700731 Set<IpPrefix> onlyDev2Subnets = Sets.difference(ipDev2, ipDev1);
Saurav Das6430f412018-01-25 09:49:01 -0800732 if (!onlyDev2Subnets.isEmpty()
733 && nhDev2 != null && !nhDev2.isEmpty()) {
Saurav Das261c3002017-06-13 15:35:54 -0700734 Map<DeviceId, Set<DeviceId>> onlyDev2NextHops = new HashMap<>();
Saurav Das6430f412018-01-25 09:49:01 -0800735 onlyDev2NextHops.put(ep.dev2, nhDev2);
Saurav Das261c3002017-06-13 15:35:54 -0700736 if (!populateEcmpRoutingRulePartial(
737 targetSw,
738 ep.dev2, null,
739 onlyDev2NextHops,
740 onlyDev2Subnets)) {
741 return false; // abort everything and fail fast
742 }
743 }
744 }
745 // if it gets here it has succeeded for all targets to this edge-pair
746 }
747 return true;
748 }
749
750 /**
751 * Programs targetSw in the changedRoutes for given prefixes reachable by
752 * a destination switch that is not part of an edge-pair.
753 * If no prefixes are given, the method will use configured subnets/prefixes.
754 *
755 * @param subnets a set of prefixes that need to be populated in the routing
756 * table of the target switch in the changedRoutes. Can be null,
757 * in which case all the configured prefixes belonging to the
758 * paired switches will be populated in the target switch
759 * @param changedRoutes a set of route-path changes, where each route-path is
760 * a list with its first element the src-switch (target)
761 * of the path, and the second element the dst-switch of
762 * the path.
763 * @return true if successful
764 */
765 private boolean redoRoutingIndividualDests(Set<IpPrefix> subnets,
Saurav Das6430f412018-01-25 09:49:01 -0800766 Set<ArrayList<DeviceId>> changedRoutes,
767 Set<DeviceId> updatedDevices) {
Saurav Das261c3002017-06-13 15:35:54 -0700768 // aggregate route-path changes for each dst device
769 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> routesBydevice =
770 new HashMap<>();
771 for (ArrayList<DeviceId> route: changedRoutes) {
772 DeviceId dstSw = route.get(1);
773 ArrayList<ArrayList<DeviceId>> deviceRoutes =
774 routesBydevice.get(dstSw);
775 if (deviceRoutes == null) {
776 deviceRoutes = new ArrayList<>();
777 routesBydevice.put(dstSw, deviceRoutes);
778 }
779 deviceRoutes.add(route);
780 }
781 for (DeviceId impactedDstDevice : routesBydevice.keySet()) {
782 ArrayList<ArrayList<DeviceId>> deviceRoutes =
783 routesBydevice.get(impactedDstDevice);
784 for (ArrayList<DeviceId> route: deviceRoutes) {
785 log.debug("* redoRoutingIndiDst Target: {} -> dst: {}",
786 route.get(0), route.get(1));
787 DeviceId targetSw = route.get(0);
788 DeviceId dstSw = route.get(1); // same as impactedDstDevice
789 Set<DeviceId> nextHops = getNextHops(targetSw, dstSw);
Saurav Das8e46aa72018-01-09 17:38:44 -0800790 if (nextHops.isEmpty()) {
791 log.warn("Could not find next hop from target:{} --> dst {} "
792 + "skipping this route", targetSw, dstSw);
793 continue;
794 }
Saurav Das261c3002017-06-13 15:35:54 -0700795 Map<DeviceId, Set<DeviceId>> nhops = new HashMap<>();
796 nhops.put(dstSw, nextHops);
797 if (!populateEcmpRoutingRulePartial(targetSw, dstSw, null, nhops,
798 (subnets == null) ? Sets.newHashSet() : subnets)) {
799 return false; // abort routing and fail fast
800 }
801 log.debug("Populating flow rules from target: {} to dst: {}"
802 + " is successful", targetSw, dstSw);
803 }
804 //Only if all the flows for all impacted routes to a
805 //specific target are pushed successfully, update the
806 //ECMP graph for that target. Or else the next event
807 //would not see any changes in the ECMP graphs.
808 //In another case, the target switch has gone away, so
809 //routes can't be installed. In that case, the current map
810 //is updated here, without any flows being pushed.
811 currentEcmpSpgMap.put(impactedDstDevice,
812 updatedEcmpSpgMap.get(impactedDstDevice));
Saurav Das6430f412018-01-25 09:49:01 -0800813 updatedDevices.add(impactedDstDevice);
Saurav Das261c3002017-06-13 15:35:54 -0700814 log.debug("Updating ECMPspg for impacted dev:{}", impactedDstDevice);
815 }
816 return true;
817 }
818
819 /**
820 * Populate ECMP rules for subnets from target to destination via nexthops.
821 *
822 * @param targetSw Device ID of target switch in which rules will be programmed
823 * @param destSw1 Device ID of final destination switch to which the rules will forward
824 * @param destSw2 Device ID of paired destination switch to which the rules will forward
825 * A null deviceId indicates packets should only be sent to destSw1
Saurav Das97241862018-02-14 14:14:54 -0800826 * @param nextHops Map of a set of next hops per destSw
Saurav Das261c3002017-06-13 15:35:54 -0700827 * @param subnets Subnets to be populated. If empty, populate all configured subnets.
828 * @return true if it succeeds in populating rules
829 */ // refactor
830 private boolean populateEcmpRoutingRulePartial(DeviceId targetSw,
831 DeviceId destSw1,
832 DeviceId destSw2,
833 Map<DeviceId, Set<DeviceId>> nextHops,
834 Set<IpPrefix> subnets) {
835 boolean result;
836 // If both target switch and dest switch are edge routers, then set IP
837 // rule for both subnet and router IP.
838 boolean targetIsEdge;
839 boolean dest1IsEdge;
840 Ip4Address dest1RouterIpv4, dest2RouterIpv4 = null;
841 Ip6Address dest1RouterIpv6, dest2RouterIpv6 = null;
842
843 try {
844 targetIsEdge = config.isEdgeDevice(targetSw);
845 dest1IsEdge = config.isEdgeDevice(destSw1);
846 dest1RouterIpv4 = config.getRouterIpv4(destSw1);
847 dest1RouterIpv6 = config.getRouterIpv6(destSw1);
848 if (destSw2 != null) {
849 dest2RouterIpv4 = config.getRouterIpv4(destSw2);
850 dest2RouterIpv6 = config.getRouterIpv6(destSw2);
851 }
852 } catch (DeviceConfigNotFoundException e) {
853 log.warn(e.getMessage() + " Aborting populateEcmpRoutingRulePartial.");
Saurav Das62ae6792017-05-15 15:34:25 -0700854 return false;
855 }
Saurav Das261c3002017-06-13 15:35:54 -0700856
857 if (targetIsEdge && dest1IsEdge) {
858 subnets = (subnets != null && !subnets.isEmpty())
859 ? Sets.newHashSet(subnets)
860 : Sets.newHashSet(config.getSubnets(destSw1));
Saurav Das97241862018-02-14 14:14:54 -0800861 // XXX - Rethink this - ignoring routerIPs in all other switches
862 // even edge to edge switches
Saurav Das261c3002017-06-13 15:35:54 -0700863 /*subnets.add(dest1RouterIpv4.toIpPrefix());
864 if (dest1RouterIpv6 != null) {
865 subnets.add(dest1RouterIpv6.toIpPrefix());
866 }
867 if (destSw2 != null && dest2RouterIpv4 != null) {
868 subnets.add(dest2RouterIpv4.toIpPrefix());
869 if (dest2RouterIpv6 != null) {
870 subnets.add(dest2RouterIpv6.toIpPrefix());
871 }
872 }*/
873 log.debug(". populateEcmpRoutingRulePartial in device {} towards {} {} "
874 + "for subnets {}", targetSw, destSw1,
875 (destSw2 != null) ? ("& " + destSw2) : "",
876 subnets);
877 result = rulePopulator.populateIpRuleForSubnet(targetSw, subnets,
878 destSw1, destSw2,
879 nextHops);
880 if (!result) {
881 return false;
882 }
Saurav Das62ae6792017-05-15 15:34:25 -0700883 }
Saurav Das261c3002017-06-13 15:35:54 -0700884
885 if (!targetIsEdge && dest1IsEdge) {
886 // MPLS rules in all non-edge target devices. These rules are for
887 // individual destinations, even if the dsts are part of edge-pairs.
888 log.debug(". populateEcmpRoutingRulePartial in device{} towards {} for "
889 + "all MPLS rules", targetSw, destSw1);
890 result = rulePopulator.populateMplsRule(targetSw, destSw1,
891 nextHops.get(destSw1),
892 dest1RouterIpv4);
893 if (!result) {
894 return false;
895 }
896 if (dest1RouterIpv6 != null) {
Saurav Das97241862018-02-14 14:14:54 -0800897 int v4sid = 0, v6sid = 0;
898 try {
899 v4sid = config.getIPv4SegmentId(destSw1);
900 v6sid = config.getIPv6SegmentId(destSw1);
901 } catch (DeviceConfigNotFoundException e) {
902 log.warn(e.getMessage());
903 }
904 if (v4sid != v6sid) {
905 result = rulePopulator.populateMplsRule(targetSw, destSw1,
906 nextHops.get(destSw1),
907 dest1RouterIpv6);
908 if (!result) {
909 return false;
910 }
Saurav Das261c3002017-06-13 15:35:54 -0700911 }
912 }
913 }
914
Andreas Pantelopoulosfc4bc2a2018-03-12 16:30:20 -0700915 if (!targetIsEdge && !dest1IsEdge) {
916 // MPLS rules for inter-connected spines
917 // can be merged with above if, left it here for clarity
918 log.debug(". populateEcmpRoutingRulePartial in device{} towards {} for "
919 + "all MPLS rules", targetSw, destSw1);
920
921 result = rulePopulator.populateMplsRule(targetSw, destSw1,
922 nextHops.get(destSw1),
923 dest1RouterIpv4);
924 if (!result) {
925 return false;
926 }
927
928 if (dest1RouterIpv6 != null) {
929 int v4sid = 0, v6sid = 0;
930 try {
931 v4sid = config.getIPv4SegmentId(destSw1);
932 v6sid = config.getIPv6SegmentId(destSw1);
933 } catch (DeviceConfigNotFoundException e) {
934 log.warn(e.getMessage());
935 }
936 if (v4sid != v6sid) {
937 result = rulePopulator.populateMplsRule(targetSw, destSw1,
938 nextHops.get(destSw1),
939 dest1RouterIpv6);
940 if (!result) {
941 return false;
942 }
943 }
944 }
945 }
946
947
Saurav Das261c3002017-06-13 15:35:54 -0700948 // To save on ECMP groups
949 // avoid MPLS rules in non-edge-devices to non-edge-devices
950 // avoid MPLS transit rules in edge-devices
951 // avoid loopback IP rules in edge-devices to non-edge-devices
952 return true;
Saurav Das62ae6792017-05-15 15:34:25 -0700953 }
954
955 /**
956 * Processes a set a route-path changes by editing hash groups.
957 *
958 * @param routeChanges a set of route-path changes, where each route-path is
959 * a list with its first element the src-switch of the path
960 * and the second element the dst-switch of the path.
961 * @param linkOrSwitchFailed true if the route changes are for a failed
962 * switch or linkDown event
963 * @param failedSwitch the switchId if the route changes are for a failed switch,
964 * otherwise null
965 */
966 private void processHashGroupChange(Set<ArrayList<DeviceId>> routeChanges,
967 boolean linkOrSwitchFailed,
968 DeviceId failedSwitch) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700969 Set<ArrayList<DeviceId>> changedRoutes = new HashSet<>();
970 // first, ensure each routeChanges entry has two elements
Saurav Das62ae6792017-05-15 15:34:25 -0700971 for (ArrayList<DeviceId> route : routeChanges) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700972 if (route.size() == 1) {
973 // route-path changes are from everyone else to this switch
974 DeviceId dstSw = route.get(0);
975 srManager.deviceService.getAvailableDevices().forEach(sw -> {
976 if (!sw.id().equals(dstSw)) {
977 changedRoutes.add(Lists.newArrayList(sw.id(), dstSw));
978 }
979 });
980 } else {
981 changedRoutes.add(route);
Saurav Das62ae6792017-05-15 15:34:25 -0700982 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700983 }
Saurav Das6430f412018-01-25 09:49:01 -0800984 boolean someFailed = false;
985 Set<DeviceId> updatedDevices = Sets.newHashSet();
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700986 for (ArrayList<DeviceId> route : changedRoutes) {
987 DeviceId targetSw = route.get(0);
988 DeviceId dstSw = route.get(1);
Saurav Das62ae6792017-05-15 15:34:25 -0700989 if (linkOrSwitchFailed) {
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700990 boolean success = fixHashGroupsForRoute(route, true);
Saurav Das62ae6792017-05-15 15:34:25 -0700991 // it's possible that we cannot fix hash groups for a route
992 // if the target switch has failed. Nevertheless the ecmp graph
993 // for the impacted switch must still be updated.
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700994 if (!success && failedSwitch != null && targetSw.equals(failedSwitch)) {
Saurav Das62ae6792017-05-15 15:34:25 -0700995 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
996 currentEcmpSpgMap.remove(targetSw);
Saurav Dasfe0b05e2017-08-14 16:44:43 -0700997 log.debug("Updating ECMPspg for dst:{} removing failed switch "
Saurav Das62ae6792017-05-15 15:34:25 -0700998 + "target:{}", dstSw, targetSw);
Saurav Das6430f412018-01-25 09:49:01 -0800999 updatedDevices.add(targetSw);
1000 updatedDevices.add(dstSw);
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001001 continue;
Saurav Das62ae6792017-05-15 15:34:25 -07001002 }
1003 //linkfailed - update both sides
Saurav Das62ae6792017-05-15 15:34:25 -07001004 if (success) {
1005 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001006 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
Saurav Das6430f412018-01-25 09:49:01 -08001007 log.debug("Updating ECMPspg for dst:{} and target:{} for linkdown"
1008 + " or switchdown", dstSw, targetSw);
1009 updatedDevices.add(targetSw);
1010 updatedDevices.add(dstSw);
1011 } else {
1012 someFailed = true;
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001013 }
1014 } else {
1015 //linkup of seen before link
1016 boolean success = fixHashGroupsForRoute(route, false);
1017 if (success) {
1018 currentEcmpSpgMap.put(targetSw, updatedEcmpSpgMap.get(targetSw));
1019 currentEcmpSpgMap.put(dstSw, updatedEcmpSpgMap.get(dstSw));
1020 log.debug("Updating ECMPspg for target:{} and dst:{} for linkup",
Saurav Das62ae6792017-05-15 15:34:25 -07001021 targetSw, dstSw);
Saurav Das6430f412018-01-25 09:49:01 -08001022 updatedDevices.add(targetSw);
1023 updatedDevices.add(dstSw);
1024 } else {
1025 someFailed = true;
Saurav Das62ae6792017-05-15 15:34:25 -07001026 }
1027 }
1028 }
Saurav Das6430f412018-01-25 09:49:01 -08001029 if (!someFailed) {
1030 // here is where we update all devices not touched by this instance
1031 updatedEcmpSpgMap.keySet().stream()
1032 .filter(devId -> !updatedDevices.contains(devId))
1033 .forEach(devId -> {
1034 currentEcmpSpgMap.put(devId, updatedEcmpSpgMap.get(devId));
1035 log.debug("Updating ECMPspg for remaining dev:{}", devId);
1036 });
1037 }
Saurav Das62ae6792017-05-15 15:34:25 -07001038 }
1039
1040 /**
1041 * Edits hash groups in the src-switch (targetSw) of a route-path by
1042 * calling the groupHandler to either add or remove buckets in an existing
1043 * hash group.
1044 *
1045 * @param route a single list representing a route-path where the first element
1046 * is the src-switch (targetSw) of the route-path and the
1047 * second element is the dst-switch
1048 * @param revoke true if buckets in the hash-groups need to be removed;
1049 * false if buckets in the hash-groups need to be added
1050 * @return true if the hash group editing is successful
1051 */
1052 private boolean fixHashGroupsForRoute(ArrayList<DeviceId> route,
1053 boolean revoke) {
1054 DeviceId targetSw = route.get(0);
1055 if (route.size() < 2) {
1056 log.warn("Cannot fixHashGroupsForRoute - no dstSw in route {}", route);
1057 return false;
1058 }
1059 DeviceId destSw = route.get(1);
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001060 log.debug("* processing fixHashGroupsForRoute: Target {} -> Dest {}",
Saurav Das62ae6792017-05-15 15:34:25 -07001061 targetSw, destSw);
Saurav Das62ae6792017-05-15 15:34:25 -07001062 // figure out the new next hops at the targetSw towards the destSw
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001063 Set<DeviceId> nextHops = getNextHops(targetSw, destSw);
Saurav Das62ae6792017-05-15 15:34:25 -07001064 // call group handler to change hash group at targetSw
1065 DefaultGroupHandler grpHandler = srManager.getGroupHandler(targetSw);
1066 if (grpHandler == null) {
1067 log.warn("Cannot find grouphandler for dev:{} .. aborting"
1068 + " {} hash group buckets for route:{} ", targetSw,
1069 (revoke) ? "revoke" : "repopulate", route);
1070 return false;
1071 }
1072 log.debug("{} hash-groups buckets For Route {} -> {} to next-hops {}",
1073 (revoke) ? "revoke" : "repopulating",
1074 targetSw, destSw, nextHops);
1075 return (revoke) ? grpHandler.fixHashGroups(targetSw, nextHops,
1076 destSw, true)
1077 : grpHandler.fixHashGroups(targetSw, nextHops,
1078 destSw, false);
1079 }
1080
1081 /**
Saurav Das261c3002017-06-13 15:35:54 -07001082 * Start the flow rule population process if it was never started. The
1083 * process finishes successfully when all flow rules are set and stops with
1084 * ABORTED status when any groups required for flows is not set yet.
Saurav Das62ae6792017-05-15 15:34:25 -07001085 */
Saurav Das261c3002017-06-13 15:35:54 -07001086 public void startPopulationProcess() {
1087 statusLock.lock();
1088 try {
1089 if (populationStatus == Status.IDLE
1090 || populationStatus == Status.SUCCEEDED
1091 || populationStatus == Status.ABORTED) {
1092 populateAllRoutingRules();
sangho28d0b6d2015-05-07 13:30:57 -07001093 } else {
Saurav Das261c3002017-06-13 15:35:54 -07001094 log.warn("Not initiating startPopulationProcess as populationStatus is {}",
1095 populationStatus);
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001096 }
Saurav Das261c3002017-06-13 15:35:54 -07001097 } finally {
1098 statusLock.unlock();
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001099 }
sanghofb7c7292015-04-13 15:15:58 -07001100 }
1101
Saurav Dasb149be12016-06-07 10:08:06 -07001102 /**
Saurav Das261c3002017-06-13 15:35:54 -07001103 * Revoke rules of given subnet in all edge switches.
1104 *
1105 * @param subnets subnet being removed
1106 * @return true if succeed
1107 */
1108 protected boolean revokeSubnet(Set<IpPrefix> subnets) {
1109 statusLock.lock();
1110 try {
Charles Chand66d6712018-03-29 16:03:41 -07001111 return Sets.newHashSet(srManager.deviceService.getAvailableDevices()).stream()
1112 .map(Device::id)
1113 .filter(this::shouldProgram)
1114 .allMatch(targetSw -> srManager.routingRulePopulator.revokeIpRuleForSubnet(targetSw, subnets));
Saurav Das261c3002017-06-13 15:35:54 -07001115 } finally {
1116 statusLock.unlock();
1117 }
1118 }
1119
1120 /**
Charles Chan910be6a2017-08-23 14:46:43 -07001121 * Populates IP rules for a route that has direct connection to the switch
1122 * if the current instance is the master of the switch.
1123 *
1124 * @param deviceId device ID of the device that next hop attaches to
1125 * @param prefix IP prefix of the route
1126 * @param hostMac MAC address of the next hop
1127 * @param hostVlanId Vlan ID of the nexthop
1128 * @param outPort port where the next hop attaches to
1129 */
1130 void populateRoute(DeviceId deviceId, IpPrefix prefix,
1131 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
Charles Chand66d6712018-03-29 16:03:41 -07001132 if (shouldProgram(deviceId)) {
Charles Chan910be6a2017-08-23 14:46:43 -07001133 srManager.routingRulePopulator.populateRoute(deviceId, prefix, hostMac, hostVlanId, outPort);
1134 }
1135 }
1136
1137 /**
1138 * Removes IP rules for a route when the next hop is gone.
1139 * if the current instance is the master of the switch.
1140 *
1141 * @param deviceId device ID of the device that next hop attaches to
1142 * @param prefix IP prefix of the route
1143 * @param hostMac MAC address of the next hop
1144 * @param hostVlanId Vlan ID of the nexthop
1145 * @param outPort port that next hop attaches to
1146 */
1147 void revokeRoute(DeviceId deviceId, IpPrefix prefix,
1148 MacAddress hostMac, VlanId hostVlanId, PortNumber outPort) {
Charles Chand66d6712018-03-29 16:03:41 -07001149 if (shouldProgram(deviceId)) {
Charles Chan910be6a2017-08-23 14:46:43 -07001150 srManager.routingRulePopulator.revokeRoute(deviceId, prefix, hostMac, hostVlanId, outPort);
1151 }
1152 }
1153
Charles Chand66d6712018-03-29 16:03:41 -07001154 void populateBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
1155 if (shouldProgram(deviceId)) {
1156 srManager.routingRulePopulator.populateBridging(deviceId, port, mac, vlanId);
1157 }
1158 }
1159
1160 void revokeBridging(DeviceId deviceId, PortNumber port, MacAddress mac, VlanId vlanId) {
1161 if (shouldProgram(deviceId)) {
1162 srManager.routingRulePopulator.revokeBridging(deviceId, port, mac, vlanId);
1163 }
1164 }
1165
1166 void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
1167 VlanId vlanId, boolean popVlan, boolean install) {
1168 if (shouldProgram(deviceId)) {
1169 srManager.routingRulePopulator.updateBridging(deviceId, portNum, hostMac, vlanId, popVlan, install);
1170 }
1171 }
1172
1173 void updateFwdObj(DeviceId deviceId, PortNumber portNumber, IpPrefix prefix, MacAddress hostMac,
1174 VlanId vlanId, boolean popVlan, boolean install) {
1175 if (shouldProgram(deviceId)) {
1176 srManager.routingRulePopulator.updateFwdObj(deviceId, portNumber, prefix, hostMac,
1177 vlanId, popVlan, install);
1178 }
1179 }
1180
Charles Chan910be6a2017-08-23 14:46:43 -07001181 /**
Saurav Das261c3002017-06-13 15:35:54 -07001182 * Remove ECMP graph entry for the given device. Typically called when
1183 * device is no longer available.
1184 *
1185 * @param deviceId the device for which graphs need to be purged
1186 */
Charles Chanfbcb8812018-04-18 18:41:05 -07001187 void purgeEcmpGraph(DeviceId deviceId) {
Saurav Das6430f412018-01-25 09:49:01 -08001188 statusLock.lock();
1189 try {
1190
1191 if (populationStatus == Status.STARTED) {
1192 log.warn("Previous rule population is not finished. Cannot"
1193 + " proceeed with purgeEcmpGraph for {}", deviceId);
1194 return;
1195 }
1196 log.debug("Updating ECMPspg for unavailable dev:{}", deviceId);
1197 currentEcmpSpgMap.remove(deviceId);
1198 if (updatedEcmpSpgMap != null) {
1199 updatedEcmpSpgMap.remove(deviceId);
1200 }
1201 } finally {
1202 statusLock.unlock();
Saurav Das261c3002017-06-13 15:35:54 -07001203 }
1204 }
1205
Saurav Das00e553b2018-04-21 17:19:48 -07001206 /**
1207 * Attempts a full reroute of route-paths if topology has changed relatively
1208 * close to a mastership change event. Does not do a reroute if mastership
1209 * change is due to reasons other than a ONOS cluster event - for example a
1210 * call to balance-masters, or a switch up/down event.
1211 *
1212 * @param devId the device identifier for which mastership has changed
1213 * @param me the mastership event
1214 */
1215 void checkFullRerouteForMasterChange(DeviceId devId, MastershipEvent me) {
1216 // give small delay to absorb mastership events that are caused by
1217 // device that has disconnected from cluster
Saurav Das49368392018-04-23 18:42:12 -07001218 executorServiceMstChg.schedule(new MasterChange(devId, me),
1219 MASTER_CHANGE_DELAY, TimeUnit.MILLISECONDS);
Saurav Das00e553b2018-04-21 17:19:48 -07001220 }
1221
1222 protected final class MasterChange implements Runnable {
1223 private DeviceId devId;
1224 private MastershipEvent me;
1225 private static final long CLUSTER_EVENT_THRESHOLD = 4500; // ms
1226 private static final long DEVICE_EVENT_THRESHOLD = 2000; // ms
1227
1228 MasterChange(DeviceId devId, MastershipEvent me) {
1229 this.devId = devId;
1230 this.me = me;
1231 }
1232
1233 @Override
1234 public void run() {
1235 long lce = srManager.clusterListener.timeSinceLastClusterEvent();
1236 boolean clusterEvent = lce < CLUSTER_EVENT_THRESHOLD;
1237
1238 // ignore event for lost switch if cluster event hasn't happened -
1239 // device down event will handle it
1240 if ((me.roleInfo().master() == null
1241 || !srManager.deviceService.isAvailable(devId))
1242 && !clusterEvent) {
1243 log.debug("Full reroute not required for lost device: {}/{} "
1244 + "clusterEvent/timeSince: {}/{}",
1245 devId, me.roleInfo(), clusterEvent, lce);
1246 return;
1247 }
1248
1249 long update = srManager.deviceService.getLastUpdatedInstant(devId);
1250 long lde = Instant.now().toEpochMilli() - update;
1251 boolean deviceEvent = lde < DEVICE_EVENT_THRESHOLD;
1252
1253 // ignore event for recently connected switch if cluster event hasn't
1254 // happened - link up events will handle it
1255 if (srManager.deviceService.isAvailable(devId) && deviceEvent
1256 && !clusterEvent) {
1257 log.debug("Full reroute not required for recently available"
1258 + " device: {}/{} deviceEvent/timeSince: {}/{} "
1259 + "clusterEvent/timeSince: {}/{}",
1260 devId, me.roleInfo(), deviceEvent, lde, clusterEvent, lce);
1261 return;
1262 }
1263
1264 // if it gets here, then mastership change is likely due to onos
1265 // instance failure, or network partition in onos cluster
1266 // normally a mastership change like this does not require re-programming
1267 // but if topology changes happen at the same time then we may miss events
1268 if (!isRoutingStable() && clusterEvent) {
1269 log.warn("Mastership changed for dev: {}/{} while programming "
1270 + "due to clusterEvent {} ms ago .. attempting full reroute",
1271 devId, me.roleInfo(), lce);
1272 if (srManager.mastershipService.isLocalMaster(devId)) {
1273 // old master could have died when populating filters
1274 populatePortAddressingRules(devId);
Saurav Das49368392018-04-23 18:42:12 -07001275 // old master could have died when creating groups
1276 srManager.purgeHashedNextObjectiveStore(devId);
Saurav Das00e553b2018-04-21 17:19:48 -07001277 }
Saurav Das00e553b2018-04-21 17:19:48 -07001278 // XXX right now we have no fine-grained way to only make changes
1279 // for the route paths affected by this device.
1280 populateAllRoutingRules();
1281 } else {
1282 log.debug("Stable route-paths .. full reroute not attempted for "
1283 + "mastership change {}/{} deviceEvent/timeSince: {}/{} "
1284 + "clusterEvent/timeSince: {}/{}", devId, me.roleInfo(),
1285 deviceEvent, lde, clusterEvent, lce);
1286 }
1287 }
1288 }
1289
Saurav Das261c3002017-06-13 15:35:54 -07001290 //////////////////////////////////////
1291 // Routing helper methods and classes
1292 //////////////////////////////////////
1293
1294 /**
Saurav Das1b391d52016-11-29 14:27:25 -08001295 * Computes set of affected routes due to failed link. Assumes
Saurav Dasb149be12016-06-07 10:08:06 -07001296 * previous ecmp shortest-path graph exists for a switch in order to compute
1297 * affected routes. If such a graph does not exist, the method returns null.
1298 *
1299 * @param linkFail the failed link
1300 * @return the set of affected routes which may be empty if no routes were
1301 * affected, or null if no previous ecmp spg was found for comparison
1302 */
sanghofb7c7292015-04-13 15:15:58 -07001303 private Set<ArrayList<DeviceId>> computeDamagedRoutes(Link linkFail) {
sanghofb7c7292015-04-13 15:15:58 -07001304 Set<ArrayList<DeviceId>> routes = new HashSet<>();
1305
1306 for (Device sw : srManager.deviceService.getDevices()) {
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001307 log.debug("Computing the impacted routes for device {} due to link fail",
1308 sw.id());
Charles Chand66d6712018-03-29 16:03:41 -07001309 if (!shouldProgram(sw.id())) {
Saurav Das00e553b2018-04-21 17:19:48 -07001310 lastProgrammed.remove(sw.id());
sanghofb7c7292015-04-13 15:15:58 -07001311 continue;
1312 }
Charles Chand66d6712018-03-29 16:03:41 -07001313 for (DeviceId rootSw : deviceAndItsPair(sw.id())) {
Saurav Das00e553b2018-04-21 17:19:48 -07001314 // check for mastership change since last run
1315 if (!lastProgrammed.contains(sw.id())) {
1316 lastProgrammed.add(sw.id());
1317 log.warn("New reponsibility for this node to program dev:{}"
1318 + " ... nuking current ECMPspg", sw.id());
1319 currentEcmpSpgMap.remove(sw.id());
1320 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001321 EcmpShortestPathGraph ecmpSpg = currentEcmpSpgMap.get(rootSw);
1322 if (ecmpSpg == null) {
1323 log.warn("No existing ECMP graph for switch {}. Aborting optimized"
1324 + " rerouting and opting for full-reroute", rootSw);
1325 return null;
1326 }
1327 if (log.isDebugEnabled()) {
1328 log.debug("Root switch: {}", rootSw);
1329 log.debug(" Current/Existing SPG: {}", ecmpSpg);
1330 log.debug(" New/Updated SPG: {}", updatedEcmpSpgMap.get(rootSw));
1331 }
1332 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>>
1333 switchVia = ecmpSpg.getAllLearnedSwitchesAndVia();
1334 // figure out if the broken link affected any route-paths in this graph
1335 for (Integer itrIdx : switchVia.keySet()) {
1336 log.trace("Current/Exiting SPG Iterindex# {}", itrIdx);
1337 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1338 switchVia.get(itrIdx);
1339 for (DeviceId targetSw : swViaMap.keySet()) {
1340 log.trace("TargetSwitch {} --> RootSwitch {}",
1341 targetSw, rootSw);
Saurav Dasb149be12016-06-07 10:08:06 -07001342 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1343 log.trace(" Via:");
Pier Ventreadb4ae62016-11-23 09:57:42 -08001344 via.forEach(e -> log.trace(" {}", e));
Saurav Dasb149be12016-06-07 10:08:06 -07001345 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001346 Set<ArrayList<DeviceId>> subLinks =
1347 computeLinks(targetSw, rootSw, swViaMap);
1348 for (ArrayList<DeviceId> alink: subLinks) {
1349 if ((alink.get(0).equals(linkFail.src().deviceId()) &&
1350 alink.get(1).equals(linkFail.dst().deviceId()))
1351 ||
1352 (alink.get(0).equals(linkFail.dst().deviceId()) &&
1353 alink.get(1).equals(linkFail.src().deviceId()))) {
1354 log.debug("Impacted route:{}->{}", targetSw, rootSw);
1355 ArrayList<DeviceId> aRoute = new ArrayList<>();
1356 aRoute.add(targetSw); // switch with rules to populate
1357 aRoute.add(rootSw); // towards this destination
1358 routes.add(aRoute);
1359 break;
1360 }
sanghofb7c7292015-04-13 15:15:58 -07001361 }
1362 }
1363 }
Saurav Dasfe0b05e2017-08-14 16:44:43 -07001364
sanghofb7c7292015-04-13 15:15:58 -07001365 }
sangho28d0b6d2015-05-07 13:30:57 -07001366
sanghofb7c7292015-04-13 15:15:58 -07001367 }
sanghofb7c7292015-04-13 15:15:58 -07001368 return routes;
1369 }
1370
Saurav Das1b391d52016-11-29 14:27:25 -08001371 /**
1372 * Computes set of affected routes due to new links or failed switches.
1373 *
Saurav Dasdc7f2752018-03-18 21:28:15 -07001374 * @param failedSwitch deviceId of failed switch if any
Saurav Das1b391d52016-11-29 14:27:25 -08001375 * @return the set of affected routes which may be empty if no routes were
1376 * affected
1377 */
Saurav Dascea556f2018-03-05 14:37:16 -08001378 private Set<ArrayList<DeviceId>> computeRouteChange(DeviceId failedSwitch) {
Saurav Das261c3002017-06-13 15:35:54 -07001379 ImmutableSet.Builder<ArrayList<DeviceId>> changedRtBldr =
Saurav Das1b391d52016-11-29 14:27:25 -08001380 ImmutableSet.builder();
sanghofb7c7292015-04-13 15:15:58 -07001381
1382 for (Device sw : srManager.deviceService.getDevices()) {
Saurav Das261c3002017-06-13 15:35:54 -07001383 log.debug("Computing the impacted routes for device {}", sw.id());
Charles Chand66d6712018-03-29 16:03:41 -07001384 if (!shouldProgram(sw.id())) {
Saurav Das00e553b2018-04-21 17:19:48 -07001385 lastProgrammed.remove(sw.id());
sanghofb7c7292015-04-13 15:15:58 -07001386 continue;
1387 }
Charles Chand66d6712018-03-29 16:03:41 -07001388 for (DeviceId rootSw : deviceAndItsPair(sw.id())) {
Saurav Das261c3002017-06-13 15:35:54 -07001389 if (log.isTraceEnabled()) {
1390 log.trace("Device links for dev: {}", rootSw);
1391 for (Link link: srManager.linkService.getDeviceLinks(rootSw)) {
1392 log.trace("{} -> {} ", link.src().deviceId(),
1393 link.dst().deviceId());
1394 }
Saurav Dasb149be12016-06-07 10:08:06 -07001395 }
Saurav Das00e553b2018-04-21 17:19:48 -07001396 // check for mastership change since last run
1397 if (!lastProgrammed.contains(sw.id())) {
1398 lastProgrammed.add(sw.id());
1399 log.warn("New reponsibility for this node to program dev:{}"
1400 + " ... nuking current ECMPspg", sw.id());
1401 currentEcmpSpgMap.remove(sw.id());
1402 }
Saurav Das261c3002017-06-13 15:35:54 -07001403 EcmpShortestPathGraph currEcmpSpg = currentEcmpSpgMap.get(rootSw);
1404 if (currEcmpSpg == null) {
1405 log.debug("No existing ECMP graph for device {}.. adding self as "
1406 + "changed route", rootSw);
1407 changedRtBldr.add(Lists.newArrayList(rootSw));
1408 continue;
1409 }
1410 EcmpShortestPathGraph newEcmpSpg = updatedEcmpSpgMap.get(rootSw);
Saurav Dasdebcf882018-04-06 20:16:01 -07001411 if (newEcmpSpg == null) {
1412 log.warn("Cannot find updated ECMP graph for dev:{}", rootSw);
1413 continue;
1414 }
Saurav Das261c3002017-06-13 15:35:54 -07001415 if (log.isDebugEnabled()) {
1416 log.debug("Root switch: {}", rootSw);
1417 log.debug(" Current/Existing SPG: {}", currEcmpSpg);
1418 log.debug(" New/Updated SPG: {}", newEcmpSpg);
1419 }
1420 // first use the updated/new map to compare to current/existing map
1421 // as new links may have come up
1422 changedRtBldr.addAll(compareGraphs(newEcmpSpg, currEcmpSpg, rootSw));
1423 // then use the current/existing map to compare to updated/new map
1424 // as switch may have been removed
1425 changedRtBldr.addAll(compareGraphs(currEcmpSpg, newEcmpSpg, rootSw));
sangho28d0b6d2015-05-07 13:30:57 -07001426 }
Saurav Das1b391d52016-11-29 14:27:25 -08001427 }
sanghofb7c7292015-04-13 15:15:58 -07001428
Saurav Dascea556f2018-03-05 14:37:16 -08001429 // handle clearing state for a failed switch in case the switch does
1430 // not have a pair, or the pair is not available
1431 if (failedSwitch != null) {
Charles Chan6dbcd252018-04-02 11:46:38 -07001432 Optional<DeviceId> pairDev = srManager.getPairDeviceId(failedSwitch);
1433 if (!pairDev.isPresent() || !srManager.deviceService.isAvailable(pairDev.get())) {
Saurav Dascea556f2018-03-05 14:37:16 -08001434 log.debug("Proxy Route changes to downed Sw:{}", failedSwitch);
1435 srManager.deviceService.getDevices().forEach(dev -> {
1436 if (!dev.id().equals(failedSwitch) &&
1437 srManager.mastershipService.isLocalMaster(dev.id())) {
1438 log.debug(" : {}", dev.id());
1439 changedRtBldr.add(Lists.newArrayList(dev.id(), failedSwitch));
1440 }
1441 });
1442 }
1443 }
1444
Saurav Das261c3002017-06-13 15:35:54 -07001445 Set<ArrayList<DeviceId>> changedRoutes = changedRtBldr.build();
Saurav Das1b391d52016-11-29 14:27:25 -08001446 for (ArrayList<DeviceId> route: changedRoutes) {
1447 log.debug("Route changes Target -> Root");
1448 if (route.size() == 1) {
1449 log.debug(" : all -> {}", route.get(0));
1450 } else {
1451 log.debug(" : {} -> {}", route.get(0), route.get(1));
1452 }
1453 }
1454 return changedRoutes;
1455 }
1456
1457 /**
1458 * For the root switch, searches all the target nodes reachable in the base
1459 * graph, and compares paths to the ones in the comp graph.
1460 *
1461 * @param base the graph that is indexed for all reachable target nodes
1462 * from the root node
1463 * @param comp the graph that the base graph is compared to
1464 * @param rootSw both ecmp graphs are calculated for the root node
1465 * @return all the routes that have changed in the base graph
1466 */
1467 private Set<ArrayList<DeviceId>> compareGraphs(EcmpShortestPathGraph base,
1468 EcmpShortestPathGraph comp,
1469 DeviceId rootSw) {
1470 ImmutableSet.Builder<ArrayList<DeviceId>> changedRoutesBuilder =
1471 ImmutableSet.builder();
1472 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> baseMap =
1473 base.getAllLearnedSwitchesAndVia();
1474 HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> compMap =
1475 comp.getAllLearnedSwitchesAndVia();
1476 for (Integer itrIdx : baseMap.keySet()) {
1477 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> baseViaMap =
1478 baseMap.get(itrIdx);
1479 for (DeviceId targetSw : baseViaMap.keySet()) {
1480 ArrayList<ArrayList<DeviceId>> basePath = baseViaMap.get(targetSw);
1481 ArrayList<ArrayList<DeviceId>> compPath = getVia(compMap, targetSw);
1482 if ((compPath == null) || !basePath.equals(compPath)) {
Saurav Das62ae6792017-05-15 15:34:25 -07001483 log.trace("Impacted route:{} -> {}", targetSw, rootSw);
Saurav Das1b391d52016-11-29 14:27:25 -08001484 ArrayList<DeviceId> route = new ArrayList<>();
Saurav Das261c3002017-06-13 15:35:54 -07001485 route.add(targetSw); // switch with rules to populate
1486 route.add(rootSw); // towards this destination
Saurav Das1b391d52016-11-29 14:27:25 -08001487 changedRoutesBuilder.add(route);
sanghofb7c7292015-04-13 15:15:58 -07001488 }
1489 }
sangho28d0b6d2015-05-07 13:30:57 -07001490 }
Saurav Das1b391d52016-11-29 14:27:25 -08001491 return changedRoutesBuilder.build();
sanghofb7c7292015-04-13 15:15:58 -07001492 }
1493
Saurav Das261c3002017-06-13 15:35:54 -07001494 /**
1495 * Returns the ECMP paths traversed to reach the target switch.
1496 *
1497 * @param switchVia a per-iteration view of the ECMP graph for a root switch
1498 * @param targetSw the switch to reach from the root switch
1499 * @return the nodes traversed on ECMP paths to the target switch
1500 */
sanghofb7c7292015-04-13 15:15:58 -07001501 private ArrayList<ArrayList<DeviceId>> getVia(HashMap<Integer, HashMap<DeviceId,
Saurav Das1b391d52016-11-29 14:27:25 -08001502 ArrayList<ArrayList<DeviceId>>>> switchVia, DeviceId targetSw) {
sanghofb7c7292015-04-13 15:15:58 -07001503 for (Integer itrIdx : switchVia.keySet()) {
1504 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1505 switchVia.get(itrIdx);
Saurav Das1b391d52016-11-29 14:27:25 -08001506 if (swViaMap.get(targetSw) == null) {
sanghofb7c7292015-04-13 15:15:58 -07001507 continue;
1508 } else {
Saurav Das1b391d52016-11-29 14:27:25 -08001509 return swViaMap.get(targetSw);
sanghofb7c7292015-04-13 15:15:58 -07001510 }
1511 }
1512
Srikanth Vavilapalli64d96c12015-05-14 20:22:47 -07001513 return null;
sanghofb7c7292015-04-13 15:15:58 -07001514 }
1515
Saurav Das261c3002017-06-13 15:35:54 -07001516 /**
1517 * Utility method to break down a path from src to dst device into a collection
1518 * of links.
1519 *
1520 * @param src src device of the path
1521 * @param dst dst device of the path
1522 * @param viaMap path taken from src to dst device
1523 * @return collection of links in the path
1524 */
sanghofb7c7292015-04-13 15:15:58 -07001525 private Set<ArrayList<DeviceId>> computeLinks(DeviceId src,
1526 DeviceId dst,
1527 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> viaMap) {
1528 Set<ArrayList<DeviceId>> subLinks = Sets.newHashSet();
1529 for (ArrayList<DeviceId> via : viaMap.get(src)) {
1530 DeviceId linkSrc = src;
1531 DeviceId linkDst = dst;
1532 for (DeviceId viaDevice: via) {
1533 ArrayList<DeviceId> link = new ArrayList<>();
1534 linkDst = viaDevice;
1535 link.add(linkSrc);
1536 link.add(linkDst);
1537 subLinks.add(link);
1538 linkSrc = viaDevice;
1539 }
1540 ArrayList<DeviceId> link = new ArrayList<>();
1541 link.add(linkSrc);
1542 link.add(dst);
1543 subLinks.add(link);
1544 }
1545
1546 return subLinks;
1547 }
1548
Charles Chanc22cef32016-04-29 14:38:22 -07001549 /**
Charles Chand66d6712018-03-29 16:03:41 -07001550 * Determines whether this controller instance should program the
Saurav Das261c3002017-06-13 15:35:54 -07001551 * given {@code deviceId}, based on mastership and pairDeviceId if one exists.
Charles Chand66d6712018-03-29 16:03:41 -07001552 * <p>
1553 * Once an instance is elected, it will be the only instance responsible for programming
1554 * both devices in the pair until it goes down.
Charles Chanc22cef32016-04-29 14:38:22 -07001555 *
Saurav Das261c3002017-06-13 15:35:54 -07001556 * @param deviceId device identifier to consider for routing
Charles Chand66d6712018-03-29 16:03:41 -07001557 * @return true if current instance should handle the routing for given device
Charles Chanc22cef32016-04-29 14:38:22 -07001558 */
Charles Chand66d6712018-03-29 16:03:41 -07001559 boolean shouldProgram(DeviceId deviceId) {
Charles Chanfbcb8812018-04-18 18:41:05 -07001560 Boolean cached = shouldProgramCache.get(deviceId);
1561 if (cached != null) {
Saurav Das00e553b2018-04-21 17:19:48 -07001562 log.debug("shouldProgram dev:{} cached:{}", deviceId, cached);
Charles Chanfbcb8812018-04-18 18:41:05 -07001563 return cached;
1564 }
1565
Charles Chand66d6712018-03-29 16:03:41 -07001566 Optional<DeviceId> pairDeviceId = srManager.getPairDeviceId(deviceId);
sangho80f11cb2015-04-01 13:05:26 -07001567
Charles Chand66d6712018-03-29 16:03:41 -07001568 NodeId currentNodeId = srManager.clusterService.getLocalNode().id();
1569 NodeId masterNodeId = srManager.mastershipService.getMasterFor(deviceId);
1570 Optional<NodeId> pairMasterNodeId = pairDeviceId.map(srManager.mastershipService::getMasterFor);
1571 log.debug("Evaluate shouldProgram {}/pair={}. current={}, master={}, pairMaster={}",
1572 deviceId, pairDeviceId, currentNodeId, masterNodeId, pairMasterNodeId);
1573
1574 // No pair device configured. Only handle when current instance is the master of the device
1575 if (!pairDeviceId.isPresent()) {
1576 log.debug("No pair device. current={}, master={}", currentNodeId, masterNodeId);
1577 return currentNodeId.equals(masterNodeId);
sangho80f11cb2015-04-01 13:05:26 -07001578 }
Charles Chand66d6712018-03-29 16:03:41 -07001579
1580 // Should not handle if current instance is not the master of either switch
1581 if (!currentNodeId.equals(masterNodeId) &&
1582 !(pairMasterNodeId.isPresent() && currentNodeId.equals(pairMasterNodeId.get()))) {
1583 log.debug("Current node {} is neither the master of target device {} nor pair device {}",
1584 currentNodeId, deviceId, pairDeviceId);
1585 return false;
1586 }
1587
1588 Set<DeviceId> key = Sets.newHashSet(deviceId, pairDeviceId.get());
1589
1590 NodeId king = shouldProgram.compute(key, ((k, v) -> {
1591 if (v == null) {
1592 // There is no value in the map. Elect a node
1593 return elect(Lists.newArrayList(masterNodeId, pairMasterNodeId.orElse(null)));
1594 } else {
1595 if (v.equals(masterNodeId) || v.equals(pairMasterNodeId.orElse(null))) {
1596 // Use the node in the map if it is still alive and is a master of any of the two switches
1597 return v;
1598 } else {
1599 // Previously elected node is no longer the master of either switch. Re-elect a node.
1600 return elect(Lists.newArrayList(masterNodeId, pairMasterNodeId.orElse(null)));
1601 }
1602 }
1603 }));
1604
1605 if (king != null) {
1606 log.debug("{} should handle routing for {}/pair={}", king, deviceId, pairDeviceId);
Charles Chanfbcb8812018-04-18 18:41:05 -07001607 shouldProgramCache.put(deviceId, king.equals(currentNodeId));
Charles Chand66d6712018-03-29 16:03:41 -07001608 return king.equals(currentNodeId);
1609 } else {
1610 log.error("Fail to elect a king for {}/pair={}. Abort.", deviceId, pairDeviceId);
Charles Chanfbcb8812018-04-18 18:41:05 -07001611 shouldProgramCache.remove(deviceId);
Charles Chand66d6712018-03-29 16:03:41 -07001612 return false;
1613 }
1614 }
1615
1616 /**
1617 * Elects a node who should take responsibility of programming devices.
1618 * @param nodeIds list of candidate node ID
1619 *
1620 * @return NodeId of the node that gets elected, or null if none of the node can be elected
1621 */
1622 private NodeId elect(List<NodeId> nodeIds) {
1623 // Remove all null elements. This could happen when some device has no master
1624 nodeIds.removeAll(Collections.singleton(null));
1625 nodeIds.sort(null);
1626 return nodeIds.size() == 0 ? null : nodeIds.get(0);
1627 }
1628
Charles Chanfbcb8812018-04-18 18:41:05 -07001629 void invalidateShouldProgramCache(DeviceId deviceId) {
1630 shouldProgramCache.remove(deviceId);
1631 }
1632
Charles Chand66d6712018-03-29 16:03:41 -07001633 /**
1634 * Returns a set of device ID, containing given device and its pair device if exist.
1635 *
1636 * @param deviceId Device ID
1637 * @return a set of device ID, containing given device and its pair device if exist.
1638 */
1639 private Set<DeviceId> deviceAndItsPair(DeviceId deviceId) {
1640 Set<DeviceId> ret = Sets.newHashSet(deviceId);
1641 srManager.getPairDeviceId(deviceId).ifPresent(ret::add);
1642 return ret;
sangho80f11cb2015-04-01 13:05:26 -07001643 }
1644
Charles Chanc22cef32016-04-29 14:38:22 -07001645 /**
Saurav Das261c3002017-06-13 15:35:54 -07001646 * Returns the set of deviceIds which are the next hops from the targetSw
1647 * to the dstSw according to the latest ECMP spg.
1648 *
1649 * @param targetSw the switch for which the next-hops are desired
1650 * @param dstSw the switch to which the next-hops lead to from the targetSw
1651 * @return set of next hop deviceIds, could be empty if no next hops are found
1652 */
1653 private Set<DeviceId> getNextHops(DeviceId targetSw, DeviceId dstSw) {
1654 boolean targetIsEdge = false;
1655 try {
1656 targetIsEdge = srManager.deviceConfiguration.isEdgeDevice(targetSw);
1657 } catch (DeviceConfigNotFoundException e) {
1658 log.warn(e.getMessage() + "Cannot determine if targetIsEdge {}.. "
1659 + "continuing to getNextHops", targetSw);
1660 }
1661
1662 EcmpShortestPathGraph ecmpSpg = updatedEcmpSpgMap.get(dstSw);
1663 if (ecmpSpg == null) {
1664 log.debug("No ecmpSpg found for dstSw: {}", dstSw);
1665 return ImmutableSet.of();
1666 }
1667 HashMap<Integer,
1668 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> switchVia =
1669 ecmpSpg.getAllLearnedSwitchesAndVia();
1670 for (Integer itrIdx : switchVia.keySet()) {
1671 HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
1672 switchVia.get(itrIdx);
1673 for (DeviceId target : swViaMap.keySet()) {
1674 if (!target.equals(targetSw)) {
1675 continue;
1676 }
Saurav Das49368392018-04-23 18:42:12 -07001677 // optimization for spines to not use leaves to get
1678 // to a spine or other leaves. Also leaves should not use other
1679 // leaves to get to the destination
1680 if ((!targetIsEdge && itrIdx > 1) || targetIsEdge) {
Saurav Das97241862018-02-14 14:14:54 -08001681 boolean pathdevIsEdge = false;
1682 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
Saurav Das49368392018-04-23 18:42:12 -07001683 log.debug("Evaluating next-hop in path: {}", via);
Saurav Das97241862018-02-14 14:14:54 -08001684 for (DeviceId pathdev : via) {
1685 try {
1686 pathdevIsEdge = srManager.deviceConfiguration
1687 .isEdgeDevice(pathdev);
1688 } catch (DeviceConfigNotFoundException e) {
1689 log.warn(e.getMessage());
1690 }
1691 if (pathdevIsEdge) {
1692 log.debug("Avoiding {} hop path for non-edge targetSw:{}"
1693 + " --> dstSw:{} which goes through an edge"
1694 + " device {} in path {}", itrIdx,
1695 targetSw, dstSw, pathdev, via);
1696 return ImmutableSet.of();
1697 }
1698 }
1699 }
Saurav Das261c3002017-06-13 15:35:54 -07001700 }
1701 Set<DeviceId> nextHops = new HashSet<>();
1702 for (ArrayList<DeviceId> via : swViaMap.get(targetSw)) {
1703 if (via.isEmpty()) {
1704 // the dstSw is the next-hop from the targetSw
1705 nextHops.add(dstSw);
1706 } else {
1707 // first elem is next-hop in each ECMP path
1708 nextHops.add(via.get(0));
1709 }
1710 }
Saurav Das49368392018-04-23 18:42:12 -07001711 log.debug("target {} --> dst: {} has next-hops:{}", targetSw,
1712 dstSw, nextHops);
Saurav Das261c3002017-06-13 15:35:54 -07001713 return nextHops;
1714 }
1715 }
Saurav Das49368392018-04-23 18:42:12 -07001716 log.debug("No next hops found for target:{} --> dst: {}", targetSw, dstSw);
Saurav Das261c3002017-06-13 15:35:54 -07001717 return ImmutableSet.of(); //no next-hops found
1718 }
1719
1720 /**
1721 * Represents two devices that are paired by configuration. An EdgePair for
1722 * (dev1, dev2) is the same as as EdgePair for (dev2, dev1)
1723 */
1724 protected final class EdgePair {
1725 DeviceId dev1;
1726 DeviceId dev2;
1727
1728 EdgePair(DeviceId dev1, DeviceId dev2) {
1729 this.dev1 = dev1;
1730 this.dev2 = dev2;
1731 }
1732
1733 boolean includes(DeviceId dev) {
1734 return dev1.equals(dev) || dev2.equals(dev);
1735 }
1736
1737 @Override
1738 public boolean equals(Object o) {
1739 if (this == o) {
1740 return true;
1741 }
1742 if (!(o instanceof EdgePair)) {
1743 return false;
1744 }
1745 EdgePair that = (EdgePair) o;
1746 return ((this.dev1.equals(that.dev1) && this.dev2.equals(that.dev2)) ||
1747 (this.dev1.equals(that.dev2) && this.dev2.equals(that.dev1)));
1748 }
1749
1750 @Override
1751 public int hashCode() {
1752 if (dev1.toString().compareTo(dev2.toString()) <= 0) {
1753 return Objects.hash(dev1, dev2);
1754 } else {
1755 return Objects.hash(dev2, dev1);
1756 }
1757 }
1758
1759 @Override
1760 public String toString() {
1761 return toStringHelper(this)
1762 .add("Dev1", dev1)
1763 .add("Dev2", dev2)
1764 .toString();
1765 }
1766 }
1767
1768 //////////////////////////////////////
1769 // Filtering rule creation
1770 //////////////////////////////////////
1771
1772 /**
Saurav Dasf9332192017-02-18 14:05:44 -08001773 * Populates filtering rules for port, and punting rules
1774 * for gateway IPs, loopback IPs and arp/ndp traffic.
1775 * Should only be called by the master instance for this device/port.
sangho80f11cb2015-04-01 13:05:26 -07001776 *
1777 * @param deviceId Switch ID to set the rules
1778 */
Charles Chanfbcb8812018-04-18 18:41:05 -07001779 void populatePortAddressingRules(DeviceId deviceId) {
Saurav Das07c74602016-04-27 18:35:50 -07001780 // Although device is added, sometimes device store does not have the
1781 // ports for this device yet. It results in missing filtering rules in the
1782 // switch. We will attempt it a few times. If it still does not work,
1783 // user can manually repopulate using CLI command sr-reroute-network
Charles Chan18fa4252017-02-08 16:10:40 -08001784 PortFilterInfo firstRun = rulePopulator.populateVlanMacFilters(deviceId);
Saurav Dasd1872b02016-12-02 15:43:47 -08001785 if (firstRun == null) {
1786 firstRun = new PortFilterInfo(0, 0, 0);
Saurav Das07c74602016-04-27 18:35:50 -07001787 }
Saurav Dasd1872b02016-12-02 15:43:47 -08001788 executorService.schedule(new RetryFilters(deviceId, firstRun),
1789 RETRY_INTERVAL_MS, TimeUnit.MILLISECONDS);
sangho80f11cb2015-04-01 13:05:26 -07001790 }
1791
1792 /**
Saurav Dasd1872b02016-12-02 15:43:47 -08001793 * Utility class used to temporarily store information about the ports on a
1794 * device processed for filtering objectives.
Saurav Dasd1872b02016-12-02 15:43:47 -08001795 */
1796 public final class PortFilterInfo {
Saurav Dasf9332192017-02-18 14:05:44 -08001797 int disabledPorts = 0, errorPorts = 0, filteredPorts = 0;
Saurav Das07c74602016-04-27 18:35:50 -07001798
Saurav Dasf9332192017-02-18 14:05:44 -08001799 public PortFilterInfo(int disabledPorts, int errorPorts,
Saurav Dasd1872b02016-12-02 15:43:47 -08001800 int filteredPorts) {
1801 this.disabledPorts = disabledPorts;
1802 this.filteredPorts = filteredPorts;
Saurav Dasf9332192017-02-18 14:05:44 -08001803 this.errorPorts = errorPorts;
Saurav Dasd1872b02016-12-02 15:43:47 -08001804 }
1805
1806 @Override
1807 public int hashCode() {
Saurav Dasf9332192017-02-18 14:05:44 -08001808 return Objects.hash(disabledPorts, filteredPorts, errorPorts);
Saurav Dasd1872b02016-12-02 15:43:47 -08001809 }
1810
1811 @Override
1812 public boolean equals(Object obj) {
1813 if (this == obj) {
1814 return true;
1815 }
1816 if ((obj == null) || (!(obj instanceof PortFilterInfo))) {
1817 return false;
1818 }
1819 PortFilterInfo other = (PortFilterInfo) obj;
1820 return ((disabledPorts == other.disabledPorts) &&
1821 (filteredPorts == other.filteredPorts) &&
Saurav Dasf9332192017-02-18 14:05:44 -08001822 (errorPorts == other.errorPorts));
Saurav Dasd1872b02016-12-02 15:43:47 -08001823 }
1824
1825 @Override
1826 public String toString() {
1827 MoreObjects.ToStringHelper helper = toStringHelper(this)
1828 .add("disabledPorts", disabledPorts)
Saurav Dasf9332192017-02-18 14:05:44 -08001829 .add("errorPorts", errorPorts)
Saurav Dasd1872b02016-12-02 15:43:47 -08001830 .add("filteredPorts", filteredPorts);
1831 return helper.toString();
1832 }
1833 }
1834
1835 /**
1836 * RetryFilters populates filtering objectives for a device and keeps retrying
1837 * till the number of ports filtered are constant for a predefined number
1838 * of attempts.
1839 */
1840 protected final class RetryFilters implements Runnable {
1841 int constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS;
1842 DeviceId devId;
1843 int counter;
1844 PortFilterInfo prevRun;
1845
1846 private RetryFilters(DeviceId deviceId, PortFilterInfo previousRun) {
Saurav Das07c74602016-04-27 18:35:50 -07001847 devId = deviceId;
Saurav Dasd1872b02016-12-02 15:43:47 -08001848 prevRun = previousRun;
1849 counter = 0;
Saurav Das07c74602016-04-27 18:35:50 -07001850 }
1851
1852 @Override
1853 public void run() {
Charles Chan077314e2017-06-22 14:27:17 -07001854 log.debug("RETRY FILTER ATTEMPT {} ** dev:{}", ++counter, devId);
Charles Chan18fa4252017-02-08 16:10:40 -08001855 PortFilterInfo thisRun = rulePopulator.populateVlanMacFilters(devId);
Saurav Dasd1872b02016-12-02 15:43:47 -08001856 boolean sameResult = prevRun.equals(thisRun);
1857 log.debug("dev:{} prevRun:{} thisRun:{} sameResult:{}", devId, prevRun,
1858 thisRun, sameResult);
Ray Milkey614352e2018-02-26 09:36:31 -08001859 if (thisRun == null || !sameResult || (--constantAttempts > 0)) {
Saurav Dasf9332192017-02-18 14:05:44 -08001860 // exponentially increasing intervals for retries
1861 executorService.schedule(this,
1862 RETRY_INTERVAL_MS * (int) Math.pow(counter, RETRY_INTERVAL_SCALE),
1863 TimeUnit.MILLISECONDS);
Saurav Dasd1872b02016-12-02 15:43:47 -08001864 if (!sameResult) {
1865 constantAttempts = MAX_CONSTANT_RETRY_ATTEMPTS; //reset
1866 }
Saurav Das07c74602016-04-27 18:35:50 -07001867 }
Saurav Dasd1872b02016-12-02 15:43:47 -08001868 prevRun = (thisRun == null) ? prevRun : thisRun;
Saurav Das07c74602016-04-27 18:35:50 -07001869 }
Saurav Das07c74602016-04-27 18:35:50 -07001870 }
1871
sangho80f11cb2015-04-01 13:05:26 -07001872}