blob: aac8fc2887e1a0674549a4e24e93efea0822ab72 [file] [log] [blame]
Saurav Dase6c448a2018-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 Dasdc7f2752018-03-18 21:28:15 -070019import java.util.List;
Saurav Dase6c448a2018-01-18 12:07:33 -080020import java.util.Map;
21import java.util.Map.Entry;
22import java.util.Set;
23import java.util.concurrent.ConcurrentHashMap;
Saurav Das6430f412018-01-25 09:49:01 -080024import java.util.stream.Collectors;
25
Saurav Dase6c448a2018-01-18 12:07:33 -080026import org.onosproject.net.Device;
27import org.onosproject.net.DeviceId;
28import org.onosproject.net.HostLocation;
29import org.onosproject.net.Link;
30import org.onosproject.net.PortNumber;
31import org.onosproject.net.link.LinkService;
32import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
33import org.onosproject.segmentrouting.config.DeviceConfiguration;
34import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
35import org.onosproject.store.service.EventuallyConsistentMap;
36import org.onosproject.store.service.EventuallyConsistentMapBuilder;
37import org.onosproject.store.service.WallClockTimestamp;
38import org.slf4j.Logger;
39import org.slf4j.LoggerFactory;
40
Saurav Dasdc7f2752018-03-18 21:28:15 -070041import com.google.common.collect.ImmutableList;
Saurav Das6430f412018-01-25 09:49:01 -080042import com.google.common.collect.ImmutableMap;
Saurav Dase6c448a2018-01-18 12:07:33 -080043import com.google.common.collect.Sets;
44
Saurav Dasdc7f2752018-03-18 21:28:15 -070045
Saurav Dase6c448a2018-01-18 12:07:33 -080046public class LinkHandler {
47 private static final Logger log = LoggerFactory.getLogger(LinkHandler.class);
48 protected final SegmentRoutingManager srManager;
49 protected LinkService linkService;
50
51 // Local store for all links seen and their present status, used for
Saurav Das6430f412018-01-25 09:49:01 -080052 // optimized routing. The existence of the link in the keys is enough to know
Saurav Dase6c448a2018-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 Das6430f412018-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 Dase6c448a2018-01-18 12:07:33 -080057 private Map<Link, Boolean> seenLinks = new ConcurrentHashMap<>();
Saurav Dasdc7f2752018-03-18 21:28:15 -070058 private Set<Link> seenBefore = Sets.newConcurrentHashSet();
Saurav Dase6c448a2018-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;
68 linkService = srManager.linkService;
69 log.debug("Creating EC map downedportstore");
70 EventuallyConsistentMapBuilder<DeviceId, Set<PortNumber>> downedPortsMapBuilder
71 = srManager.storageService.eventuallyConsistentMapBuilder();
72 downedPortStore = downedPortsMapBuilder.withName("downedportstore")
73 .withSerializer(srManager.createSerializer())
74 .withTimestampProvider((k, v) -> new WallClockTimestamp())
75 .build();
76 log.trace("Current size {}", downedPortStore.size());
77 }
78
79 /**
80 * Constructs the LinkHandler for unit-testing.
81 *
82 * @param srManager SegmentRoutingManager
83 * @param linkService LinkService
84 */
85 LinkHandler(SegmentRoutingManager srManager, LinkService linkService) {
86 this.srManager = srManager;
87 this.linkService = linkService;
88 }
89
90 /**
Saurav Dase321cff2018-02-09 17:26:45 -080091 * Initialize LinkHandler.
92 */
Charles Chanc12c3d02018-03-09 15:53:44 -080093 void init() {
Saurav Dase321cff2018-02-09 17:26:45 -080094 log.info("Loading stored links");
Charles Chanc12c3d02018-03-09 15:53:44 -080095 srManager.linkService.getActiveLinks().forEach(this::processLinkAdded);
Saurav Dase321cff2018-02-09 17:26:45 -080096 }
97
98 /**
Saurav Dase6c448a2018-01-18 12:07:33 -080099 * Preprocessing of added link before being sent for route-path handling.
100 * Also performs post processing of link.
101 *
102 * @param link the link to be processed
103 */
104 void processLinkAdded(Link link) {
105 log.info("** LINK ADDED {}", link.toString());
106 if (!isLinkValid(link)) {
107 return;
108 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800109 // Irrespective of whether the local is a MASTER or not for this device,
Saurav Das6430f412018-01-25 09:49:01 -0800110 // create group handler instance and push default TTP flow rules if needed,
Saurav Dase6c448a2018-01-18 12:07:33 -0800111 // as in a multi-instance setup, instances can initiate groups for any
Saurav Das97241862018-02-14 14:14:54 -0800112 // device. Also update local groupHandler stores.
Saurav Dase6c448a2018-01-18 12:07:33 -0800113 DefaultGroupHandler groupHandler = srManager.groupHandlerMap
Saurav Das97241862018-02-14 14:14:54 -0800114 .get(link.src().deviceId());
Saurav Dase6c448a2018-01-18 12:07:33 -0800115 if (groupHandler != null) {
116 groupHandler.portUpForLink(link);
117 } else {
Saurav Dase6c448a2018-01-18 12:07:33 -0800118 Device device = srManager.deviceService.getDevice(link.src().deviceId());
119 if (device != null) {
Saurav Das97241862018-02-14 14:14:54 -0800120 log.warn("processLinkAdded: Link Added notification without "
121 + "Device Added event, still handling it");
Saurav Dase6c448a2018-01-18 12:07:33 -0800122 srManager.processDeviceAdded(device);
123 groupHandler = srManager.groupHandlerMap.get(link.src().deviceId());
Saurav Das97241862018-02-14 14:14:54 -0800124 if (groupHandler != null) {
125 groupHandler.portUpForLink(link);
126 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800127 }
128 }
Saurav Dasdc7f2752018-03-18 21:28:15 -0700129
130 if (isSeenLink(link)) {
131 // temp store retains previous state, just before the state is updated in
132 // seenLinks; previous state is necessary when processing the
133 // linkupdate in defaultRoutingHandler
134 seenBefore.add(link);
135 }
136 updateSeenLink(link, true);
137
Saurav Das97241862018-02-14 14:14:54 -0800138 if (srManager.deviceConfiguration == null ||
139 !srManager.deviceConfiguration.isConfigured(link.src().deviceId())) {
Saurav Das97241862018-02-14 14:14:54 -0800140 log.warn("Source device of this link is not configured.. "
141 + "not processing further");
142 return;
143 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800144
Saurav Dasdc7f2752018-03-18 21:28:15 -0700145 // process link only if it is bidirectional
146 if (!isBidirectionalLinkUp(link)) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800147 log.debug("Link not bidirectional.. waiting for other direction " +
Saurav Dasdc7f2752018-03-18 21:28:15 -0700148 "src {} --> dst {} ", link.dst(), link.src());
149 return;
150 }
151 log.info("processing bidi links {} <--> {} UP", link.src(), link.dst());
Saurav Dase6c448a2018-01-18 12:07:33 -0800152
Saurav Dasdc7f2752018-03-18 21:28:15 -0700153 for (Link ulink : getBidiComponentLinks(link)) {
154 log.info("Starting optimized route-path processing for component "
155 + "unidirectional link {} --> {} UP", ulink.src(), ulink.dst());
156 srManager.defaultRoutingHandler
157 .populateRoutingRulesForLinkStatusChange(null, ulink, null,
158 seenBefore.contains(ulink));
Saurav Dase6c448a2018-01-18 12:07:33 -0800159
Saurav Dasdc7f2752018-03-18 21:28:15 -0700160 if (srManager.mastershipService.isLocalMaster(ulink.src().deviceId())) {
161 // handle edge-ports for dual-homed hosts
162 updateDualHomedHostPorts(ulink, true);
Saurav Dase6c448a2018-01-18 12:07:33 -0800163
Saurav Dasdc7f2752018-03-18 21:28:15 -0700164 // It's possible that linkUp causes no route-path change as ECMP graph does
165 // not change if the link is a parallel link (same src-dst as
166 // another link). However we still need to update ECMP hash
167 // groups to include new buckets for the link that has come up.
168 if (groupHandler != null) {
169 if (!seenBefore.contains(ulink) && isParallelLink(ulink)) {
170 // if link seen first time, we need to ensure hash-groups have
171 // all ports
172 log.debug("Attempting retryHash for paralled first-time link {}",
173 ulink);
174 groupHandler.retryHash(ulink, false, true);
175 } else {
176 // seen before-link
177 if (isParallelLink(ulink)) {
178 log.debug("Attempting retryHash for paralled seen-before "
179 + "link {}", ulink);
180 groupHandler.retryHash(ulink, false, false);
181 }
Ray Milkey43969b92018-01-24 10:41:14 -0800182 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800183 }
184 }
Saurav Dasdc7f2752018-03-18 21:28:15 -0700185 //clean up temp state
186 seenBefore.remove(ulink);
Saurav Dase6c448a2018-01-18 12:07:33 -0800187 }
Saurav Dasdc7f2752018-03-18 21:28:15 -0700188
Saurav Dase6c448a2018-01-18 12:07:33 -0800189 }
190
191 /**
192 * Preprocessing of removed link before being sent for route-path handling.
193 * Also performs post processing of link.
194 *
195 * @param link the link to be processed
196 */
197 void processLinkRemoved(Link link) {
198 log.info("** LINK REMOVED {}", link.toString());
199 if (!isLinkValid(link)) {
200 return;
201 }
202 // when removing links, update seen links first, before doing route-path
203 // changes
204 updateSeenLink(link, false);
Saurav Das6430f412018-01-25 09:49:01 -0800205 // handle edge-ports for dual-homed hosts
206 if (srManager.mastershipService.isLocalMaster(link.src().deviceId())) {
207 updateDualHomedHostPorts(link, false);
208 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800209
210 // device availability check helps to ensure that multiple link-removed
211 // events are actually treated as a single switch removed event.
212 // purgeSeenLink is necessary so we do rerouting (instead of rehashing)
213 // when switch comes back.
214 if (link.src().elementId() instanceof DeviceId
215 && !srManager.deviceService.isAvailable(link.src().deviceId())) {
216 purgeSeenLink(link);
217 return;
218 }
219 if (link.dst().elementId() instanceof DeviceId
220 && !srManager.deviceService.isAvailable(link.dst().deviceId())) {
221 purgeSeenLink(link);
222 return;
223 }
224
Saurav Dasdc7f2752018-03-18 21:28:15 -0700225 // process link only if it is bidirectional
226 if (!isBidirectionalLinkDown(link)) {
227 log.debug("Link not bidirectional.. waiting for other direction " +
228 "src {} --> dst {} ", link.dst(), link.src());
229 return;
230 }
231 log.info("processing bidi links {} <--> {} DOWN", link.src(), link.dst());
Saurav Dase6c448a2018-01-18 12:07:33 -0800232
Saurav Dasdc7f2752018-03-18 21:28:15 -0700233 for (Link ulink : getBidiComponentLinks(link)) {
234 log.info("Starting optimized route-path processing for component "
235 + "unidirectional link {} --> {} DOWN", ulink.src(), ulink.dst());
236 srManager.defaultRoutingHandler
237 .populateRoutingRulesForLinkStatusChange(ulink, null, null, true);
238
239 // attempt rehashing for parallel links
240 DefaultGroupHandler groupHandler = srManager.groupHandlerMap
241 .get(ulink.src().deviceId());
242 if (groupHandler != null) {
243 if (srManager.mastershipService.isLocalMaster(ulink.src().deviceId())
244 && isParallelLink(ulink)) {
245 log.debug("* retrying hash for parallel link removed:{}", ulink);
246 groupHandler.retryHash(ulink, true, false);
247 } else {
248 log.debug("Not attempting retry-hash for link removed: {} .. {}",
249 ulink,
250 (srManager.mastershipService.isLocalMaster(ulink
251 .src().deviceId())) ? "not parallel"
252 : "not master");
253 }
254 // ensure local stores are updated after all rerouting or rehashing
255 groupHandler.portDownForLink(ulink);
Saurav Dase6c448a2018-01-18 12:07:33 -0800256 } else {
Saurav Dasdc7f2752018-03-18 21:28:15 -0700257 log.warn("group handler not found for dev:{} when removing link: {}",
258 ulink.src().deviceId(), ulink);
Saurav Dase6c448a2018-01-18 12:07:33 -0800259 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800260 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800261 }
262
263 /**
264 * Checks validity of link. Examples of invalid links include
265 * indirect-links, links between ports on the same switch, and more.
266 *
267 * @param link the link to be processed
268 * @return true if valid link
269 */
Pier Luigid8a15162018-02-15 16:33:08 +0100270 boolean isLinkValid(Link link) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800271 if (link.type() != Link.Type.DIRECT) {
272 // NOTE: A DIRECT link might be transiently marked as INDIRECT
273 // if BDDP is received before LLDP. We can safely ignore that
274 // until the LLDP is received and the link is marked as DIRECT.
275 log.info("Ignore link {}->{}. Link type is {} instead of DIRECT.",
276 link.src(), link.dst(), link.type());
277 return false;
278 }
279 DeviceId srcId = link.src().deviceId();
280 DeviceId dstId = link.dst().deviceId();
281 if (srcId.equals(dstId)) {
282 log.warn("Links between ports on the same switch are not "
283 + "allowed .. ignoring link {}", link);
284 return false;
285 }
286 DeviceConfiguration devConfig = srManager.deviceConfiguration;
Saurav Dase321cff2018-02-09 17:26:45 -0800287 if (devConfig == null) {
288 log.warn("Cannot check validity of link without device config");
289 return true;
290 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800291 try {
Saurav Das97241862018-02-14 14:14:54 -0800292 /*if (!devConfig.isEdgeDevice(srcId)
Saurav Dase6c448a2018-01-18 12:07:33 -0800293 && !devConfig.isEdgeDevice(dstId)) {
294 // ignore links between spines
295 // XXX revisit when handling multi-stage fabrics
296 log.warn("Links between spines not allowed...ignoring "
297 + "link {}", link);
298 return false;
Saurav Das97241862018-02-14 14:14:54 -0800299 }*/
Saurav Dase6c448a2018-01-18 12:07:33 -0800300 if (devConfig.isEdgeDevice(srcId)
301 && devConfig.isEdgeDevice(dstId)) {
302 // ignore links between leaves if they are not pair-links
303 // XXX revisit if removing pair-link config or allowing more than
304 // one pair-link
305 if (devConfig.getPairDeviceId(srcId).equals(dstId)
306 && devConfig.getPairLocalPort(srcId)
307 .equals(link.src().port())
308 && devConfig.getPairLocalPort(dstId)
309 .equals(link.dst().port())) {
310 // found pair link - allow it
311 return true;
312 } else {
313 log.warn("Links between leaves other than pair-links are "
314 + "not allowed...ignoring link {}", link);
315 return false;
316 }
317 }
318 } catch (DeviceConfigNotFoundException e) {
319 // We still want to count the links in seenLinks even though there
320 // is no config. So we let it return true
321 log.warn("Could not check validity of link {} as subtending devices "
322 + "are not yet configured", link);
323 }
324 return true;
325 }
326
327 /**
328 * Administratively enables or disables edge ports if the link that was
329 * added or removed was the only uplink port from an edge device. Only edge
330 * ports that belong to dual-homed hosts are considered.
331 *
332 * @param link the link to be processed
333 * @param added true if link was added, false if link was removed
334 */
335 private void updateDualHomedHostPorts(Link link, boolean added) {
Saurav Das6430f412018-01-25 09:49:01 -0800336 if (!onlyUplink(link)) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800337 return;
338 }
339 if (added) {
340 // re-enable previously disabled ports on this dev
341 Set<PortNumber> p = downedPortStore.remove(link.src().deviceId());
342 if (p != null) {
343 log.warn("Link src {} -->dst {} added is the first uplink, "
344 + "enabling dual homed ports: {}", link.src().deviceId(),
345 link.dst().deviceId(), (p.isEmpty()) ? "no ports" : p);
346 p.forEach(pnum -> srManager.deviceAdminService
347 .changePortState(link.src().deviceId(), pnum, true));
348 }
349 } else {
350 // find dual homed hosts on this dev to disable
351 Set<PortNumber> dhp = srManager.hostHandler
352 .getDualHomedHostPorts(link.src().deviceId());
353 log.warn("Link src {} -->dst {} removed was the last uplink, "
354 + "disabling dual homed ports: {}", link.src().deviceId(),
355 link.dst().deviceId(), (dhp.isEmpty()) ? "no ports" : dhp);
356 dhp.forEach(pnum -> srManager.deviceAdminService
357 .changePortState(link.src().deviceId(), pnum, false));
358 if (!dhp.isEmpty()) {
359 // update global store
360 Set<PortNumber> p = downedPortStore.get(link.src().deviceId());
361 if (p == null) {
362 p = dhp;
363 } else {
364 p.addAll(dhp);
365 }
366 downedPortStore.put(link.src().deviceId(), p);
367 }
368 }
369 }
370
371 /**
Saurav Das6430f412018-01-25 09:49:01 -0800372 * Returns true if given link is the only active uplink from src-device of
Saurav Dase6c448a2018-01-18 12:07:33 -0800373 * link. An uplink is defined as a unidirectional link with src as
374 * edgeRouter and dst as non-edgeRouter.
375 *
376 * @param link
377 * @return true if given link is-the-first/was-the-last uplink from the src
378 * device
379 */
Saurav Das6430f412018-01-25 09:49:01 -0800380 private boolean onlyUplink(Link link) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800381 DeviceConfiguration devConfig = srManager.deviceConfiguration;
382 try {
Saurav Das6430f412018-01-25 09:49:01 -0800383 if (!devConfig.isEdgeDevice(link.src().deviceId())
384 || devConfig.isEdgeDevice(link.dst().deviceId())) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800385 return false;
386 }
Saurav Das6430f412018-01-25 09:49:01 -0800387 // note that using linkservice here would cause race conditions as
388 // more links can show up while the app is still processing the first one
389 Set<Link> devLinks = seenLinks.entrySet().stream()
390 .filter(entry -> entry.getKey().src().deviceId()
391 .equals(link.src().deviceId()))
392 .filter(entry -> entry.getValue())
393 .filter(entry -> !entry.getKey().equals(link))
394 .map(entry -> entry.getKey())
395 .collect(Collectors.toSet());
396
Saurav Dase6c448a2018-01-18 12:07:33 -0800397 for (Link l : devLinks) {
Saurav Das6430f412018-01-25 09:49:01 -0800398 if (devConfig.isEdgeDevice(l.dst().deviceId())) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800399 continue;
400 }
Saurav Das6430f412018-01-25 09:49:01 -0800401 log.debug("Link {} is not the only active uplink. Found another"
402 + "link {}", link, l);
403 return false;
Saurav Dase6c448a2018-01-18 12:07:33 -0800404 }
Saurav Das6430f412018-01-25 09:49:01 -0800405 log.debug("Link {} is the only uplink", link);
406 return true;
Saurav Dase6c448a2018-01-18 12:07:33 -0800407 } catch (DeviceConfigNotFoundException e) {
Saurav Das6430f412018-01-25 09:49:01 -0800408 log.warn("Unable to determine if link is only uplink"
Saurav Dase6c448a2018-01-18 12:07:33 -0800409 + e.getMessage());
410 }
411 return false;
412 }
413
414 /**
415 * Returns true if this controller instance has seen this link before. The
416 * link may not be currently up, but as long as the link had been seen
417 * before this method will return true. The one exception is when the link
418 * was indeed seen before, but this controller instance was forced to forget
419 * it by a call to purgeSeenLink method.
420 *
421 * @param link the infrastructure link being queried
422 * @return true if this controller instance has seen this link before
423 */
424 boolean isSeenLink(Link link) {
425 return seenLinks.containsKey(link);
426 }
427
428 /**
429 * Updates the seen link store. Updates can be for links that are currently
430 * available or not.
431 *
432 * @param link the link to update in the seen-link local store
433 * @param up the status of the link, true if up, false if down
434 */
435 void updateSeenLink(Link link, boolean up) {
436 seenLinks.put(link, up);
437 }
438
439 /**
440 * Returns the status of a seen-link (up or down). If the link has not been
441 * seen-before, a null object is returned.
442 *
443 * @param link the infrastructure link being queried
444 * @return null if the link was not seen-before; true if the seen-link is
445 * up; false if the seen-link is down
446 */
447 private Boolean isSeenLinkUp(Link link) {
448 return seenLinks.get(link);
449 }
450
451 /**
452 * Makes this controller instance forget a previously seen before link.
453 *
454 * @param link the infrastructure link to purge
455 */
456 private void purgeSeenLink(Link link) {
457 seenLinks.remove(link);
Saurav Dasdc7f2752018-03-18 21:28:15 -0700458 seenBefore.remove(link);
Saurav Dase6c448a2018-01-18 12:07:33 -0800459 }
460
461 /**
462 * Returns the status of a link as parallel link. A parallel link is defined
463 * as a link which has common src and dst switches as another seen-link that
464 * is currently enabled. It is not necessary for the link being queried to
465 * be a seen-link.
466 *
467 * @param link the infrastructure link being queried
468 * @return true if a seen-link exists that is up, and shares the same src
469 * and dst switches as the link being queried
470 */
471 private boolean isParallelLink(Link link) {
472 for (Entry<Link, Boolean> seen : seenLinks.entrySet()) {
473 Link seenLink = seen.getKey();
474 if (seenLink.equals(link)) {
475 continue;
476 }
477 if (seenLink.src().deviceId().equals(link.src().deviceId())
478 && seenLink.dst().deviceId().equals(link.dst().deviceId())
479 && seen.getValue()) {
480 return true;
481 }
482 }
483 return false;
484 }
485
486 /**
Saurav Dasdc7f2752018-03-18 21:28:15 -0700487 * Returns true if the link being queried is a bidirectional link that is
488 * up. A bidi-link is defined as a component unidirectional link, whose
489 * reverse link - ie. the component unidirectional link in the reverse
490 * direction - has been seen-before and is up. It is NOT necessary for the
491 * link being queried to be a previously seen-link.
Saurav Dase6c448a2018-01-18 12:07:33 -0800492 *
Saurav Dasdc7f2752018-03-18 21:28:15 -0700493 * @param link the infrastructure (unidirectional) link being queried
Saurav Dase6c448a2018-01-18 12:07:33 -0800494 * @return true if another unidirectional link exists in the reverse
495 * direction, has been seen-before and is up
496 */
Saurav Dasdc7f2752018-03-18 21:28:15 -0700497 boolean isBidirectionalLinkUp(Link link) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800498 Link reverseLink = linkService.getLink(link.dst(), link.src());
499 if (reverseLink == null) {
500 return false;
501 }
502 Boolean result = isSeenLinkUp(reverseLink);
503 if (result == null) {
504 return false;
505 }
506 return result.booleanValue();
507 }
508
509 /**
Saurav Dasdc7f2752018-03-18 21:28:15 -0700510 * Returns true if the link being queried is a bidirectional link that is
511 * down. A bidi-link is defined as a component unidirectional link, whose
512 * reverse link - i.e the component unidirectional link in the reverse
513 * direction - has been seen before and is down. It is necessary for the
514 * reverse-link to have been previously seen.
515 *
516 * @param link the infrastructure (unidirectional) link being queried
517 * @return true if another unidirectional link exists in the reverse
518 * direction, has been seen-before and is down
519 */
520 boolean isBidirectionalLinkDown(Link link) {
521 // cannot call linkService as link may be gone
522 Link reverseLink = getReverseLink(link);
523 if (reverseLink == null) {
524 log.warn("Query for bidi-link down but reverse-link not found "
525 + "for link {}", link);
526 return false;
527 }
528 Boolean result = seenLinks.get(reverseLink);
529 if (result == null) {
530 return false;
531 }
532 // if reverse link is seen UP (true), then its not bidi yet
533 return !result.booleanValue();
534 }
535
536 /**
537 * Returns the link in the reverse direction from the given link, by
538 * consulting the seen-links store.
539 *
540 * @param link the given link
541 * @return the reverse link or null
542 */
543 Link getReverseLink(Link link) {
544 return seenLinks.keySet().stream()
545 .filter(l -> l.src().equals(link.dst()) && l.dst().equals(link.src()))
546 .findAny()
547 .orElse(null);
548 }
549
550 /**
551 * Returns the component unidirectional links of a declared bidirectional
552 * link, by consulting the seen-links store. Caller is responsible for
553 * previously verifying bidirectionality. Returned list may be empty if
554 * errors are encountered.
555 *
556 * @param link the declared bidirectional link
557 * @return list of component unidirectional links
558 */
559 List<Link> getBidiComponentLinks(Link link) {
560 Link reverseLink = getReverseLink(link);
561 List<Link> componentLinks;
562 if (reverseLink == null) { // really should not happen if link is bidi
563 log.error("cannot find reverse link for given link: {} ... is it "
564 + "bi-directional?", link);
565 componentLinks = ImmutableList.of();
566 } else {
567 componentLinks = ImmutableList.of(reverseLink, link);
568 }
569 return componentLinks;
570 }
571
572 /**
Saurav Dase6c448a2018-01-18 12:07:33 -0800573 * Determines if the given link should be avoided in routing calculations by
574 * policy or design.
575 *
576 * @param link the infrastructure link being queried
577 * @return true if link should be avoided
578 */
579 boolean avoidLink(Link link) {
580 // XXX currently only avoids all pair-links. In the future can be
581 // extended to avoid any generic link
582 DeviceId src = link.src().deviceId();
583 PortNumber srcPort = link.src().port();
584 DeviceConfiguration devConfig = srManager.deviceConfiguration;
585 if (devConfig == null || !devConfig.isConfigured(src)) {
586 log.warn("Device {} not configured..cannot avoid link {}", src,
587 link);
588 return false;
589 }
590 DeviceId pairDev;
591 PortNumber pairLocalPort, pairRemotePort = null;
592 try {
593 pairDev = devConfig.getPairDeviceId(src);
594 pairLocalPort = devConfig.getPairLocalPort(src);
595 if (pairDev != null) {
596 pairRemotePort = devConfig
597 .getPairLocalPort(pairDev);
598 }
599 } catch (DeviceConfigNotFoundException e) {
600 log.warn("Pair dev for dev {} not configured..cannot avoid link {}",
601 src, link);
602 return false;
603 }
604
605 return srcPort.equals(pairLocalPort)
606 && link.dst().deviceId().equals(pairDev)
607 && link.dst().port().equals(pairRemotePort);
608 }
609
610 /**
611 * Cleans up internal LinkHandler stores.
612 *
613 * @param device the device that has been removed
614 */
615 void processDeviceRemoved(Device device) {
616 seenLinks.keySet()
617 .removeIf(key -> key.src().deviceId().equals(device.id())
618 || key.dst().deviceId().equals(device.id()));
619 }
620
621 /**
622 * Administratively disables the host location switchport if the edge device
623 * has no viable uplinks.
624 *
625 * @param loc one of the locations of the dual-homed host
626 */
627 void checkUplinksForDualHomedHosts(HostLocation loc) {
628 try {
629 for (Link l : srManager.linkService.getDeviceLinks(loc.deviceId())) {
630 if (srManager.deviceConfiguration.isEdgeDevice(l.dst().deviceId())
631 || l.state() == Link.State.INACTIVE) {
632 continue;
633 }
634 // found valid uplink - so, nothing to do
635 return;
636 }
637 } catch (DeviceConfigNotFoundException e) {
638 log.warn("Could not check for valid uplinks due to missing device"
639 + "config " + e.getMessage());
640 return;
641 }
642 log.warn("Dual homed host location {} has no valid uplinks; "
643 + "disabling dual homed port", loc);
644 srManager.deviceAdminService.changePortState(loc.deviceId(), loc.port(),
645 false);
646 Set<PortNumber> p = downedPortStore.get(loc.deviceId());
647 if (p == null) {
648 p = Sets.newHashSet(loc.port());
649 } else {
650 p.add(loc.port());
651 }
652 downedPortStore.put(loc.deviceId(), p);
653 }
654
Saurav Das6430f412018-01-25 09:49:01 -0800655 ImmutableMap<Link, Boolean> getSeenLinks() {
656 return ImmutableMap.copyOf(seenLinks);
657 }
658
659 ImmutableMap<DeviceId, Set<PortNumber>> getDownedPorts() {
660 return ImmutableMap.copyOf(downedPortStore.entrySet());
661 }
662
Saurav Dasdc7f2752018-03-18 21:28:15 -0700663 /**
664 * Returns all links that egress from given device that are UP in the
665 * seenLinks store. The returned links are also confirmed to be
666 * bidirectional.
667 *
668 * @param deviceId the device identifier
669 * @return set of egress links from the device
670 */
671 Set<Link> getDeviceEgressLinks(DeviceId deviceId) {
672 return seenLinks.keySet().stream()
673 .filter(link -> link.src().deviceId().equals(deviceId))
674 .filter(link -> seenLinks.get(link))
675 .filter(link -> isBidirectionalLinkUp(link))
676 .collect(Collectors.toSet());
677 }
678
Saurav Dase6c448a2018-01-18 12:07:33 -0800679}