blob: 23caadc81914bd345ef2ddb132fac6c1ecadf7f7 [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;
Saurav Dase6c448a2018-01-18 12:07:33 -080049
50 // Local store for all links seen and their present status, used for
Saurav Das6430f412018-01-25 09:49:01 -080051 // optimized routing. The existence of the link in the keys is enough to know
Saurav Dase6c448a2018-01-18 12:07:33 -080052 // if the link has been "seen-before" by this instance of the controller.
53 // The boolean value indicates if the link is currently up or not.
Saurav Das6430f412018-01-25 09:49:01 -080054 // Currently the optimized routing logic depends on "forgetting" a link
55 // when a switch goes down, but "remembering" it when only the link goes down.
Saurav Dase6c448a2018-01-18 12:07:33 -080056 private Map<Link, Boolean> seenLinks = new ConcurrentHashMap<>();
Saurav Dasdc7f2752018-03-18 21:28:15 -070057 private Set<Link> seenBefore = Sets.newConcurrentHashSet();
Saurav Dase6c448a2018-01-18 12:07:33 -080058 private EventuallyConsistentMap<DeviceId, Set<PortNumber>> downedPortStore = null;
59
60 /**
61 * Constructs the LinkHandler.
62 *
63 * @param srManager Segment Routing manager
64 */
65 LinkHandler(SegmentRoutingManager srManager) {
66 this.srManager = srManager;
Saurav Dase6c448a2018-01-18 12:07:33 -080067 log.debug("Creating EC map downedportstore");
68 EventuallyConsistentMapBuilder<DeviceId, Set<PortNumber>> downedPortsMapBuilder
69 = srManager.storageService.eventuallyConsistentMapBuilder();
70 downedPortStore = downedPortsMapBuilder.withName("downedportstore")
71 .withSerializer(srManager.createSerializer())
72 .withTimestampProvider((k, v) -> new WallClockTimestamp())
73 .build();
74 log.trace("Current size {}", downedPortStore.size());
75 }
76
77 /**
78 * Constructs the LinkHandler for unit-testing.
79 *
80 * @param srManager SegmentRoutingManager
81 * @param linkService LinkService
82 */
83 LinkHandler(SegmentRoutingManager srManager, LinkService linkService) {
84 this.srManager = srManager;
Saurav Dase6c448a2018-01-18 12:07:33 -080085 }
86
87 /**
Saurav Dase321cff2018-02-09 17:26:45 -080088 * Initialize LinkHandler.
89 */
Charles Chanc12c3d02018-03-09 15:53:44 -080090 void init() {
Saurav Dase321cff2018-02-09 17:26:45 -080091 log.info("Loading stored links");
Charles Chanc12c3d02018-03-09 15:53:44 -080092 srManager.linkService.getActiveLinks().forEach(this::processLinkAdded);
Saurav Dase321cff2018-02-09 17:26:45 -080093 }
94
95 /**
Saurav Dase6c448a2018-01-18 12:07:33 -080096 * Preprocessing of added link before being sent for route-path handling.
97 * Also performs post processing of link.
98 *
99 * @param link the link to be processed
100 */
101 void processLinkAdded(Link link) {
102 log.info("** LINK ADDED {}", link.toString());
103 if (!isLinkValid(link)) {
104 return;
105 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800106 // Irrespective of whether the local is a MASTER or not for this device,
Saurav Das6430f412018-01-25 09:49:01 -0800107 // create group handler instance and push default TTP flow rules if needed,
Saurav Dase6c448a2018-01-18 12:07:33 -0800108 // as in a multi-instance setup, instances can initiate groups for any
Saurav Das97241862018-02-14 14:14:54 -0800109 // device. Also update local groupHandler stores.
Saurav Dase6c448a2018-01-18 12:07:33 -0800110 DefaultGroupHandler groupHandler = srManager.groupHandlerMap
Saurav Das97241862018-02-14 14:14:54 -0800111 .get(link.src().deviceId());
Saurav Dasdebcf882018-04-06 20:16:01 -0700112 if (groupHandler == null) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800113 Device device = srManager.deviceService.getDevice(link.src().deviceId());
114 if (device != null) {
Saurav Das97241862018-02-14 14:14:54 -0800115 log.warn("processLinkAdded: Link Added notification without "
116 + "Device Added event, still handling it");
Saurav Dase6c448a2018-01-18 12:07:33 -0800117 srManager.processDeviceAdded(device);
Saurav Dase6c448a2018-01-18 12:07:33 -0800118 }
119 }
Saurav Dasdc7f2752018-03-18 21:28:15 -0700120
121 if (isSeenLink(link)) {
122 // temp store retains previous state, just before the state is updated in
123 // seenLinks; previous state is necessary when processing the
124 // linkupdate in defaultRoutingHandler
125 seenBefore.add(link);
126 }
127 updateSeenLink(link, true);
128
Saurav Das97241862018-02-14 14:14:54 -0800129 if (srManager.deviceConfiguration == null ||
130 !srManager.deviceConfiguration.isConfigured(link.src().deviceId())) {
Saurav Das97241862018-02-14 14:14:54 -0800131 log.warn("Source device of this link is not configured.. "
132 + "not processing further");
133 return;
134 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800135
Saurav Dasdc7f2752018-03-18 21:28:15 -0700136 // process link only if it is bidirectional
137 if (!isBidirectionalLinkUp(link)) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800138 log.debug("Link not bidirectional.. waiting for other direction " +
Saurav Dasdc7f2752018-03-18 21:28:15 -0700139 "src {} --> dst {} ", link.dst(), link.src());
140 return;
141 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800142
Saurav Dasdebcf882018-04-06 20:16:01 -0700143 log.info("processing bidi links {} <--> {} UP", link.src(), link.dst());
144 // update groupHandler internal port state for both directions
145 List<Link> ulinks = getBidiComponentLinks(link);
146 for (Link ulink : ulinks) {
147 DefaultGroupHandler gh = srManager.groupHandlerMap
148 .get(ulink.src().deviceId());
149 if (gh != null) {
150 gh.portUpForLink(ulink);
151 }
152 }
153
154 for (Link ulink : ulinks) {
155 log.info("-- Starting optimized route-path processing for component "
Saurav Dasdc7f2752018-03-18 21:28:15 -0700156 + "unidirectional link {} --> {} UP", ulink.src(), ulink.dst());
157 srManager.defaultRoutingHandler
158 .populateRoutingRulesForLinkStatusChange(null, ulink, null,
159 seenBefore.contains(ulink));
Saurav Dase6c448a2018-01-18 12:07:33 -0800160
Saurav Dasdc7f2752018-03-18 21:28:15 -0700161 if (srManager.mastershipService.isLocalMaster(ulink.src().deviceId())) {
162 // handle edge-ports for dual-homed hosts
163 updateDualHomedHostPorts(ulink, true);
Saurav Dase6c448a2018-01-18 12:07:33 -0800164
Saurav Dasdc7f2752018-03-18 21:28:15 -0700165 // It's possible that linkUp causes no route-path change as ECMP graph does
166 // not change if the link is a parallel link (same src-dst as
167 // another link). However we still need to update ECMP hash
168 // groups to include new buckets for the link that has come up.
Saurav Dasdebcf882018-04-06 20:16:01 -0700169 DefaultGroupHandler gh = srManager.groupHandlerMap
170 .get(ulink.src().deviceId());
171 if (gh != null) {
Saurav Dasdc7f2752018-03-18 21:28:15 -0700172 if (!seenBefore.contains(ulink) && isParallelLink(ulink)) {
173 // if link seen first time, we need to ensure hash-groups have
174 // all ports
175 log.debug("Attempting retryHash for paralled first-time link {}",
176 ulink);
Saurav Dasdebcf882018-04-06 20:16:01 -0700177 gh.retryHash(ulink, false, true);
Saurav Dasdc7f2752018-03-18 21:28:15 -0700178 } else {
179 // seen before-link
180 if (isParallelLink(ulink)) {
181 log.debug("Attempting retryHash for paralled seen-before "
182 + "link {}", ulink);
Saurav Dasdebcf882018-04-06 20:16:01 -0700183 gh.retryHash(ulink, false, false);
Saurav Dasdc7f2752018-03-18 21:28:15 -0700184 }
Ray Milkey43969b92018-01-24 10:41:14 -0800185 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800186 }
187 }
Saurav Dasdc7f2752018-03-18 21:28:15 -0700188 //clean up temp state
189 seenBefore.remove(ulink);
Saurav Dase6c448a2018-01-18 12:07:33 -0800190 }
Saurav Dasdc7f2752018-03-18 21:28:15 -0700191
Saurav Dase6c448a2018-01-18 12:07:33 -0800192 }
193
194 /**
195 * Preprocessing of removed link before being sent for route-path handling.
196 * Also performs post processing of link.
197 *
198 * @param link the link to be processed
199 */
200 void processLinkRemoved(Link link) {
201 log.info("** LINK REMOVED {}", link.toString());
202 if (!isLinkValid(link)) {
203 return;
204 }
205 // when removing links, update seen links first, before doing route-path
206 // changes
207 updateSeenLink(link, false);
Saurav Das6430f412018-01-25 09:49:01 -0800208 // handle edge-ports for dual-homed hosts
209 if (srManager.mastershipService.isLocalMaster(link.src().deviceId())) {
210 updateDualHomedHostPorts(link, false);
211 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800212
213 // device availability check helps to ensure that multiple link-removed
214 // events are actually treated as a single switch removed event.
215 // purgeSeenLink is necessary so we do rerouting (instead of rehashing)
216 // when switch comes back.
217 if (link.src().elementId() instanceof DeviceId
218 && !srManager.deviceService.isAvailable(link.src().deviceId())) {
219 purgeSeenLink(link);
220 return;
221 }
222 if (link.dst().elementId() instanceof DeviceId
223 && !srManager.deviceService.isAvailable(link.dst().deviceId())) {
224 purgeSeenLink(link);
225 return;
226 }
227
Saurav Dasdc7f2752018-03-18 21:28:15 -0700228 // process link only if it is bidirectional
229 if (!isBidirectionalLinkDown(link)) {
230 log.debug("Link not bidirectional.. waiting for other direction " +
231 "src {} --> dst {} ", link.dst(), link.src());
232 return;
233 }
234 log.info("processing bidi links {} <--> {} DOWN", link.src(), link.dst());
Saurav Dase6c448a2018-01-18 12:07:33 -0800235
Saurav Dasdc7f2752018-03-18 21:28:15 -0700236 for (Link ulink : getBidiComponentLinks(link)) {
Saurav Dasdebcf882018-04-06 20:16:01 -0700237 log.info("-- Starting optimized route-path processing for component "
Saurav Dasdc7f2752018-03-18 21:28:15 -0700238 + "unidirectional link {} --> {} DOWN", ulink.src(), ulink.dst());
239 srManager.defaultRoutingHandler
240 .populateRoutingRulesForLinkStatusChange(ulink, null, null, true);
241
242 // attempt rehashing for parallel links
243 DefaultGroupHandler groupHandler = srManager.groupHandlerMap
244 .get(ulink.src().deviceId());
245 if (groupHandler != null) {
246 if (srManager.mastershipService.isLocalMaster(ulink.src().deviceId())
247 && isParallelLink(ulink)) {
248 log.debug("* retrying hash for parallel link removed:{}", ulink);
249 groupHandler.retryHash(ulink, true, false);
250 } else {
251 log.debug("Not attempting retry-hash for link removed: {} .. {}",
252 ulink,
253 (srManager.mastershipService.isLocalMaster(ulink
254 .src().deviceId())) ? "not parallel"
255 : "not master");
256 }
257 // ensure local stores are updated after all rerouting or rehashing
258 groupHandler.portDownForLink(ulink);
Saurav Dase6c448a2018-01-18 12:07:33 -0800259 } else {
Saurav Dasdc7f2752018-03-18 21:28:15 -0700260 log.warn("group handler not found for dev:{} when removing link: {}",
261 ulink.src().deviceId(), ulink);
Saurav Dase6c448a2018-01-18 12:07:33 -0800262 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800263 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800264 }
265
266 /**
267 * Checks validity of link. Examples of invalid links include
268 * indirect-links, links between ports on the same switch, and more.
269 *
270 * @param link the link to be processed
271 * @return true if valid link
272 */
Pier Luigid8a15162018-02-15 16:33:08 +0100273 boolean isLinkValid(Link link) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800274 if (link.type() != Link.Type.DIRECT) {
275 // NOTE: A DIRECT link might be transiently marked as INDIRECT
276 // if BDDP is received before LLDP. We can safely ignore that
277 // until the LLDP is received and the link is marked as DIRECT.
278 log.info("Ignore link {}->{}. Link type is {} instead of DIRECT.",
279 link.src(), link.dst(), link.type());
280 return false;
281 }
282 DeviceId srcId = link.src().deviceId();
283 DeviceId dstId = link.dst().deviceId();
284 if (srcId.equals(dstId)) {
285 log.warn("Links between ports on the same switch are not "
286 + "allowed .. ignoring link {}", link);
287 return false;
288 }
289 DeviceConfiguration devConfig = srManager.deviceConfiguration;
Saurav Dase321cff2018-02-09 17:26:45 -0800290 if (devConfig == null) {
291 log.warn("Cannot check validity of link without device config");
292 return true;
293 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800294 try {
Saurav Das97241862018-02-14 14:14:54 -0800295 /*if (!devConfig.isEdgeDevice(srcId)
Saurav Dase6c448a2018-01-18 12:07:33 -0800296 && !devConfig.isEdgeDevice(dstId)) {
297 // ignore links between spines
298 // XXX revisit when handling multi-stage fabrics
299 log.warn("Links between spines not allowed...ignoring "
300 + "link {}", link);
301 return false;
Saurav Das97241862018-02-14 14:14:54 -0800302 }*/
Saurav Dase6c448a2018-01-18 12:07:33 -0800303 if (devConfig.isEdgeDevice(srcId)
304 && devConfig.isEdgeDevice(dstId)) {
305 // ignore links between leaves if they are not pair-links
306 // XXX revisit if removing pair-link config or allowing more than
307 // one pair-link
308 if (devConfig.getPairDeviceId(srcId).equals(dstId)
309 && devConfig.getPairLocalPort(srcId)
310 .equals(link.src().port())
311 && devConfig.getPairLocalPort(dstId)
312 .equals(link.dst().port())) {
313 // found pair link - allow it
314 return true;
315 } else {
316 log.warn("Links between leaves other than pair-links are "
317 + "not allowed...ignoring link {}", link);
318 return false;
319 }
320 }
321 } catch (DeviceConfigNotFoundException e) {
322 // We still want to count the links in seenLinks even though there
323 // is no config. So we let it return true
324 log.warn("Could not check validity of link {} as subtending devices "
325 + "are not yet configured", link);
326 }
327 return true;
328 }
329
330 /**
331 * Administratively enables or disables edge ports if the link that was
332 * added or removed was the only uplink port from an edge device. Only edge
333 * ports that belong to dual-homed hosts are considered.
334 *
335 * @param link the link to be processed
336 * @param added true if link was added, false if link was removed
337 */
338 private void updateDualHomedHostPorts(Link link, boolean added) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800339 if (added) {
Saurav Dasdebcf882018-04-06 20:16:01 -0700340 DeviceConfiguration devConfig = srManager.deviceConfiguration;
341 try {
342 if (!devConfig.isEdgeDevice(link.src().deviceId())
343 || devConfig.isEdgeDevice(link.dst().deviceId())) {
344 return;
345 }
346 } catch (DeviceConfigNotFoundException e) {
347 log.warn("Unable to determine if link is a valid uplink"
348 + e.getMessage());
349 }
350 // re-enable previously disabled ports on this edge-device if any
Saurav Dase6c448a2018-01-18 12:07:33 -0800351 Set<PortNumber> p = downedPortStore.remove(link.src().deviceId());
352 if (p != null) {
Saurav Dasdebcf882018-04-06 20:16:01 -0700353 log.warn("Link src {} --> dst {} added is an edge-device uplink, "
354 + "enabling dual homed ports if any: {}", link.src().deviceId(),
355 link.dst().deviceId(), (p.isEmpty()) ? "no ports" : p);
Saurav Dase6c448a2018-01-18 12:07:33 -0800356 p.forEach(pnum -> srManager.deviceAdminService
357 .changePortState(link.src().deviceId(), pnum, true));
358 }
359 } else {
Saurav Dasdebcf882018-04-06 20:16:01 -0700360 if (!lastUplink(link)) {
361 return;
362 }
Saurav Dase6c448a2018-01-18 12:07:33 -0800363 // find dual homed hosts on this dev to disable
364 Set<PortNumber> dhp = srManager.hostHandler
365 .getDualHomedHostPorts(link.src().deviceId());
366 log.warn("Link src {} -->dst {} removed was the last uplink, "
367 + "disabling dual homed ports: {}", link.src().deviceId(),
368 link.dst().deviceId(), (dhp.isEmpty()) ? "no ports" : dhp);
369 dhp.forEach(pnum -> srManager.deviceAdminService
370 .changePortState(link.src().deviceId(), pnum, false));
371 if (!dhp.isEmpty()) {
372 // update global store
373 Set<PortNumber> p = downedPortStore.get(link.src().deviceId());
374 if (p == null) {
375 p = dhp;
376 } else {
377 p.addAll(dhp);
378 }
379 downedPortStore.put(link.src().deviceId(), p);
380 }
381 }
382 }
383
384 /**
Saurav Dasdebcf882018-04-06 20:16:01 -0700385 * Returns true if given link was the last active uplink from src-device of
Saurav Dase6c448a2018-01-18 12:07:33 -0800386 * link. An uplink is defined as a unidirectional link with src as
387 * edgeRouter and dst as non-edgeRouter.
388 *
389 * @param link
Saurav Dasdebcf882018-04-06 20:16:01 -0700390 * @return true if given link was the last uplink from the src device
Saurav Dase6c448a2018-01-18 12:07:33 -0800391 */
Saurav Dasdebcf882018-04-06 20:16:01 -0700392 private boolean lastUplink(Link link) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800393 DeviceConfiguration devConfig = srManager.deviceConfiguration;
394 try {
Saurav Das6430f412018-01-25 09:49:01 -0800395 if (!devConfig.isEdgeDevice(link.src().deviceId())
396 || devConfig.isEdgeDevice(link.dst().deviceId())) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800397 return false;
398 }
Saurav Das6430f412018-01-25 09:49:01 -0800399 // note that using linkservice here would cause race conditions as
400 // more links can show up while the app is still processing the first one
401 Set<Link> devLinks = seenLinks.entrySet().stream()
402 .filter(entry -> entry.getKey().src().deviceId()
403 .equals(link.src().deviceId()))
404 .filter(entry -> entry.getValue())
405 .filter(entry -> !entry.getKey().equals(link))
406 .map(entry -> entry.getKey())
407 .collect(Collectors.toSet());
408
Saurav Dase6c448a2018-01-18 12:07:33 -0800409 for (Link l : devLinks) {
Saurav Das6430f412018-01-25 09:49:01 -0800410 if (devConfig.isEdgeDevice(l.dst().deviceId())) {
Saurav Dase6c448a2018-01-18 12:07:33 -0800411 continue;
412 }
Saurav Dasdebcf882018-04-06 20:16:01 -0700413 log.debug("Found another active uplink {}", l);
Saurav Das6430f412018-01-25 09:49:01 -0800414 return false;
Saurav Dase6c448a2018-01-18 12:07:33 -0800415 }
Saurav Dasdebcf882018-04-06 20:16:01 -0700416 log.debug("No active uplink found");
Saurav Das6430f412018-01-25 09:49:01 -0800417 return true;
Saurav Dase6c448a2018-01-18 12:07:33 -0800418 } catch (DeviceConfigNotFoundException e) {
Saurav Dasdebcf882018-04-06 20:16:01 -0700419 log.warn("Unable to determine if link was the last uplink"
Saurav Dase6c448a2018-01-18 12:07:33 -0800420 + e.getMessage());
421 }
422 return false;
423 }
424
425 /**
426 * Returns true if this controller instance has seen this link before. The
427 * link may not be currently up, but as long as the link had been seen
428 * before this method will return true. The one exception is when the link
429 * was indeed seen before, but this controller instance was forced to forget
430 * it by a call to purgeSeenLink method.
431 *
432 * @param link the infrastructure link being queried
433 * @return true if this controller instance has seen this link before
434 */
435 boolean isSeenLink(Link link) {
436 return seenLinks.containsKey(link);
437 }
438
439 /**
440 * Updates the seen link store. Updates can be for links that are currently
441 * available or not.
442 *
443 * @param link the link to update in the seen-link local store
444 * @param up the status of the link, true if up, false if down
445 */
446 void updateSeenLink(Link link, boolean up) {
447 seenLinks.put(link, up);
448 }
449
450 /**
451 * Returns the status of a seen-link (up or down). If the link has not been
452 * seen-before, a null object is returned.
453 *
454 * @param link the infrastructure link being queried
455 * @return null if the link was not seen-before; true if the seen-link is
456 * up; false if the seen-link is down
457 */
458 private Boolean isSeenLinkUp(Link link) {
459 return seenLinks.get(link);
460 }
461
462 /**
463 * Makes this controller instance forget a previously seen before link.
464 *
465 * @param link the infrastructure link to purge
466 */
467 private void purgeSeenLink(Link link) {
468 seenLinks.remove(link);
Saurav Dasdc7f2752018-03-18 21:28:15 -0700469 seenBefore.remove(link);
Saurav Dase6c448a2018-01-18 12:07:33 -0800470 }
471
472 /**
473 * Returns the status of a link as parallel link. A parallel link is defined
474 * as a link which has common src and dst switches as another seen-link that
475 * is currently enabled. It is not necessary for the link being queried to
476 * be a seen-link.
477 *
478 * @param link the infrastructure link being queried
479 * @return true if a seen-link exists that is up, and shares the same src
480 * and dst switches as the link being queried
481 */
482 private boolean isParallelLink(Link link) {
483 for (Entry<Link, Boolean> seen : seenLinks.entrySet()) {
484 Link seenLink = seen.getKey();
485 if (seenLink.equals(link)) {
486 continue;
487 }
488 if (seenLink.src().deviceId().equals(link.src().deviceId())
489 && seenLink.dst().deviceId().equals(link.dst().deviceId())
490 && seen.getValue()) {
491 return true;
492 }
493 }
494 return false;
495 }
496
497 /**
Saurav Dasdc7f2752018-03-18 21:28:15 -0700498 * Returns true if the link being queried is a bidirectional link that is
499 * up. A bidi-link is defined as a component unidirectional link, whose
500 * reverse link - ie. the component unidirectional link in the reverse
501 * direction - has been seen-before and is up. It is NOT necessary for the
502 * link being queried to be a previously seen-link.
Saurav Dase6c448a2018-01-18 12:07:33 -0800503 *
Saurav Dasdc7f2752018-03-18 21:28:15 -0700504 * @param link the infrastructure (unidirectional) link being queried
Saurav Dase6c448a2018-01-18 12:07:33 -0800505 * @return true if another unidirectional link exists in the reverse
506 * direction, has been seen-before and is up
507 */
Saurav Dasdc7f2752018-03-18 21:28:15 -0700508 boolean isBidirectionalLinkUp(Link link) {
Saurav Dasdebcf882018-04-06 20:16:01 -0700509 // cannot call linkService as link may be gone
510 Link reverseLink = getReverseLink(link);
Saurav Dase6c448a2018-01-18 12:07:33 -0800511 if (reverseLink == null) {
512 return false;
513 }
514 Boolean result = isSeenLinkUp(reverseLink);
515 if (result == null) {
516 return false;
517 }
518 return result.booleanValue();
519 }
520
521 /**
Saurav Dasdc7f2752018-03-18 21:28:15 -0700522 * Returns true if the link being queried is a bidirectional link that is
523 * down. A bidi-link is defined as a component unidirectional link, whose
524 * reverse link - i.e the component unidirectional link in the reverse
525 * direction - has been seen before and is down. It is necessary for the
526 * reverse-link to have been previously seen.
527 *
528 * @param link the infrastructure (unidirectional) link being queried
529 * @return true if another unidirectional link exists in the reverse
530 * direction, has been seen-before and is down
531 */
532 boolean isBidirectionalLinkDown(Link link) {
533 // cannot call linkService as link may be gone
534 Link reverseLink = getReverseLink(link);
535 if (reverseLink == null) {
536 log.warn("Query for bidi-link down but reverse-link not found "
537 + "for link {}", link);
538 return false;
539 }
540 Boolean result = seenLinks.get(reverseLink);
541 if (result == null) {
542 return false;
543 }
544 // if reverse link is seen UP (true), then its not bidi yet
545 return !result.booleanValue();
546 }
547
548 /**
549 * Returns the link in the reverse direction from the given link, by
550 * consulting the seen-links store.
551 *
552 * @param link the given link
553 * @return the reverse link or null
554 */
555 Link getReverseLink(Link link) {
556 return seenLinks.keySet().stream()
557 .filter(l -> l.src().equals(link.dst()) && l.dst().equals(link.src()))
558 .findAny()
559 .orElse(null);
560 }
561
562 /**
563 * Returns the component unidirectional links of a declared bidirectional
564 * link, by consulting the seen-links store. Caller is responsible for
565 * previously verifying bidirectionality. Returned list may be empty if
566 * errors are encountered.
567 *
568 * @param link the declared bidirectional link
569 * @return list of component unidirectional links
570 */
571 List<Link> getBidiComponentLinks(Link link) {
572 Link reverseLink = getReverseLink(link);
573 List<Link> componentLinks;
574 if (reverseLink == null) { // really should not happen if link is bidi
575 log.error("cannot find reverse link for given link: {} ... is it "
576 + "bi-directional?", link);
577 componentLinks = ImmutableList.of();
578 } else {
579 componentLinks = ImmutableList.of(reverseLink, link);
580 }
581 return componentLinks;
582 }
583
584 /**
Saurav Dase6c448a2018-01-18 12:07:33 -0800585 * Determines if the given link should be avoided in routing calculations by
586 * policy or design.
587 *
588 * @param link the infrastructure link being queried
589 * @return true if link should be avoided
590 */
591 boolean avoidLink(Link link) {
592 // XXX currently only avoids all pair-links. In the future can be
593 // extended to avoid any generic link
594 DeviceId src = link.src().deviceId();
595 PortNumber srcPort = link.src().port();
596 DeviceConfiguration devConfig = srManager.deviceConfiguration;
597 if (devConfig == null || !devConfig.isConfigured(src)) {
598 log.warn("Device {} not configured..cannot avoid link {}", src,
599 link);
600 return false;
601 }
602 DeviceId pairDev;
603 PortNumber pairLocalPort, pairRemotePort = null;
604 try {
605 pairDev = devConfig.getPairDeviceId(src);
606 pairLocalPort = devConfig.getPairLocalPort(src);
607 if (pairDev != null) {
608 pairRemotePort = devConfig
609 .getPairLocalPort(pairDev);
610 }
611 } catch (DeviceConfigNotFoundException e) {
612 log.warn("Pair dev for dev {} not configured..cannot avoid link {}",
613 src, link);
614 return false;
615 }
616
617 return srcPort.equals(pairLocalPort)
618 && link.dst().deviceId().equals(pairDev)
619 && link.dst().port().equals(pairRemotePort);
620 }
621
622 /**
623 * Cleans up internal LinkHandler stores.
624 *
625 * @param device the device that has been removed
626 */
627 void processDeviceRemoved(Device device) {
628 seenLinks.keySet()
629 .removeIf(key -> key.src().deviceId().equals(device.id())
630 || key.dst().deviceId().equals(device.id()));
631 }
632
633 /**
634 * Administratively disables the host location switchport if the edge device
635 * has no viable uplinks.
636 *
637 * @param loc one of the locations of the dual-homed host
638 */
639 void checkUplinksForDualHomedHosts(HostLocation loc) {
640 try {
641 for (Link l : srManager.linkService.getDeviceLinks(loc.deviceId())) {
642 if (srManager.deviceConfiguration.isEdgeDevice(l.dst().deviceId())
643 || l.state() == Link.State.INACTIVE) {
644 continue;
645 }
646 // found valid uplink - so, nothing to do
647 return;
648 }
649 } catch (DeviceConfigNotFoundException e) {
650 log.warn("Could not check for valid uplinks due to missing device"
651 + "config " + e.getMessage());
652 return;
653 }
654 log.warn("Dual homed host location {} has no valid uplinks; "
655 + "disabling dual homed port", loc);
656 srManager.deviceAdminService.changePortState(loc.deviceId(), loc.port(),
657 false);
658 Set<PortNumber> p = downedPortStore.get(loc.deviceId());
659 if (p == null) {
660 p = Sets.newHashSet(loc.port());
661 } else {
662 p.add(loc.port());
663 }
664 downedPortStore.put(loc.deviceId(), p);
665 }
666
Saurav Das6430f412018-01-25 09:49:01 -0800667 ImmutableMap<Link, Boolean> getSeenLinks() {
668 return ImmutableMap.copyOf(seenLinks);
669 }
670
671 ImmutableMap<DeviceId, Set<PortNumber>> getDownedPorts() {
672 return ImmutableMap.copyOf(downedPortStore.entrySet());
673 }
674
Saurav Dasdc7f2752018-03-18 21:28:15 -0700675 /**
676 * Returns all links that egress from given device that are UP in the
677 * seenLinks store. The returned links are also confirmed to be
678 * bidirectional.
679 *
680 * @param deviceId the device identifier
681 * @return set of egress links from the device
682 */
683 Set<Link> getDeviceEgressLinks(DeviceId deviceId) {
684 return seenLinks.keySet().stream()
685 .filter(link -> link.src().deviceId().equals(deviceId))
686 .filter(link -> seenLinks.get(link))
687 .filter(link -> isBidirectionalLinkUp(link))
688 .collect(Collectors.toSet());
689 }
690
Saurav Dase6c448a2018-01-18 12:07:33 -0800691}