blob: 5e41dc57fab1e32536f9c4e7999b791b6b0739a1 [file] [log] [blame]
Saurav Das45f48152018-01-18 12:07:33 -08001/*
2 * Copyright 2018-present Open Networking Foundation
3 *
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 */
16
17package org.onosproject.segmentrouting;
18
Saurav Das604ab3a2018-03-18 21:28:15 -070019import java.util.List;
Saurav Das45f48152018-01-18 12:07:33 -080020import java.util.Map;
21import java.util.Map.Entry;
22import java.util.Set;
23import java.util.concurrent.ConcurrentHashMap;
Saurav Dasc568c342018-01-25 09:49:01 -080024import java.util.stream.Collectors;
25
Saurav Das9a554292018-04-27 18:42:30 -070026import org.onosproject.net.ConnectPoint;
Saurav Das45f48152018-01-18 12:07:33 -080027import org.onosproject.net.Device;
28import org.onosproject.net.DeviceId;
29import org.onosproject.net.HostLocation;
30import org.onosproject.net.Link;
31import org.onosproject.net.PortNumber;
32import org.onosproject.net.link.LinkService;
33import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
34import org.onosproject.segmentrouting.config.DeviceConfiguration;
35import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
36import org.onosproject.store.service.EventuallyConsistentMap;
37import org.onosproject.store.service.EventuallyConsistentMapBuilder;
38import org.onosproject.store.service.WallClockTimestamp;
39import org.slf4j.Logger;
40import org.slf4j.LoggerFactory;
41
Saurav Das604ab3a2018-03-18 21:28:15 -070042import com.google.common.collect.ImmutableList;
Saurav Dasc568c342018-01-25 09:49:01 -080043import com.google.common.collect.ImmutableMap;
Saurav Das45f48152018-01-18 12:07:33 -080044import com.google.common.collect.Sets;
45
Saurav Das604ab3a2018-03-18 21:28:15 -070046
Saurav Das45f48152018-01-18 12:07:33 -080047public class LinkHandler {
48 private static final Logger log = LoggerFactory.getLogger(LinkHandler.class);
49 protected final SegmentRoutingManager srManager;
Saurav Das45f48152018-01-18 12:07:33 -080050
51 // Local store for all links seen and their present status, used for
Saurav Dasc568c342018-01-25 09:49:01 -080052 // optimized routing. The existence of the link in the keys is enough to know
Saurav Das45f48152018-01-18 12:07:33 -080053 // if the link has been "seen-before" by this instance of the controller.
54 // The boolean value indicates if the link is currently up or not.
Saurav Dasc568c342018-01-25 09:49:01 -080055 // Currently the optimized routing logic depends on "forgetting" a link
56 // when a switch goes down, but "remembering" it when only the link goes down.
Saurav Das45f48152018-01-18 12:07:33 -080057 private Map<Link, Boolean> seenLinks = new ConcurrentHashMap<>();
Saurav Das604ab3a2018-03-18 21:28:15 -070058 private Set<Link> seenBefore = Sets.newConcurrentHashSet();
Saurav Das45f48152018-01-18 12:07:33 -080059 private EventuallyConsistentMap<DeviceId, Set<PortNumber>> downedPortStore = null;
60
61 /**
62 * Constructs the LinkHandler.
63 *
64 * @param srManager Segment Routing manager
65 */
66 LinkHandler(SegmentRoutingManager srManager) {
67 this.srManager = srManager;
Saurav Das45f48152018-01-18 12:07:33 -080068 log.debug("Creating EC map downedportstore");
69 EventuallyConsistentMapBuilder<DeviceId, Set<PortNumber>> downedPortsMapBuilder
70 = srManager.storageService.eventuallyConsistentMapBuilder();
71 downedPortStore = downedPortsMapBuilder.withName("downedportstore")
72 .withSerializer(srManager.createSerializer())
73 .withTimestampProvider((k, v) -> new WallClockTimestamp())
74 .build();
75 log.trace("Current size {}", downedPortStore.size());
76 }
77
78 /**
79 * Constructs the LinkHandler for unit-testing.
80 *
81 * @param srManager SegmentRoutingManager
82 * @param linkService LinkService
83 */
84 LinkHandler(SegmentRoutingManager srManager, LinkService linkService) {
85 this.srManager = srManager;
Saurav Das45f48152018-01-18 12:07:33 -080086 }
87
88 /**
Saurav Dase7f51012018-02-09 17:26:45 -080089 * Initialize LinkHandler.
90 */
Charles Chanb39777c2018-03-09 15:53:44 -080091 void init() {
Saurav Dase7f51012018-02-09 17:26:45 -080092 log.info("Loading stored links");
Charles Chanb39777c2018-03-09 15:53:44 -080093 srManager.linkService.getActiveLinks().forEach(this::processLinkAdded);
Saurav Dase7f51012018-02-09 17:26:45 -080094 }
95
96 /**
Saurav Das45f48152018-01-18 12:07:33 -080097 * Preprocessing of added link before being sent for route-path handling.
98 * Also performs post processing of link.
99 *
100 * @param link the link to be processed
101 */
102 void processLinkAdded(Link link) {
103 log.info("** LINK ADDED {}", link.toString());
104 if (!isLinkValid(link)) {
105 return;
106 }
Saurav Das45f48152018-01-18 12:07:33 -0800107 // Irrespective of whether the local is a MASTER or not for this device,
Saurav Dasc568c342018-01-25 09:49:01 -0800108 // create group handler instance and push default TTP flow rules if needed,
Saurav Das45f48152018-01-18 12:07:33 -0800109 // as in a multi-instance setup, instances can initiate groups for any
Saurav Dasa4020382018-02-14 14:14:54 -0800110 // device. Also update local groupHandler stores.
Saurav Das45f48152018-01-18 12:07:33 -0800111 DefaultGroupHandler groupHandler = srManager.groupHandlerMap
Saurav Dasa4020382018-02-14 14:14:54 -0800112 .get(link.src().deviceId());
Saurav Das5a356042018-04-06 20:16:01 -0700113 if (groupHandler == null) {
Saurav Das45f48152018-01-18 12:07:33 -0800114 Device device = srManager.deviceService.getDevice(link.src().deviceId());
115 if (device != null) {
Saurav Dasa4020382018-02-14 14:14:54 -0800116 log.warn("processLinkAdded: Link Added notification without "
117 + "Device Added event, still handling it");
Saurav Das45f48152018-01-18 12:07:33 -0800118 srManager.processDeviceAdded(device);
Saurav Das45f48152018-01-18 12:07:33 -0800119 }
120 }
Saurav Das604ab3a2018-03-18 21:28:15 -0700121
122 if (isSeenLink(link)) {
123 // temp store retains previous state, just before the state is updated in
124 // seenLinks; previous state is necessary when processing the
125 // linkupdate in defaultRoutingHandler
126 seenBefore.add(link);
127 }
128 updateSeenLink(link, true);
129
Saurav Dasa4020382018-02-14 14:14:54 -0800130 if (srManager.deviceConfiguration == null ||
131 !srManager.deviceConfiguration.isConfigured(link.src().deviceId())) {
Saurav Dasa4020382018-02-14 14:14:54 -0800132 log.warn("Source device of this link is not configured.. "
133 + "not processing further");
134 return;
135 }
Saurav Das45f48152018-01-18 12:07:33 -0800136
Saurav Das604ab3a2018-03-18 21:28:15 -0700137 // process link only if it is bidirectional
138 if (!isBidirectionalLinkUp(link)) {
Saurav Das45f48152018-01-18 12:07:33 -0800139 log.debug("Link not bidirectional.. waiting for other direction " +
Saurav Das604ab3a2018-03-18 21:28:15 -0700140 "src {} --> dst {} ", link.dst(), link.src());
141 return;
142 }
Saurav Das45f48152018-01-18 12:07:33 -0800143
Saurav Das5a356042018-04-06 20:16:01 -0700144 log.info("processing bidi links {} <--> {} UP", link.src(), link.dst());
145 // update groupHandler internal port state for both directions
146 List<Link> ulinks = getBidiComponentLinks(link);
147 for (Link ulink : ulinks) {
148 DefaultGroupHandler gh = srManager.groupHandlerMap
149 .get(ulink.src().deviceId());
150 if (gh != null) {
151 gh.portUpForLink(ulink);
152 }
153 }
154
155 for (Link ulink : ulinks) {
156 log.info("-- Starting optimized route-path processing for component "
Saurav Das604ab3a2018-03-18 21:28:15 -0700157 + "unidirectional link {} --> {} UP", ulink.src(), ulink.dst());
158 srManager.defaultRoutingHandler
159 .populateRoutingRulesForLinkStatusChange(null, ulink, null,
160 seenBefore.contains(ulink));
Saurav Das45f48152018-01-18 12:07:33 -0800161
Saurav Das604ab3a2018-03-18 21:28:15 -0700162 if (srManager.mastershipService.isLocalMaster(ulink.src().deviceId())) {
163 // handle edge-ports for dual-homed hosts
Saurav Das9a554292018-04-27 18:42:30 -0700164 updateHostPorts(ulink, true);
Saurav Das45f48152018-01-18 12:07:33 -0800165
Saurav Das604ab3a2018-03-18 21:28:15 -0700166 // It's possible that linkUp causes no route-path change as ECMP graph does
167 // not change if the link is a parallel link (same src-dst as
168 // another link). However we still need to update ECMP hash
169 // groups to include new buckets for the link that has come up.
Saurav Das5a356042018-04-06 20:16:01 -0700170 DefaultGroupHandler gh = srManager.groupHandlerMap
171 .get(ulink.src().deviceId());
172 if (gh != null) {
Saurav Das604ab3a2018-03-18 21:28:15 -0700173 if (!seenBefore.contains(ulink) && isParallelLink(ulink)) {
174 // if link seen first time, we need to ensure hash-groups have
175 // all ports
176 log.debug("Attempting retryHash for paralled first-time link {}",
177 ulink);
Saurav Das5a356042018-04-06 20:16:01 -0700178 gh.retryHash(ulink, false, true);
Saurav Das604ab3a2018-03-18 21:28:15 -0700179 } else {
180 // seen before-link
181 if (isParallelLink(ulink)) {
182 log.debug("Attempting retryHash for paralled seen-before "
183 + "link {}", ulink);
Saurav Das5a356042018-04-06 20:16:01 -0700184 gh.retryHash(ulink, false, false);
Saurav Das604ab3a2018-03-18 21:28:15 -0700185 }
Ray Milkeyffe1a332018-01-24 10:41:14 -0800186 }
Saurav Das45f48152018-01-18 12:07:33 -0800187 }
188 }
Saurav Das604ab3a2018-03-18 21:28:15 -0700189 //clean up temp state
190 seenBefore.remove(ulink);
Saurav Das45f48152018-01-18 12:07:33 -0800191 }
Saurav Das604ab3a2018-03-18 21:28:15 -0700192
Saurav Das45f48152018-01-18 12:07:33 -0800193 }
194
195 /**
196 * Preprocessing of removed link before being sent for route-path handling.
197 * Also performs post processing of link.
198 *
199 * @param link the link to be processed
200 */
201 void processLinkRemoved(Link link) {
202 log.info("** LINK REMOVED {}", link.toString());
203 if (!isLinkValid(link)) {
204 return;
205 }
206 // when removing links, update seen links first, before doing route-path
207 // changes
208 updateSeenLink(link, false);
Saurav Dasc568c342018-01-25 09:49:01 -0800209 // handle edge-ports for dual-homed hosts
210 if (srManager.mastershipService.isLocalMaster(link.src().deviceId())) {
Saurav Das9a554292018-04-27 18:42:30 -0700211 updateHostPorts(link, false);
Saurav Dasc568c342018-01-25 09:49:01 -0800212 }
Saurav Das45f48152018-01-18 12:07:33 -0800213
214 // device availability check helps to ensure that multiple link-removed
215 // events are actually treated as a single switch removed event.
216 // purgeSeenLink is necessary so we do rerouting (instead of rehashing)
217 // when switch comes back.
218 if (link.src().elementId() instanceof DeviceId
219 && !srManager.deviceService.isAvailable(link.src().deviceId())) {
220 purgeSeenLink(link);
221 return;
222 }
223 if (link.dst().elementId() instanceof DeviceId
224 && !srManager.deviceService.isAvailable(link.dst().deviceId())) {
225 purgeSeenLink(link);
226 return;
227 }
228
Saurav Das604ab3a2018-03-18 21:28:15 -0700229 // process link only if it is bidirectional
230 if (!isBidirectionalLinkDown(link)) {
231 log.debug("Link not bidirectional.. waiting for other direction " +
232 "src {} --> dst {} ", link.dst(), link.src());
233 return;
234 }
235 log.info("processing bidi links {} <--> {} DOWN", link.src(), link.dst());
Saurav Das45f48152018-01-18 12:07:33 -0800236
Saurav Das604ab3a2018-03-18 21:28:15 -0700237 for (Link ulink : getBidiComponentLinks(link)) {
Saurav Das5a356042018-04-06 20:16:01 -0700238 log.info("-- Starting optimized route-path processing for component "
Saurav Das604ab3a2018-03-18 21:28:15 -0700239 + "unidirectional link {} --> {} DOWN", ulink.src(), ulink.dst());
240 srManager.defaultRoutingHandler
241 .populateRoutingRulesForLinkStatusChange(ulink, null, null, true);
242
243 // attempt rehashing for parallel links
244 DefaultGroupHandler groupHandler = srManager.groupHandlerMap
245 .get(ulink.src().deviceId());
246 if (groupHandler != null) {
247 if (srManager.mastershipService.isLocalMaster(ulink.src().deviceId())
248 && isParallelLink(ulink)) {
249 log.debug("* retrying hash for parallel link removed:{}", ulink);
250 groupHandler.retryHash(ulink, true, false);
251 } else {
252 log.debug("Not attempting retry-hash for link removed: {} .. {}",
253 ulink,
254 (srManager.mastershipService.isLocalMaster(ulink
255 .src().deviceId())) ? "not parallel"
256 : "not master");
257 }
258 // ensure local stores are updated after all rerouting or rehashing
259 groupHandler.portDownForLink(ulink);
Saurav Das45f48152018-01-18 12:07:33 -0800260 } else {
Saurav Das604ab3a2018-03-18 21:28:15 -0700261 log.warn("group handler not found for dev:{} when removing link: {}",
262 ulink.src().deviceId(), ulink);
Saurav Das45f48152018-01-18 12:07:33 -0800263 }
Saurav Das45f48152018-01-18 12:07:33 -0800264 }
Saurav Das45f48152018-01-18 12:07:33 -0800265 }
266
267 /**
268 * Checks validity of link. Examples of invalid links include
269 * indirect-links, links between ports on the same switch, and more.
270 *
271 * @param link the link to be processed
272 * @return true if valid link
273 */
Pier Luigi83f919b2018-02-15 16:33:08 +0100274 boolean isLinkValid(Link link) {
Saurav Das45f48152018-01-18 12:07:33 -0800275 if (link.type() != Link.Type.DIRECT) {
276 // NOTE: A DIRECT link might be transiently marked as INDIRECT
277 // if BDDP is received before LLDP. We can safely ignore that
278 // until the LLDP is received and the link is marked as DIRECT.
279 log.info("Ignore link {}->{}. Link type is {} instead of DIRECT.",
280 link.src(), link.dst(), link.type());
281 return false;
282 }
283 DeviceId srcId = link.src().deviceId();
284 DeviceId dstId = link.dst().deviceId();
285 if (srcId.equals(dstId)) {
286 log.warn("Links between ports on the same switch are not "
287 + "allowed .. ignoring link {}", link);
288 return false;
289 }
290 DeviceConfiguration devConfig = srManager.deviceConfiguration;
Saurav Dase7f51012018-02-09 17:26:45 -0800291 if (devConfig == null) {
292 log.warn("Cannot check validity of link without device config");
293 return true;
294 }
Saurav Das45f48152018-01-18 12:07:33 -0800295 try {
Saurav Dasa4020382018-02-14 14:14:54 -0800296 /*if (!devConfig.isEdgeDevice(srcId)
Saurav Das45f48152018-01-18 12:07:33 -0800297 && !devConfig.isEdgeDevice(dstId)) {
298 // ignore links between spines
299 // XXX revisit when handling multi-stage fabrics
300 log.warn("Links between spines not allowed...ignoring "
301 + "link {}", link);
302 return false;
Saurav Dasa4020382018-02-14 14:14:54 -0800303 }*/
Saurav Das45f48152018-01-18 12:07:33 -0800304 if (devConfig.isEdgeDevice(srcId)
305 && devConfig.isEdgeDevice(dstId)) {
306 // ignore links between leaves if they are not pair-links
307 // XXX revisit if removing pair-link config or allowing more than
308 // one pair-link
309 if (devConfig.getPairDeviceId(srcId).equals(dstId)
310 && devConfig.getPairLocalPort(srcId)
311 .equals(link.src().port())
312 && devConfig.getPairLocalPort(dstId)
313 .equals(link.dst().port())) {
314 // found pair link - allow it
315 return true;
316 } else {
317 log.warn("Links between leaves other than pair-links are "
318 + "not allowed...ignoring link {}", link);
319 return false;
320 }
321 }
322 } catch (DeviceConfigNotFoundException e) {
323 // We still want to count the links in seenLinks even though there
324 // is no config. So we let it return true
325 log.warn("Could not check validity of link {} as subtending devices "
326 + "are not yet configured", link);
327 }
328 return true;
329 }
330
331 /**
332 * Administratively enables or disables edge ports if the link that was
Saurav Das9a554292018-04-27 18:42:30 -0700333 * added or removed was the only uplink port from an edge device. Edge ports
334 * that belong to dual-homed hosts are always processed. In addition,
335 * single-homed host ports are optionally processed depending on the
336 * singleHomedDown property.
Saurav Das45f48152018-01-18 12:07:33 -0800337 *
338 * @param link the link to be processed
339 * @param added true if link was added, false if link was removed
340 */
Saurav Das9a554292018-04-27 18:42:30 -0700341 private void updateHostPorts(Link link, boolean added) {
Saurav Das45f48152018-01-18 12:07:33 -0800342 if (added) {
Saurav Das5a356042018-04-06 20:16:01 -0700343 DeviceConfiguration devConfig = srManager.deviceConfiguration;
344 try {
345 if (!devConfig.isEdgeDevice(link.src().deviceId())
346 || devConfig.isEdgeDevice(link.dst().deviceId())) {
347 return;
348 }
349 } catch (DeviceConfigNotFoundException e) {
350 log.warn("Unable to determine if link is a valid uplink"
351 + e.getMessage());
352 }
353 // re-enable previously disabled ports on this edge-device if any
Saurav Das45f48152018-01-18 12:07:33 -0800354 Set<PortNumber> p = downedPortStore.remove(link.src().deviceId());
355 if (p != null) {
Saurav Das5a356042018-04-06 20:16:01 -0700356 log.warn("Link src {} --> dst {} added is an edge-device uplink, "
357 + "enabling dual homed ports if any: {}", link.src().deviceId(),
358 link.dst().deviceId(), (p.isEmpty()) ? "no ports" : p);
Saurav Das45f48152018-01-18 12:07:33 -0800359 p.forEach(pnum -> srManager.deviceAdminService
360 .changePortState(link.src().deviceId(), pnum, true));
361 }
362 } else {
Saurav Das5a356042018-04-06 20:16:01 -0700363 if (!lastUplink(link)) {
364 return;
365 }
Saurav Das45f48152018-01-18 12:07:33 -0800366 // find dual homed hosts on this dev to disable
Saurav Das9a554292018-04-27 18:42:30 -0700367 DeviceId dev = link.src().deviceId();
368 Set<PortNumber> dp = srManager.hostHandler
369 .getDualHomedHostPorts(dev);
370 log.warn("Link src {} --> dst {} removed was the last uplink, "
371 + "disabling dual homed ports: {}", dev,
372 link.dst().deviceId(), (dp.isEmpty()) ? "no ports" : dp);
373 dp.forEach(pnum -> srManager.deviceAdminService
374 .changePortState(dev, pnum, false));
375 if (srManager.singleHomedDown) {
376 // get all configured ports and down them if they haven't already
377 // been downed
378 srManager.deviceService.getPorts(dev).stream()
379 .filter(p -> p.isEnabled() && !dp.contains(p.number()))
380 .filter(p -> srManager.interfaceService
381 .isConfigured(new ConnectPoint(dev, p.number())))
382 .filter(p -> !srManager.deviceConfiguration
383 .isPairLocalPort(dev, p.number()))
384 .forEach(p -> {
385 log.warn("Last uplink gone src {} -> dst {} .. removing "
386 + "configured port {}", p.number());
387 srManager.deviceAdminService
388 .changePortState(dev, p.number(), false);
389 dp.add(p.number());
390 });
391 }
392 if (!dp.isEmpty()) {
Saurav Das45f48152018-01-18 12:07:33 -0800393 // update global store
Saurav Das9a554292018-04-27 18:42:30 -0700394 Set<PortNumber> p = downedPortStore.get(dev);
Saurav Das45f48152018-01-18 12:07:33 -0800395 if (p == null) {
Saurav Das9a554292018-04-27 18:42:30 -0700396 p = dp;
Saurav Das45f48152018-01-18 12:07:33 -0800397 } else {
Saurav Das9a554292018-04-27 18:42:30 -0700398 p.addAll(dp);
Saurav Das45f48152018-01-18 12:07:33 -0800399 }
400 downedPortStore.put(link.src().deviceId(), p);
401 }
402 }
403 }
404
405 /**
Saurav Das5a356042018-04-06 20:16:01 -0700406 * Returns true if given link was the last active uplink from src-device of
Saurav Das45f48152018-01-18 12:07:33 -0800407 * link. An uplink is defined as a unidirectional link with src as
408 * edgeRouter and dst as non-edgeRouter.
409 *
410 * @param link
Saurav Das5a356042018-04-06 20:16:01 -0700411 * @return true if given link was the last uplink from the src device
Saurav Das45f48152018-01-18 12:07:33 -0800412 */
Saurav Das5a356042018-04-06 20:16:01 -0700413 private boolean lastUplink(Link link) {
Saurav Das45f48152018-01-18 12:07:33 -0800414 DeviceConfiguration devConfig = srManager.deviceConfiguration;
415 try {
Saurav Dasc568c342018-01-25 09:49:01 -0800416 if (!devConfig.isEdgeDevice(link.src().deviceId())
417 || devConfig.isEdgeDevice(link.dst().deviceId())) {
Saurav Das45f48152018-01-18 12:07:33 -0800418 return false;
419 }
Saurav Dasc568c342018-01-25 09:49:01 -0800420 // note that using linkservice here would cause race conditions as
421 // more links can show up while the app is still processing the first one
422 Set<Link> devLinks = seenLinks.entrySet().stream()
423 .filter(entry -> entry.getKey().src().deviceId()
424 .equals(link.src().deviceId()))
425 .filter(entry -> entry.getValue())
426 .filter(entry -> !entry.getKey().equals(link))
427 .map(entry -> entry.getKey())
428 .collect(Collectors.toSet());
429
Saurav Das45f48152018-01-18 12:07:33 -0800430 for (Link l : devLinks) {
Saurav Dasc568c342018-01-25 09:49:01 -0800431 if (devConfig.isEdgeDevice(l.dst().deviceId())) {
Saurav Das45f48152018-01-18 12:07:33 -0800432 continue;
433 }
Saurav Das5a356042018-04-06 20:16:01 -0700434 log.debug("Found another active uplink {}", l);
Saurav Dasc568c342018-01-25 09:49:01 -0800435 return false;
Saurav Das45f48152018-01-18 12:07:33 -0800436 }
Saurav Das5a356042018-04-06 20:16:01 -0700437 log.debug("No active uplink found");
Saurav Dasc568c342018-01-25 09:49:01 -0800438 return true;
Saurav Das45f48152018-01-18 12:07:33 -0800439 } catch (DeviceConfigNotFoundException e) {
Saurav Das5a356042018-04-06 20:16:01 -0700440 log.warn("Unable to determine if link was the last uplink"
Saurav Das45f48152018-01-18 12:07:33 -0800441 + e.getMessage());
442 }
443 return false;
444 }
445
446 /**
447 * Returns true if this controller instance has seen this link before. The
448 * link may not be currently up, but as long as the link had been seen
449 * before this method will return true. The one exception is when the link
450 * was indeed seen before, but this controller instance was forced to forget
451 * it by a call to purgeSeenLink method.
452 *
453 * @param link the infrastructure link being queried
454 * @return true if this controller instance has seen this link before
455 */
456 boolean isSeenLink(Link link) {
457 return seenLinks.containsKey(link);
458 }
459
460 /**
461 * Updates the seen link store. Updates can be for links that are currently
462 * available or not.
463 *
464 * @param link the link to update in the seen-link local store
465 * @param up the status of the link, true if up, false if down
466 */
467 void updateSeenLink(Link link, boolean up) {
468 seenLinks.put(link, up);
469 }
470
471 /**
472 * Returns the status of a seen-link (up or down). If the link has not been
473 * seen-before, a null object is returned.
474 *
475 * @param link the infrastructure link being queried
476 * @return null if the link was not seen-before; true if the seen-link is
477 * up; false if the seen-link is down
478 */
479 private Boolean isSeenLinkUp(Link link) {
480 return seenLinks.get(link);
481 }
482
483 /**
484 * Makes this controller instance forget a previously seen before link.
485 *
486 * @param link the infrastructure link to purge
487 */
488 private void purgeSeenLink(Link link) {
489 seenLinks.remove(link);
Saurav Das604ab3a2018-03-18 21:28:15 -0700490 seenBefore.remove(link);
Saurav Das45f48152018-01-18 12:07:33 -0800491 }
492
493 /**
494 * Returns the status of a link as parallel link. A parallel link is defined
495 * as a link which has common src and dst switches as another seen-link that
496 * is currently enabled. It is not necessary for the link being queried to
497 * be a seen-link.
498 *
499 * @param link the infrastructure link being queried
500 * @return true if a seen-link exists that is up, and shares the same src
501 * and dst switches as the link being queried
502 */
503 private boolean isParallelLink(Link link) {
504 for (Entry<Link, Boolean> seen : seenLinks.entrySet()) {
505 Link seenLink = seen.getKey();
506 if (seenLink.equals(link)) {
507 continue;
508 }
509 if (seenLink.src().deviceId().equals(link.src().deviceId())
510 && seenLink.dst().deviceId().equals(link.dst().deviceId())
511 && seen.getValue()) {
512 return true;
513 }
514 }
515 return false;
516 }
517
518 /**
Saurav Das604ab3a2018-03-18 21:28:15 -0700519 * Returns true if the link being queried is a bidirectional link that is
520 * up. A bidi-link is defined as a component unidirectional link, whose
521 * reverse link - ie. the component unidirectional link in the reverse
522 * direction - has been seen-before and is up. It is NOT necessary for the
523 * link being queried to be a previously seen-link.
Saurav Das45f48152018-01-18 12:07:33 -0800524 *
Saurav Das604ab3a2018-03-18 21:28:15 -0700525 * @param link the infrastructure (unidirectional) link being queried
Saurav Das45f48152018-01-18 12:07:33 -0800526 * @return true if another unidirectional link exists in the reverse
527 * direction, has been seen-before and is up
528 */
Saurav Das604ab3a2018-03-18 21:28:15 -0700529 boolean isBidirectionalLinkUp(Link link) {
Saurav Das5a356042018-04-06 20:16:01 -0700530 // cannot call linkService as link may be gone
531 Link reverseLink = getReverseLink(link);
Saurav Das45f48152018-01-18 12:07:33 -0800532 if (reverseLink == null) {
533 return false;
534 }
535 Boolean result = isSeenLinkUp(reverseLink);
536 if (result == null) {
537 return false;
538 }
539 return result.booleanValue();
540 }
541
542 /**
Saurav Das604ab3a2018-03-18 21:28:15 -0700543 * Returns true if the link being queried is a bidirectional link that is
544 * down. A bidi-link is defined as a component unidirectional link, whose
545 * reverse link - i.e the component unidirectional link in the reverse
546 * direction - has been seen before and is down. It is necessary for the
547 * reverse-link to have been previously seen.
548 *
549 * @param link the infrastructure (unidirectional) link being queried
550 * @return true if another unidirectional link exists in the reverse
551 * direction, has been seen-before and is down
552 */
553 boolean isBidirectionalLinkDown(Link link) {
554 // cannot call linkService as link may be gone
555 Link reverseLink = getReverseLink(link);
556 if (reverseLink == null) {
557 log.warn("Query for bidi-link down but reverse-link not found "
558 + "for link {}", link);
559 return false;
560 }
561 Boolean result = seenLinks.get(reverseLink);
562 if (result == null) {
563 return false;
564 }
565 // if reverse link is seen UP (true), then its not bidi yet
566 return !result.booleanValue();
567 }
568
569 /**
570 * Returns the link in the reverse direction from the given link, by
571 * consulting the seen-links store.
572 *
573 * @param link the given link
574 * @return the reverse link or null
575 */
576 Link getReverseLink(Link link) {
577 return seenLinks.keySet().stream()
578 .filter(l -> l.src().equals(link.dst()) && l.dst().equals(link.src()))
579 .findAny()
580 .orElse(null);
581 }
582
583 /**
584 * Returns the component unidirectional links of a declared bidirectional
585 * link, by consulting the seen-links store. Caller is responsible for
586 * previously verifying bidirectionality. Returned list may be empty if
587 * errors are encountered.
588 *
589 * @param link the declared bidirectional link
590 * @return list of component unidirectional links
591 */
592 List<Link> getBidiComponentLinks(Link link) {
593 Link reverseLink = getReverseLink(link);
594 List<Link> componentLinks;
595 if (reverseLink == null) { // really should not happen if link is bidi
596 log.error("cannot find reverse link for given link: {} ... is it "
597 + "bi-directional?", link);
598 componentLinks = ImmutableList.of();
599 } else {
600 componentLinks = ImmutableList.of(reverseLink, link);
601 }
602 return componentLinks;
603 }
604
605 /**
Saurav Das45f48152018-01-18 12:07:33 -0800606 * Determines if the given link should be avoided in routing calculations by
607 * policy or design.
608 *
609 * @param link the infrastructure link being queried
610 * @return true if link should be avoided
611 */
612 boolean avoidLink(Link link) {
613 // XXX currently only avoids all pair-links. In the future can be
614 // extended to avoid any generic link
615 DeviceId src = link.src().deviceId();
616 PortNumber srcPort = link.src().port();
617 DeviceConfiguration devConfig = srManager.deviceConfiguration;
618 if (devConfig == null || !devConfig.isConfigured(src)) {
619 log.warn("Device {} not configured..cannot avoid link {}", src,
620 link);
621 return false;
622 }
623 DeviceId pairDev;
624 PortNumber pairLocalPort, pairRemotePort = null;
625 try {
626 pairDev = devConfig.getPairDeviceId(src);
627 pairLocalPort = devConfig.getPairLocalPort(src);
628 if (pairDev != null) {
629 pairRemotePort = devConfig
630 .getPairLocalPort(pairDev);
631 }
632 } catch (DeviceConfigNotFoundException e) {
633 log.warn("Pair dev for dev {} not configured..cannot avoid link {}",
634 src, link);
635 return false;
636 }
637
638 return srcPort.equals(pairLocalPort)
639 && link.dst().deviceId().equals(pairDev)
640 && link.dst().port().equals(pairRemotePort);
641 }
642
643 /**
644 * Cleans up internal LinkHandler stores.
645 *
646 * @param device the device that has been removed
647 */
648 void processDeviceRemoved(Device device) {
649 seenLinks.keySet()
650 .removeIf(key -> key.src().deviceId().equals(device.id())
651 || key.dst().deviceId().equals(device.id()));
652 }
653
654 /**
655 * Administratively disables the host location switchport if the edge device
Saurav Das9a554292018-04-27 18:42:30 -0700656 * has no viable uplinks. The caller needs to determine if such behavior is
657 * desired for the single or dual-homed host.
Saurav Das45f48152018-01-18 12:07:33 -0800658 *
Saurav Das9a554292018-04-27 18:42:30 -0700659 * @param loc the host location
Saurav Das45f48152018-01-18 12:07:33 -0800660 */
Saurav Das9a554292018-04-27 18:42:30 -0700661 void checkUplinksForHost(HostLocation loc) {
Saurav Das45f48152018-01-18 12:07:33 -0800662 try {
663 for (Link l : srManager.linkService.getDeviceLinks(loc.deviceId())) {
664 if (srManager.deviceConfiguration.isEdgeDevice(l.dst().deviceId())
665 || l.state() == Link.State.INACTIVE) {
666 continue;
667 }
668 // found valid uplink - so, nothing to do
669 return;
670 }
671 } catch (DeviceConfigNotFoundException e) {
672 log.warn("Could not check for valid uplinks due to missing device"
673 + "config " + e.getMessage());
674 return;
675 }
Saurav Das9a554292018-04-27 18:42:30 -0700676 log.warn("Host location {} has no valid uplinks disabling port", loc);
Saurav Das45f48152018-01-18 12:07:33 -0800677 srManager.deviceAdminService.changePortState(loc.deviceId(), loc.port(),
678 false);
679 Set<PortNumber> p = downedPortStore.get(loc.deviceId());
680 if (p == null) {
681 p = Sets.newHashSet(loc.port());
682 } else {
683 p.add(loc.port());
684 }
685 downedPortStore.put(loc.deviceId(), p);
686 }
687
Saurav Dasc568c342018-01-25 09:49:01 -0800688 ImmutableMap<Link, Boolean> getSeenLinks() {
689 return ImmutableMap.copyOf(seenLinks);
690 }
691
692 ImmutableMap<DeviceId, Set<PortNumber>> getDownedPorts() {
693 return ImmutableMap.copyOf(downedPortStore.entrySet());
694 }
695
Saurav Das604ab3a2018-03-18 21:28:15 -0700696 /**
697 * Returns all links that egress from given device that are UP in the
698 * seenLinks store. The returned links are also confirmed to be
699 * bidirectional.
700 *
701 * @param deviceId the device identifier
702 * @return set of egress links from the device
703 */
704 Set<Link> getDeviceEgressLinks(DeviceId deviceId) {
705 return seenLinks.keySet().stream()
706 .filter(link -> link.src().deviceId().equals(deviceId))
707 .filter(link -> seenLinks.get(link))
708 .filter(link -> isBidirectionalLinkUp(link))
709 .collect(Collectors.toSet());
710 }
711
Saurav Das45f48152018-01-18 12:07:33 -0800712}