blob: 90b0e1f81db4a28ad63be60621b975ab79aa61c4 [file] [log] [blame]
Saurav Dase9c8971e2018-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
19import java.util.Map;
20import java.util.Map.Entry;
21import java.util.Set;
22import java.util.concurrent.ConcurrentHashMap;
Saurav Das95047002018-01-25 09:49:01 -080023import java.util.stream.Collectors;
24
Saurav Dase9c8971e2018-01-18 12:07:33 -080025import org.onosproject.net.Device;
26import org.onosproject.net.DeviceId;
27import org.onosproject.net.HostLocation;
28import org.onosproject.net.Link;
29import org.onosproject.net.PortNumber;
30import org.onosproject.net.link.LinkService;
31import org.onosproject.segmentrouting.config.DeviceConfigNotFoundException;
32import org.onosproject.segmentrouting.config.DeviceConfiguration;
33import org.onosproject.segmentrouting.grouphandler.DefaultGroupHandler;
34import org.onosproject.store.service.EventuallyConsistentMap;
35import org.onosproject.store.service.EventuallyConsistentMapBuilder;
36import org.onosproject.store.service.WallClockTimestamp;
37import org.slf4j.Logger;
38import org.slf4j.LoggerFactory;
39
Saurav Das95047002018-01-25 09:49:01 -080040import com.google.common.collect.ImmutableMap;
Saurav Dase9c8971e2018-01-18 12:07:33 -080041import com.google.common.collect.Sets;
42
43public class LinkHandler {
44 private static final Logger log = LoggerFactory.getLogger(LinkHandler.class);
45 protected final SegmentRoutingManager srManager;
46 protected LinkService linkService;
47
48 // Local store for all links seen and their present status, used for
Saurav Das95047002018-01-25 09:49:01 -080049 // optimized routing. The existence of the link in the keys is enough to know
Saurav Dase9c8971e2018-01-18 12:07:33 -080050 // if the link has been "seen-before" by this instance of the controller.
51 // The boolean value indicates if the link is currently up or not.
Saurav Das95047002018-01-25 09:49:01 -080052 // Currently the optimized routing logic depends on "forgetting" a link
53 // when a switch goes down, but "remembering" it when only the link goes down.
Saurav Dase9c8971e2018-01-18 12:07:33 -080054 private Map<Link, Boolean> seenLinks = new ConcurrentHashMap<>();
55
56 private EventuallyConsistentMap<DeviceId, Set<PortNumber>> downedPortStore = null;
57
58 /**
59 * Constructs the LinkHandler.
60 *
61 * @param srManager Segment Routing manager
62 */
63 LinkHandler(SegmentRoutingManager srManager) {
64 this.srManager = srManager;
65 linkService = srManager.linkService;
66 log.debug("Creating EC map downedportstore");
67 EventuallyConsistentMapBuilder<DeviceId, Set<PortNumber>> downedPortsMapBuilder
68 = srManager.storageService.eventuallyConsistentMapBuilder();
69 downedPortStore = downedPortsMapBuilder.withName("downedportstore")
70 .withSerializer(srManager.createSerializer())
71 .withTimestampProvider((k, v) -> new WallClockTimestamp())
72 .build();
73 log.trace("Current size {}", downedPortStore.size());
74 }
75
76 /**
77 * Constructs the LinkHandler for unit-testing.
78 *
79 * @param srManager SegmentRoutingManager
80 * @param linkService LinkService
81 */
82 LinkHandler(SegmentRoutingManager srManager, LinkService linkService) {
83 this.srManager = srManager;
84 this.linkService = linkService;
85 }
86
87 /**
Saurav Das07a34aa2018-02-09 17:26:45 -080088 * Initialize LinkHandler.
89 */
Charles Chan09c66992018-03-09 15:53:44 -080090 void init() {
Saurav Das07a34aa2018-02-09 17:26:45 -080091 log.info("Loading stored links");
Charles Chan09c66992018-03-09 15:53:44 -080092 srManager.linkService.getActiveLinks().forEach(this::processLinkAdded);
Saurav Das07a34aa2018-02-09 17:26:45 -080093 }
94
95 /**
Saurav Dase9c8971e2018-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 Das07a34aa2018-02-09 17:26:45 -0800106 if (srManager.deviceConfiguration == null ||
107 !srManager.deviceConfiguration.isConfigured(link.src().deviceId())) {
Saurav Dase9c8971e2018-01-18 12:07:33 -0800108 updateSeenLink(link, true);
109 // XXX revisit - what about devicePortMap
110 log.warn("Source device of this link is not configured.. "
111 + "not processing further");
112 return;
113 }
114
115 // Irrespective of whether the local is a MASTER or not for this device,
Saurav Das95047002018-01-25 09:49:01 -0800116 // create group handler instance and push default TTP flow rules if needed,
Saurav Dase9c8971e2018-01-18 12:07:33 -0800117 // as in a multi-instance setup, instances can initiate groups for any
118 // device.
119 DefaultGroupHandler groupHandler = srManager.groupHandlerMap
120 .get(link.src().deviceId());
121 if (groupHandler != null) {
122 groupHandler.portUpForLink(link);
123 } else {
124 // XXX revisit/cleanup
125 Device device = srManager.deviceService.getDevice(link.src().deviceId());
126 if (device != null) {
127 log.warn("processLinkAdded: Link Added "
128 + "Notification without Device Added "
129 + "event, still handling it");
130 srManager.processDeviceAdded(device);
131 groupHandler = srManager.groupHandlerMap.get(link.src().deviceId());
132 groupHandler.portUpForLink(link);
133 }
134 }
135
136 /*
137 // process link only if it is bidirectional
138 if (!isBidirectional(link)) {
139 log.debug("Link not bidirectional.. waiting for other direction " +
140 "src {} --> dst {} ", link.dst(), link.src());
141 // note that if we are not processing for routing, it should at least
142 // be considered a seen-link
143 updateSeenLink(link, true); return;
144 }
145 //TODO ensure that rehash is still done correctly even if link is not processed for
146 //rerouting - perhaps rehash in both directions when it ultimately becomes bidi?
147 */
148
149 log.debug("Starting optimized route-path processing for added link "
150 + "{} --> {}", link.src(), link.dst());
151 boolean seenBefore = isSeenLink(link);
152 // seenLink updates will be done after route-path changes
153 srManager.defaultRoutingHandler
154 .populateRoutingRulesForLinkStatusChange(null, link, null);
155
156 if (srManager.mastershipService.isLocalMaster(link.src().deviceId())) {
157 // handle edge-ports for dual-homed hosts
158 updateDualHomedHostPorts(link, true);
159
Saurav Das95047002018-01-25 09:49:01 -0800160 // It's possible that linkUp causes no route-path change as ECMP graph does
Saurav Dase9c8971e2018-01-18 12:07:33 -0800161 // not change if the link is a parallel link (same src-dst as
Saurav Das95047002018-01-25 09:49:01 -0800162 // another link). However we still need to update ECMP hash groups to include new buckets
Saurav Dase9c8971e2018-01-18 12:07:33 -0800163 // for the link that has come up.
Ray Milkeyd8615942018-01-24 10:41:14 -0800164 if (groupHandler != null) {
165 if (!seenBefore && isParallelLink(link)) {
166 // if link seen first time, we need to ensure hash-groups have
167 // all ports
168 log.debug("Attempting retryHash for paralled first-time link {}",
169 link);
170 groupHandler.retryHash(link, false, true);
171 } else {
172 // seen before-link
173 if (isParallelLink(link)) {
174 log.debug("Attempting retryHash for paralled seen-before "
175 + "link {}", link);
176 groupHandler.retryHash(link, false, false);
177 }
Saurav Dase9c8971e2018-01-18 12:07:33 -0800178 }
179 }
180 }
181
182 srManager.mcastHandler.init();
183 }
184
185 /**
186 * Preprocessing of removed link before being sent for route-path handling.
187 * Also performs post processing of link.
188 *
189 * @param link the link to be processed
190 */
191 void processLinkRemoved(Link link) {
192 log.info("** LINK REMOVED {}", link.toString());
193 if (!isLinkValid(link)) {
194 return;
195 }
196 // when removing links, update seen links first, before doing route-path
197 // changes
198 updateSeenLink(link, false);
Saurav Das95047002018-01-25 09:49:01 -0800199 // handle edge-ports for dual-homed hosts
200 if (srManager.mastershipService.isLocalMaster(link.src().deviceId())) {
201 updateDualHomedHostPorts(link, false);
202 }
Saurav Dase9c8971e2018-01-18 12:07:33 -0800203
204 // device availability check helps to ensure that multiple link-removed
205 // events are actually treated as a single switch removed event.
206 // purgeSeenLink is necessary so we do rerouting (instead of rehashing)
207 // when switch comes back.
208 if (link.src().elementId() instanceof DeviceId
209 && !srManager.deviceService.isAvailable(link.src().deviceId())) {
210 purgeSeenLink(link);
211 return;
212 }
213 if (link.dst().elementId() instanceof DeviceId
214 && !srManager.deviceService.isAvailable(link.dst().deviceId())) {
215 purgeSeenLink(link);
216 return;
217 }
218
Saurav Dase9c8971e2018-01-18 12:07:33 -0800219 log.debug("Starting optimized route-path processing for removed link "
220 + "{} --> {}", link.src(), link.dst());
221 srManager.defaultRoutingHandler
222 .populateRoutingRulesForLinkStatusChange(link, null, null);
223
224 // update local groupHandler stores
225 DefaultGroupHandler groupHandler = srManager.groupHandlerMap
226 .get(link.src().deviceId());
227 if (groupHandler != null) {
228 if (srManager.mastershipService.isLocalMaster(link.src().deviceId())
229 && isParallelLink(link)) {
230 log.debug("* retrying hash for parallel link removed:{}", link);
231 groupHandler.retryHash(link, true, false);
232 } else {
233 log.debug("Not attempting retry-hash for link removed: {} .. {}",
234 link,
235 (srManager.mastershipService.isLocalMaster(link.src()
236 .deviceId())) ? "not parallel"
237 : "not master");
238 }
239 // ensure local stores are updated
240 groupHandler.portDown(link.src().port());
241 } else {
242 log.warn("group handler not found for dev:{} when removing link: {}",
243 link.src().deviceId(), link);
244 }
245
246 srManager.mcastHandler.processLinkDown(link);
247 }
248
249 /**
250 * Checks validity of link. Examples of invalid links include
251 * indirect-links, links between ports on the same switch, and more.
252 *
253 * @param link the link to be processed
254 * @return true if valid link
255 */
256 private boolean isLinkValid(Link link) {
257 if (link.type() != Link.Type.DIRECT) {
258 // NOTE: A DIRECT link might be transiently marked as INDIRECT
259 // if BDDP is received before LLDP. We can safely ignore that
260 // until the LLDP is received and the link is marked as DIRECT.
261 log.info("Ignore link {}->{}. Link type is {} instead of DIRECT.",
262 link.src(), link.dst(), link.type());
263 return false;
264 }
265 DeviceId srcId = link.src().deviceId();
266 DeviceId dstId = link.dst().deviceId();
267 if (srcId.equals(dstId)) {
268 log.warn("Links between ports on the same switch are not "
269 + "allowed .. ignoring link {}", link);
270 return false;
271 }
272 DeviceConfiguration devConfig = srManager.deviceConfiguration;
Saurav Das07a34aa2018-02-09 17:26:45 -0800273 if (devConfig == null) {
274 log.warn("Cannot check validity of link without device config");
275 return true;
276 }
Saurav Dase9c8971e2018-01-18 12:07:33 -0800277 try {
278 if (!devConfig.isEdgeDevice(srcId)
279 && !devConfig.isEdgeDevice(dstId)) {
280 // ignore links between spines
281 // XXX revisit when handling multi-stage fabrics
282 log.warn("Links between spines not allowed...ignoring "
283 + "link {}", link);
284 return false;
285 }
286 if (devConfig.isEdgeDevice(srcId)
287 && devConfig.isEdgeDevice(dstId)) {
288 // ignore links between leaves if they are not pair-links
289 // XXX revisit if removing pair-link config or allowing more than
290 // one pair-link
291 if (devConfig.getPairDeviceId(srcId).equals(dstId)
292 && devConfig.getPairLocalPort(srcId)
293 .equals(link.src().port())
294 && devConfig.getPairLocalPort(dstId)
295 .equals(link.dst().port())) {
296 // found pair link - allow it
297 return true;
298 } else {
299 log.warn("Links between leaves other than pair-links are "
300 + "not allowed...ignoring link {}", link);
301 return false;
302 }
303 }
304 } catch (DeviceConfigNotFoundException e) {
305 // We still want to count the links in seenLinks even though there
306 // is no config. So we let it return true
307 log.warn("Could not check validity of link {} as subtending devices "
308 + "are not yet configured", link);
309 }
310 return true;
311 }
312
313 /**
314 * Administratively enables or disables edge ports if the link that was
315 * added or removed was the only uplink port from an edge device. Only edge
316 * ports that belong to dual-homed hosts are considered.
317 *
318 * @param link the link to be processed
319 * @param added true if link was added, false if link was removed
320 */
321 private void updateDualHomedHostPorts(Link link, boolean added) {
Saurav Das95047002018-01-25 09:49:01 -0800322 if (!onlyUplink(link)) {
Saurav Dase9c8971e2018-01-18 12:07:33 -0800323 return;
324 }
325 if (added) {
326 // re-enable previously disabled ports on this dev
327 Set<PortNumber> p = downedPortStore.remove(link.src().deviceId());
328 if (p != null) {
329 log.warn("Link src {} -->dst {} added is the first uplink, "
330 + "enabling dual homed ports: {}", link.src().deviceId(),
331 link.dst().deviceId(), (p.isEmpty()) ? "no ports" : p);
332 p.forEach(pnum -> srManager.deviceAdminService
333 .changePortState(link.src().deviceId(), pnum, true));
334 }
335 } else {
336 // find dual homed hosts on this dev to disable
337 Set<PortNumber> dhp = srManager.hostHandler
338 .getDualHomedHostPorts(link.src().deviceId());
339 log.warn("Link src {} -->dst {} removed was the last uplink, "
340 + "disabling dual homed ports: {}", link.src().deviceId(),
341 link.dst().deviceId(), (dhp.isEmpty()) ? "no ports" : dhp);
342 dhp.forEach(pnum -> srManager.deviceAdminService
343 .changePortState(link.src().deviceId(), pnum, false));
344 if (!dhp.isEmpty()) {
345 // update global store
346 Set<PortNumber> p = downedPortStore.get(link.src().deviceId());
347 if (p == null) {
348 p = dhp;
349 } else {
350 p.addAll(dhp);
351 }
352 downedPortStore.put(link.src().deviceId(), p);
353 }
354 }
355 }
356
357 /**
Saurav Das95047002018-01-25 09:49:01 -0800358 * Returns true if given link is the only active uplink from src-device of
Saurav Dase9c8971e2018-01-18 12:07:33 -0800359 * link. An uplink is defined as a unidirectional link with src as
360 * edgeRouter and dst as non-edgeRouter.
361 *
362 * @param link
363 * @return true if given link is-the-first/was-the-last uplink from the src
364 * device
365 */
Saurav Das95047002018-01-25 09:49:01 -0800366 private boolean onlyUplink(Link link) {
Saurav Dase9c8971e2018-01-18 12:07:33 -0800367 DeviceConfiguration devConfig = srManager.deviceConfiguration;
368 try {
Saurav Das95047002018-01-25 09:49:01 -0800369 if (!devConfig.isEdgeDevice(link.src().deviceId())
370 || devConfig.isEdgeDevice(link.dst().deviceId())) {
Saurav Dase9c8971e2018-01-18 12:07:33 -0800371 return false;
372 }
Saurav Das95047002018-01-25 09:49:01 -0800373 // note that using linkservice here would cause race conditions as
374 // more links can show up while the app is still processing the first one
375 Set<Link> devLinks = seenLinks.entrySet().stream()
376 .filter(entry -> entry.getKey().src().deviceId()
377 .equals(link.src().deviceId()))
378 .filter(entry -> entry.getValue())
379 .filter(entry -> !entry.getKey().equals(link))
380 .map(entry -> entry.getKey())
381 .collect(Collectors.toSet());
382
Saurav Dase9c8971e2018-01-18 12:07:33 -0800383 for (Link l : devLinks) {
Saurav Das95047002018-01-25 09:49:01 -0800384 if (devConfig.isEdgeDevice(l.dst().deviceId())) {
Saurav Dase9c8971e2018-01-18 12:07:33 -0800385 continue;
386 }
Saurav Das95047002018-01-25 09:49:01 -0800387 log.debug("Link {} is not the only active uplink. Found another"
388 + "link {}", link, l);
389 return false;
Saurav Dase9c8971e2018-01-18 12:07:33 -0800390 }
Saurav Das95047002018-01-25 09:49:01 -0800391 log.debug("Link {} is the only uplink", link);
392 return true;
Saurav Dase9c8971e2018-01-18 12:07:33 -0800393 } catch (DeviceConfigNotFoundException e) {
Saurav Das95047002018-01-25 09:49:01 -0800394 log.warn("Unable to determine if link is only uplink"
Saurav Dase9c8971e2018-01-18 12:07:33 -0800395 + e.getMessage());
396 }
397 return false;
398 }
399
400 /**
401 * Returns true if this controller instance has seen this link before. The
402 * link may not be currently up, but as long as the link had been seen
403 * before this method will return true. The one exception is when the link
404 * was indeed seen before, but this controller instance was forced to forget
405 * it by a call to purgeSeenLink method.
406 *
407 * @param link the infrastructure link being queried
408 * @return true if this controller instance has seen this link before
409 */
410 boolean isSeenLink(Link link) {
411 return seenLinks.containsKey(link);
412 }
413
414 /**
415 * Updates the seen link store. Updates can be for links that are currently
416 * available or not.
417 *
418 * @param link the link to update in the seen-link local store
419 * @param up the status of the link, true if up, false if down
420 */
421 void updateSeenLink(Link link, boolean up) {
422 seenLinks.put(link, up);
423 }
424
425 /**
426 * Returns the status of a seen-link (up or down). If the link has not been
427 * seen-before, a null object is returned.
428 *
429 * @param link the infrastructure link being queried
430 * @return null if the link was not seen-before; true if the seen-link is
431 * up; false if the seen-link is down
432 */
433 private Boolean isSeenLinkUp(Link link) {
434 return seenLinks.get(link);
435 }
436
437 /**
438 * Makes this controller instance forget a previously seen before link.
439 *
440 * @param link the infrastructure link to purge
441 */
442 private void purgeSeenLink(Link link) {
443 seenLinks.remove(link);
444 }
445
446 /**
447 * Returns the status of a link as parallel link. A parallel link is defined
448 * as a link which has common src and dst switches as another seen-link that
449 * is currently enabled. It is not necessary for the link being queried to
450 * be a seen-link.
451 *
452 * @param link the infrastructure link being queried
453 * @return true if a seen-link exists that is up, and shares the same src
454 * and dst switches as the link being queried
455 */
456 private boolean isParallelLink(Link link) {
457 for (Entry<Link, Boolean> seen : seenLinks.entrySet()) {
458 Link seenLink = seen.getKey();
459 if (seenLink.equals(link)) {
460 continue;
461 }
462 if (seenLink.src().deviceId().equals(link.src().deviceId())
463 && seenLink.dst().deviceId().equals(link.dst().deviceId())
464 && seen.getValue()) {
465 return true;
466 }
467 }
468 return false;
469 }
470
471 /**
472 * Returns true if the link being queried is a bidirectional link. A bidi
473 * link is defined as a link, whose reverse link - ie. the link in the
474 * reverse direction - has been seen-before and is up. It is not necessary
475 * for the link being queried to be a seen-link.
476 *
477 * @param link the infrastructure link being queried
478 * @return true if another unidirectional link exists in the reverse
479 * direction, has been seen-before and is up
480 */
481 boolean isBidirectional(Link link) {
482 Link reverseLink = linkService.getLink(link.dst(), link.src());
483 if (reverseLink == null) {
484 return false;
485 }
486 Boolean result = isSeenLinkUp(reverseLink);
487 if (result == null) {
488 return false;
489 }
490 return result.booleanValue();
491 }
492
493 /**
494 * Determines if the given link should be avoided in routing calculations by
495 * policy or design.
496 *
497 * @param link the infrastructure link being queried
498 * @return true if link should be avoided
499 */
500 boolean avoidLink(Link link) {
501 // XXX currently only avoids all pair-links. In the future can be
502 // extended to avoid any generic link
503 DeviceId src = link.src().deviceId();
504 PortNumber srcPort = link.src().port();
505 DeviceConfiguration devConfig = srManager.deviceConfiguration;
506 if (devConfig == null || !devConfig.isConfigured(src)) {
507 log.warn("Device {} not configured..cannot avoid link {}", src,
508 link);
509 return false;
510 }
511 DeviceId pairDev;
512 PortNumber pairLocalPort, pairRemotePort = null;
513 try {
514 pairDev = devConfig.getPairDeviceId(src);
515 pairLocalPort = devConfig.getPairLocalPort(src);
516 if (pairDev != null) {
517 pairRemotePort = devConfig
518 .getPairLocalPort(pairDev);
519 }
520 } catch (DeviceConfigNotFoundException e) {
521 log.warn("Pair dev for dev {} not configured..cannot avoid link {}",
522 src, link);
523 return false;
524 }
525
526 return srcPort.equals(pairLocalPort)
527 && link.dst().deviceId().equals(pairDev)
528 && link.dst().port().equals(pairRemotePort);
529 }
530
531 /**
532 * Cleans up internal LinkHandler stores.
533 *
534 * @param device the device that has been removed
535 */
536 void processDeviceRemoved(Device device) {
537 seenLinks.keySet()
538 .removeIf(key -> key.src().deviceId().equals(device.id())
539 || key.dst().deviceId().equals(device.id()));
540 }
541
542 /**
543 * Administratively disables the host location switchport if the edge device
544 * has no viable uplinks.
545 *
546 * @param loc one of the locations of the dual-homed host
547 */
548 void checkUplinksForDualHomedHosts(HostLocation loc) {
549 try {
550 for (Link l : srManager.linkService.getDeviceLinks(loc.deviceId())) {
551 if (srManager.deviceConfiguration.isEdgeDevice(l.dst().deviceId())
552 || l.state() == Link.State.INACTIVE) {
553 continue;
554 }
555 // found valid uplink - so, nothing to do
556 return;
557 }
558 } catch (DeviceConfigNotFoundException e) {
559 log.warn("Could not check for valid uplinks due to missing device"
560 + "config " + e.getMessage());
561 return;
562 }
563 log.warn("Dual homed host location {} has no valid uplinks; "
564 + "disabling dual homed port", loc);
565 srManager.deviceAdminService.changePortState(loc.deviceId(), loc.port(),
566 false);
567 Set<PortNumber> p = downedPortStore.get(loc.deviceId());
568 if (p == null) {
569 p = Sets.newHashSet(loc.port());
570 } else {
571 p.add(loc.port());
572 }
573 downedPortStore.put(loc.deviceId(), p);
574 }
575
Saurav Das95047002018-01-25 09:49:01 -0800576 ImmutableMap<Link, Boolean> getSeenLinks() {
577 return ImmutableMap.copyOf(seenLinks);
578 }
579
580 ImmutableMap<DeviceId, Set<PortNumber>> getDownedPorts() {
581 return ImmutableMap.copyOf(downedPortStore.entrySet());
582 }
583
Saurav Dase9c8971e2018-01-18 12:07:33 -0800584}