blob: f67bfea6c3830d655414227954ab2cafb830ddf1 [file] [log] [blame]
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001/**
2 * Copyright 2011, Big Switch Networks, Inc.
3 * Originally created by David Erickson, Stanford University
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License"); you may
6 * not use this file except in compliance with the License. You may obtain
7 * a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 * License for the specific language governing permissions and limitations
15 * under the License.
16 **/
17
18package net.floodlightcontroller.linkdiscovery.internal;
19
20import java.io.IOException;
21import java.net.InetAddress;
22import java.net.InetSocketAddress;
23import java.net.NetworkInterface;
24import java.net.SocketAddress;
25import java.nio.ByteBuffer;
26import java.util.ArrayList;
27import java.util.Collection;
28import java.util.Collections;
29import java.util.HashMap;
30import java.util.HashSet;
31import java.util.Iterator;
32import java.util.List;
33import java.util.Map;
34import java.util.Map.Entry;
35import java.util.Set;
36import java.util.concurrent.BlockingQueue;
37import java.util.concurrent.LinkedBlockingQueue;
38import java.util.concurrent.ScheduledExecutorService;
39import java.util.concurrent.TimeUnit;
40import java.util.concurrent.locks.ReentrantReadWriteLock;
41
42import net.floodlightcontroller.core.FloodlightContext;
43import net.floodlightcontroller.core.IFloodlightProviderService;
44import net.floodlightcontroller.core.IFloodlightProviderService.Role;
Umesh Krishnaswamy2b9d5642013-01-04 11:00:27 -080045import net.floodlightcontroller.core.INetMapStorage.DM_OPERATION;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080046import net.floodlightcontroller.core.IHAListener;
47import net.floodlightcontroller.core.IInfoProvider;
48import net.floodlightcontroller.core.IOFMessageListener;
49import net.floodlightcontroller.core.IOFSwitch;
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -080050import net.floodlightcontroller.core.internal.OFSwitchImpl;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080051import net.floodlightcontroller.core.IOFSwitchListener;
52import net.floodlightcontroller.core.annotations.LogMessageCategory;
53import net.floodlightcontroller.core.annotations.LogMessageDoc;
54import net.floodlightcontroller.core.annotations.LogMessageDocs;
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -080055//import net.floodlightcontroller.core.internal.SwitchStorageImpl;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080056import net.floodlightcontroller.core.module.FloodlightModuleContext;
57import net.floodlightcontroller.core.module.FloodlightModuleException;
58import net.floodlightcontroller.core.module.IFloodlightModule;
59import net.floodlightcontroller.core.module.IFloodlightService;
60import net.floodlightcontroller.core.util.SingletonTask;
61import net.floodlightcontroller.linkdiscovery.ILinkDiscovery;
62import net.floodlightcontroller.linkdiscovery.ILinkDiscovery.LinkType;
63import net.floodlightcontroller.linkdiscovery.ILinkDiscovery.SwitchType;
64import net.floodlightcontroller.linkdiscovery.ILinkDiscovery.LDUpdate;
65import net.floodlightcontroller.linkdiscovery.ILinkDiscovery.UpdateOperation;
66import net.floodlightcontroller.linkdiscovery.web.LinkDiscoveryWebRoutable;
67import net.floodlightcontroller.linkdiscovery.ILinkDiscoveryListener;
68import net.floodlightcontroller.linkdiscovery.ILinkDiscoveryService;
69import net.floodlightcontroller.linkdiscovery.LinkInfo;
70import net.floodlightcontroller.packet.BSN;
71import net.floodlightcontroller.packet.Ethernet;
72import net.floodlightcontroller.packet.IPv4;
73import net.floodlightcontroller.packet.LLDP;
74import net.floodlightcontroller.packet.LLDPTLV;
75import net.floodlightcontroller.restserver.IRestApiService;
76import net.floodlightcontroller.routing.Link;
77import net.floodlightcontroller.storage.IResultSet;
78import net.floodlightcontroller.storage.IStorageSourceService;
79import net.floodlightcontroller.storage.IStorageSourceListener;
80import net.floodlightcontroller.storage.OperatorPredicate;
81import net.floodlightcontroller.storage.StorageException;
82import net.floodlightcontroller.threadpool.IThreadPoolService;
83import net.floodlightcontroller.topology.NodePortTuple;
84import net.floodlightcontroller.util.EventHistory;
85import net.floodlightcontroller.util.EventHistory.EvAction;
86
87import org.openflow.protocol.OFMessage;
88import org.openflow.protocol.OFPacketIn;
89import org.openflow.protocol.OFPacketOut;
90import org.openflow.protocol.OFPhysicalPort;
91import org.openflow.protocol.OFPhysicalPort.OFPortConfig;
92import org.openflow.protocol.OFPhysicalPort.OFPortState;
93import org.openflow.protocol.OFPort;
94import org.openflow.protocol.OFPortStatus;
95import org.openflow.protocol.OFPortStatus.OFPortReason;
96import org.openflow.protocol.OFType;
97import org.openflow.protocol.action.OFAction;
98import org.openflow.protocol.action.OFActionOutput;
99import org.openflow.util.HexString;
100import org.slf4j.Logger;
101import org.slf4j.LoggerFactory;
102
103/**
104 * This class sends out LLDP messages containing the sending switch's datapath
105 * id as well as the outgoing port number. Received LLrescDP messages that
106 * match a known switch cause a new LinkTuple to be created according to the
107 * invariant rules listed below. This new LinkTuple is also passed to routing
108 * if it exists to trigger updates.
109 *
110 * This class also handles removing links that are associated to switch ports
111 * that go down, and switches that are disconnected.
112 *
113 * Invariants:
114 * -portLinks and switchLinks will not contain empty Sets outside of
115 * critical sections
116 * -portLinks contains LinkTuples where one of the src or dst
117 * SwitchPortTuple matches the map key
118 * -switchLinks contains LinkTuples where one of the src or dst
119 * SwitchPortTuple's id matches the switch id
120 * -Each LinkTuple will be indexed into switchLinks for both
121 * src.id and dst.id, and portLinks for each src and dst
122 * -The updates queue is only added to from within a held write lock
123 */
124@LogMessageCategory("Network Topology")
125public class LinkDiscoveryManager
126implements IOFMessageListener, IOFSwitchListener,
127IStorageSourceListener, ILinkDiscoveryService,
128IFloodlightModule, IInfoProvider, IHAListener {
129 protected static Logger log = LoggerFactory.getLogger(LinkDiscoveryManager.class);
130
131 // Names of table/fields for links in the storage API
132 private static final String LINK_TABLE_NAME = "controller_link";
133 private static final String LINK_ID = "id";
134 private static final String LINK_SRC_SWITCH = "src_switch_id";
135 private static final String LINK_SRC_PORT = "src_port";
136 private static final String LINK_SRC_PORT_STATE = "src_port_state";
137 private static final String LINK_DST_SWITCH = "dst_switch_id";
138 private static final String LINK_DST_PORT = "dst_port";
139 private static final String LINK_DST_PORT_STATE = "dst_port_state";
140 private static final String LINK_VALID_TIME = "valid_time";
141 private static final String LINK_TYPE = "link_type";
142 private static final String SWITCH_CONFIG_TABLE_NAME = "controller_switchconfig";
143 private static final String SWITCH_CONFIG_CORE_SWITCH = "core_switch";
144
145 protected IFloodlightProviderService floodlightProvider;
146 protected IStorageSourceService storageSource;
147 protected IThreadPoolService threadPool;
148 protected IRestApiService restApi;
149
150
151 // LLDP and BDDP fields
152 private static final byte[] LLDP_STANDARD_DST_MAC_STRING =
153 HexString.fromHexString("01:80:c2:00:00:0e");
154 private static final long LINK_LOCAL_MASK = 0xfffffffffff0L;
155 private static final long LINK_LOCAL_VALUE = 0x0180c2000000L;
156
157 // BigSwitch OUI is 5C:16:C7, so 5D:16:C7 is the multicast version
158 // private static final String LLDP_BSN_DST_MAC_STRING = "5d:16:c7:00:00:01";
159 private static final String LLDP_BSN_DST_MAC_STRING = "ff:ff:ff:ff:ff:ff";
160
161
162 // Direction TLVs are used to indicate if the LLDPs were sent
163 // periodically or in response to a recieved LLDP
164 private static final byte TLV_DIRECTION_TYPE = 0x73;
165 private static final short TLV_DIRECTION_LENGTH = 1; // 1 byte
166 private static final byte TLV_DIRECTION_VALUE_FORWARD[] = {0x01};
167 private static final byte TLV_DIRECTION_VALUE_REVERSE[] = {0x02};
168 private static final LLDPTLV forwardTLV
169 = new LLDPTLV().
170 setType((byte)TLV_DIRECTION_TYPE).
171 setLength((short)TLV_DIRECTION_LENGTH).
172 setValue(TLV_DIRECTION_VALUE_FORWARD);
173
174 private static final LLDPTLV reverseTLV
175 = new LLDPTLV().
176 setType((byte)TLV_DIRECTION_TYPE).
177 setLength((short)TLV_DIRECTION_LENGTH).
178 setValue(TLV_DIRECTION_VALUE_REVERSE);
179
180 // Link discovery task details.
181 protected SingletonTask discoveryTask;
182 protected final int DISCOVERY_TASK_INTERVAL = 1;
183 protected final int LINK_TIMEOUT = 35; // timeout as part of LLDP process.
184 protected final int LLDP_TO_ALL_INTERVAL = 15 ; //15 seconds.
185 protected long lldpClock = 0;
186 // This value is intentionally kept higher than LLDP_TO_ALL_INTERVAL.
187 // If we want to identify link failures faster, we could decrease this
188 // value to a small number, say 1 or 2 sec.
189 protected final int LLDP_TO_KNOWN_INTERVAL= 20; // LLDP frequency for known links
190
191 protected LLDPTLV controllerTLV;
192 protected ReentrantReadWriteLock lock;
193 int lldpTimeCount = 0;
194
Umesh Krishnaswamy2b9d5642013-01-04 11:00:27 -0800195 // Storage
Pankaj Berdec125e622013-01-25 06:39:39 -0800196
197 ThreadLocal<LinkStorageImpl> store = new ThreadLocal<LinkStorageImpl>() {
198 @Override
199 protected LinkStorageImpl initialValue() {
200 LinkStorageImpl swStore = new LinkStorageImpl();
201 //TODO: Get the file path from global properties
202 swStore.init("/tmp/cassandra.titan");
203 return swStore;
204 }
205 };
206 protected LinkStorageImpl linkStore = store.get();
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800207 // protected SwitchStorageImpl swStore;
Umesh Krishnaswamy2b9d5642013-01-04 11:00:27 -0800208
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800209 /**
210 * Flag to indicate if automatic port fast is enabled or not.
211 * Default is set to false -- Initialized in the init method as well.
212 */
213 boolean autoPortFastFeature = false;
214
215 /**
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800216 * Map of remote switches that are not connected to this controller. This
217 * is used to learn remote switches in a distributed controller.
218 */
219 protected Map<Long, IOFSwitch> remoteSwitches;
220
221 /**
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800222 * Map from link to the most recent time it was verified functioning
223 */
224 protected Map<Link, LinkInfo> links;
225
226 /**
227 * Map from switch id to a set of all links with it as an endpoint
228 */
229 protected Map<Long, Set<Link>> switchLinks;
230
231 /**
232 * Map from a id:port to the set of links containing it as an endpoint
233 */
234 protected Map<NodePortTuple, Set<Link>> portLinks;
235
236 /**
237 * Set of link tuples over which multicast LLDPs are received
238 * and unicast LLDPs are not received.
239 */
240 protected Map<NodePortTuple, Set<Link>> portBroadcastDomainLinks;
241
242 protected volatile boolean shuttingDown = false;
243
244 /* topology aware components are called in the order they were added to the
245 * the array */
246 protected ArrayList<ILinkDiscoveryListener> linkDiscoveryAware;
247 protected BlockingQueue<LDUpdate> updates;
248 protected Thread updatesThread;
249
250 /**
251 * List of ports through which LLDP/BDDPs are not sent.
252 */
253 protected Set<NodePortTuple> suppressLinkDiscovery;
254
255 /** A list of ports that are quarantined for discovering links through
256 * them. Data traffic from these ports are not allowed until the ports
257 * are released from quarantine.
258 */
259 protected LinkedBlockingQueue<NodePortTuple> quarantineQueue;
260 protected LinkedBlockingQueue<NodePortTuple> maintenanceQueue;
261 /**
262 * Quarantine task
263 */
264 protected SingletonTask bddpTask;
265 protected final int BDDP_TASK_INTERVAL = 100; // 100 ms.
266 protected final int BDDP_TASK_SIZE = 5; // # of ports per iteration
267
268 /**
269 * Map of broadcast domain ports and the last time a BDDP was either
270 * sent or received on that port.
271 */
272 protected Map<NodePortTuple, Long> broadcastDomainPortTimeMap;
273
274 /**
275 * Get the LLDP sending period in seconds.
276 * @return LLDP sending period in seconds.
277 */
278 public int getLldpFrequency() {
279 return LLDP_TO_KNOWN_INTERVAL;
280 }
281
282 /**
283 * Get the LLDP timeout value in seconds
284 * @return LLDP timeout value in seconds
285 */
286 public int getLldpTimeout() {
287 return LINK_TIMEOUT;
288 }
289
290 public Map<NodePortTuple, Set<Link>> getPortLinks() {
291 return portLinks;
292 }
293
294 public Set<NodePortTuple> getSuppressLLDPsInfo() {
295 return suppressLinkDiscovery;
296 }
297
298 /**
299 * Add a switch port to the suppressed LLDP list.
300 * Remove any known links on the switch port.
301 */
302 public void AddToSuppressLLDPs(long sw, short port)
303 {
304 NodePortTuple npt = new NodePortTuple(sw, port);
305 this.suppressLinkDiscovery.add(npt);
306 deleteLinksOnPort(npt, "LLDP suppressed.");
307 }
308
309 /**
310 * Remove a switch port from the suppressed LLDP list.
311 * Discover links on that switchport.
312 */
313 public void RemoveFromSuppressLLDPs(long sw, short port)
314 {
315 NodePortTuple npt = new NodePortTuple(sw, port);
316 this.suppressLinkDiscovery.remove(npt);
317 discover(npt);
318 }
319
320 public boolean isShuttingDown() {
321 return shuttingDown;
322 }
323
324 public boolean isFastPort(long sw, short port) {
325 return false;
326 }
327
328 public ILinkDiscovery.LinkType getLinkType(Link lt, LinkInfo info) {
329 if (info.getUnicastValidTime() != null) {
330 return ILinkDiscovery.LinkType.DIRECT_LINK;
331 } else if (info.getMulticastValidTime() != null) {
332 return ILinkDiscovery.LinkType.MULTIHOP_LINK;
333 }
334 return ILinkDiscovery.LinkType.INVALID_LINK;
335 }
336
337 @LogMessageDoc(level="ERROR",
338 message="Error in link discovery updates loop",
339 explanation="An unknown error occured while dispatching " +
340 "link update notifications",
341 recommendation=LogMessageDoc.GENERIC_ACTION)
342 private void doUpdatesThread() throws InterruptedException {
343 do {
344 LDUpdate update = updates.take();
345
346 if (linkDiscoveryAware != null) {
347 if (log.isTraceEnabled()) {
348 log.trace("Dispatching link discovery update {} {} {} {} {} for {}",
349 new Object[]{update.getOperation(),
350 HexString.toHexString(update.getSrc()), update.getSrcPort(),
351 HexString.toHexString(update.getDst()), update.getDstPort(),
352 linkDiscoveryAware});
353 }
354 try {
355 for (ILinkDiscoveryListener lda : linkDiscoveryAware) { // order maintained
356 lda.linkDiscoveryUpdate(update);
357 }
358 }
359 catch (Exception e) {
360 log.error("Error in link discovery updates loop", e);
361 }
362 }
363 } while (updates.peek() != null);
364 }
365 private boolean isLinkDiscoverySuppressed(long sw, short portNumber) {
366 return this.suppressLinkDiscovery.contains(new NodePortTuple(sw, portNumber));
367 }
368
369 protected void discoverLinks() {
370
371 // timeout known links.
372 timeoutLinks();
373
374 //increment LLDP clock
375 lldpClock = (lldpClock + 1)% LLDP_TO_ALL_INTERVAL;
376
377 if (lldpClock == 0) {
378 log.debug("Sending LLDP out on all ports.");
379 discoverOnAllPorts();
380 }
381 }
382
383
384 /**
385 * Quarantine Ports.
386 */
387 protected class QuarantineWorker implements Runnable {
388 @Override
389 public void run() {
390 try {
391 processBDDPLists();
392 }
393 catch (Exception e) {
394 log.error("Error in quarantine worker thread", e);
395 } finally {
396 bddpTask.reschedule(BDDP_TASK_INTERVAL,
397 TimeUnit.MILLISECONDS);
398 }
399 }
400 }
401
402 /**
403 * Add a switch port to the quarantine queue. Schedule the
404 * quarantine task if the quarantine queue was empty before adding
405 * this switch port.
406 * @param npt
407 */
408 protected void addToQuarantineQueue(NodePortTuple npt) {
409 if (quarantineQueue.contains(npt) == false)
410 quarantineQueue.add(npt);
411 }
412
413 /**
414 * Remove a switch port from the quarantine queue.
415 */
416 protected void removeFromQuarantineQueue(NodePortTuple npt) {
417 // Remove all occurrences of the node port tuple from the list.
418 while (quarantineQueue.remove(npt));
419 }
420
421 /**
422 * Add a switch port to maintenance queue.
423 * @param npt
424 */
425 protected void addToMaintenanceQueue(NodePortTuple npt) {
426 // TODO We are not checking if the switch port tuple is already
427 // in the maintenance list or not. This will be an issue for
428 // really large number of switch ports in the network.
429 if (maintenanceQueue.contains(npt) == false)
430 maintenanceQueue.add(npt);
431 }
432
433 /**
434 * Remove a switch port from maintenance queue.
435 * @param npt
436 */
437 protected void removeFromMaintenanceQueue(NodePortTuple npt) {
438 // Remove all occurrences of the node port tuple from the queue.
439 while (maintenanceQueue.remove(npt));
440 }
441
442 /**
443 * This method processes the quarantine list in bursts. The task is
444 * at most once per BDDP_TASK_INTERVAL.
445 * One each call, BDDP_TASK_SIZE number of switch ports are processed.
446 * Once the BDDP packets are sent out through the switch ports, the ports
447 * are removed from the quarantine list.
448 */
449
450 protected void processBDDPLists() {
451 int count = 0;
452 Set<NodePortTuple> nptList = new HashSet<NodePortTuple>();
453
454 while(count < BDDP_TASK_SIZE && quarantineQueue.peek() !=null) {
455 NodePortTuple npt;
456 npt = quarantineQueue.remove();
457 sendDiscoveryMessage(npt.getNodeId(), npt.getPortId(), false, false);
458 nptList.add(npt);
459 count++;
460 }
461
462 count = 0;
463 while (count < BDDP_TASK_SIZE && maintenanceQueue.peek() != null) {
464 NodePortTuple npt;
465 npt = maintenanceQueue.remove();
466 sendDiscoveryMessage(npt.getNodeId(), npt.getPortId(), false, false);
467 count++;
468 }
469
470 for(NodePortTuple npt:nptList) {
471 generateSwitchPortStatusUpdate(npt.getNodeId(), npt.getPortId());
472 }
473 }
474
475 public Set<Short> getQuarantinedPorts(long sw) {
476 Set<Short> qPorts = new HashSet<Short>();
477
478 Iterator<NodePortTuple> iter = quarantineQueue.iterator();
479 while (iter.hasNext()) {
480 NodePortTuple npt = iter.next();
481 if (npt.getNodeId() == sw) {
482 qPorts.add(npt.getPortId());
483 }
484 }
485 return qPorts;
486 }
487
488 private void generateSwitchPortStatusUpdate(long sw, short port) {
489 UpdateOperation operation;
490
491 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
492 if (iofSwitch == null) return;
493
494 OFPhysicalPort ofp = iofSwitch.getPort(port);
495 if (ofp == null) return;
496
497 int srcPortState = ofp.getState();
498 boolean portUp = ((srcPortState &
499 OFPortState.OFPPS_STP_MASK.getValue()) !=
500 OFPortState.OFPPS_STP_BLOCK.getValue());
501
502 if (portUp) operation = UpdateOperation.PORT_UP;
503 else operation = UpdateOperation.PORT_DOWN;
504
505 updates.add(new LDUpdate(sw, port, operation));
506 }
507
508 /**
509 * Send LLDP on known ports
510 */
511 protected void discoverOnKnownLinkPorts() {
512 // Copy the port set.
513 Set<NodePortTuple> nptSet = new HashSet<NodePortTuple>();
514 nptSet.addAll(portLinks.keySet());
515
516 // Send LLDP from each of them.
517 for(NodePortTuple npt: nptSet) {
518 discover(npt);
519 }
520 }
521
522 protected void discover(NodePortTuple npt) {
523 discover(npt.getNodeId(), npt.getPortId());
524 }
525
526 protected void discover(long sw, short port) {
527 sendDiscoveryMessage(sw, port, true, false);
528 }
529
530 /**
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800531 * Learn remote switches when running as a distributed controller
532 */
533 protected IOFSwitch addRemoteSwitch(long sw, short port) {
534 IOFSwitch remotesw = null;
535
536 // add a switch if we have not seen it before
Umesh Krishnaswamy4c8e1082013-01-24 23:15:37 -0800537 remotesw = remoteSwitches.get(sw);
Jonathan Harte7231052013-01-25 00:01:14 -0800538
Pankaj Berdec125e622013-01-25 06:39:39 -0800539 if (remotesw == null) {
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800540 remotesw = new OFSwitchImpl();
541 remotesw.setupRemoteSwitch(sw);
542 remoteSwitches.put(remotesw.getId(), remotesw);
543 log.debug("addRemoteSwitch(): added fake remote sw {}", remotesw);
544 }
545
546 // add the port if we have not seen it before
547 if (remotesw.getPort(port) != null) {
548 OFPhysicalPort remoteport = new OFPhysicalPort();
549 remoteport.setPortNumber(port);
550 remoteport.setName("fake_" + port);
551 remoteport.setConfig(0);
552 remoteport.setState(0);
553 remotesw.setPort(remoteport);
554 log.debug("addRemoteSwitch(): added fake remote port {} to sw {}", remoteport, remotesw);
555 }
556
557 return remotesw;
558 }
559
560 /**
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800561 * Send link discovery message out of a given switch port.
562 * The discovery message may be a standard LLDP or a modified
563 * LLDP, where the dst mac address is set to :ff.
564 *
565 * TODO: The modified LLDP will updated in the future and may
566 * use a different eth-type.
567 * @param sw
568 * @param port
569 * @param isStandard indicates standard or modified LLDP
570 * @param isReverse indicates whether the LLDP was sent as a response
571 */
572 @LogMessageDoc(level="ERROR",
573 message="Failure sending LLDP out port {port} on switch {switch}",
574 explanation="An I/O error occured while sending LLDP message " +
575 "to the switch.",
576 recommendation=LogMessageDoc.CHECK_SWITCH)
577 protected void sendDiscoveryMessage(long sw, short port,
578 boolean isStandard,
579 boolean isReverse) {
580
581 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
582 if (iofSwitch == null) {
583 return;
584 }
585
586 if (port == OFPort.OFPP_LOCAL.getValue())
587 return;
588
589 OFPhysicalPort ofpPort = iofSwitch.getPort(port);
590
591 if (ofpPort == null) {
592 if (log.isTraceEnabled()) {
593 log.trace("Null physical port. sw={}, port={}", sw, port);
594 }
595 return;
596 }
597
598 if (isLinkDiscoverySuppressed(sw, port)) {
599 /* Dont send LLDPs out of this port as suppressLLDPs set
600 *
601 */
602 return;
603 }
604
605 // For fast ports, do not send forward LLDPs or BDDPs.
606 if (!isReverse && autoPortFastFeature && isFastPort(sw, port))
607 return;
608
609 if (log.isTraceEnabled()) {
610 log.trace("Sending LLDP packet out of swich: {}, port: {}",
611 sw, port);
612 }
613
614 // using "nearest customer bridge" MAC address for broadest possible propagation
615 // through provider and TPMR bridges (see IEEE 802.1AB-2009 and 802.1Q-2011),
616 // in particular the Linux bridge which behaves mostly like a provider bridge
617 byte[] chassisId = new byte[] {4, 0, 0, 0, 0, 0, 0}; // filled in later
618 byte[] portId = new byte[] {2, 0, 0}; // filled in later
619 byte[] ttlValue = new byte[] {0, 0x78};
620 // OpenFlow OUI - 00-26-E1
621 byte[] dpidTLVValue = new byte[] {0x0, 0x26, (byte) 0xe1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
622 LLDPTLV dpidTLV = new LLDPTLV().setType((byte) 127).setLength((short) dpidTLVValue.length).setValue(dpidTLVValue);
623
624 byte[] dpidArray = new byte[8];
625 ByteBuffer dpidBB = ByteBuffer.wrap(dpidArray);
626 ByteBuffer portBB = ByteBuffer.wrap(portId, 1, 2);
627
628 Long dpid = sw;
629 dpidBB.putLong(dpid);
630 // set the ethernet source mac to last 6 bytes of dpid
631 System.arraycopy(dpidArray, 2, ofpPort.getHardwareAddress(), 0, 6);
632 // set the chassis id's value to last 6 bytes of dpid
633 System.arraycopy(dpidArray, 2, chassisId, 1, 6);
634 // set the optional tlv to the full dpid
635 System.arraycopy(dpidArray, 0, dpidTLVValue, 4, 8);
636
637
638 // set the portId to the outgoing port
639 portBB.putShort(port);
640 if (log.isTraceEnabled()) {
641 log.trace("Sending LLDP out of interface: {}/{}",
642 HexString.toHexString(sw), port);
643 }
644
645 LLDP lldp = new LLDP();
646 lldp.setChassisId(new LLDPTLV().setType((byte) 1).setLength((short) chassisId.length).setValue(chassisId));
647 lldp.setPortId(new LLDPTLV().setType((byte) 2).setLength((short) portId.length).setValue(portId));
648 lldp.setTtl(new LLDPTLV().setType((byte) 3).setLength((short) ttlValue.length).setValue(ttlValue));
649 lldp.getOptionalTLVList().add(dpidTLV);
650
651 // Add the controller identifier to the TLV value.
652 lldp.getOptionalTLVList().add(controllerTLV);
653 if (isReverse) {
654 lldp.getOptionalTLVList().add(reverseTLV);
655 }else {
656 lldp.getOptionalTLVList().add(forwardTLV);
657 }
658
659 Ethernet ethernet;
660 if (isStandard) {
661 ethernet = new Ethernet()
662 .setSourceMACAddress(ofpPort.getHardwareAddress())
663 .setDestinationMACAddress(LLDP_STANDARD_DST_MAC_STRING)
664 .setEtherType(Ethernet.TYPE_LLDP);
665 ethernet.setPayload(lldp);
666 } else {
667 BSN bsn = new BSN(BSN.BSN_TYPE_BDDP);
668 bsn.setPayload(lldp);
669
670 ethernet = new Ethernet()
671 .setSourceMACAddress(ofpPort.getHardwareAddress())
672 .setDestinationMACAddress(LLDP_BSN_DST_MAC_STRING)
673 .setEtherType(Ethernet.TYPE_BSN);
674 ethernet.setPayload(bsn);
675 }
676
677
678 // serialize and wrap in a packet out
679 byte[] data = ethernet.serialize();
680 OFPacketOut po = (OFPacketOut) floodlightProvider.getOFMessageFactory().getMessage(OFType.PACKET_OUT);
681 po.setBufferId(OFPacketOut.BUFFER_ID_NONE);
682 po.setInPort(OFPort.OFPP_NONE);
683
684 // set actions
685 List<OFAction> actions = new ArrayList<OFAction>();
686 actions.add(new OFActionOutput(port, (short) 0));
687 po.setActions(actions);
688 po.setActionsLength((short) OFActionOutput.MINIMUM_LENGTH);
689
690 // set data
691 po.setLengthU(OFPacketOut.MINIMUM_LENGTH + po.getActionsLength() + data.length);
692 po.setPacketData(data);
693
694 // send
695 try {
696 iofSwitch.write(po, null);
697 iofSwitch.flush();
698 } catch (IOException e) {
699 log.error("Failure sending LLDP out port {} on switch {}",
700 new Object[]{ port, iofSwitch.getStringId() }, e);
701 }
702
703 }
704
705 /**
706 * Send LLDPs to all switch-ports
707 */
708 protected void discoverOnAllPorts() {
709 if (log.isTraceEnabled()) {
710 log.trace("Sending LLDP packets out of all the enabled ports on switch {}");
711 }
712 Set<Long> switches = floodlightProvider.getSwitches().keySet();
713 // Send standard LLDPs
714 for (long sw: switches) {
715 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
716 if (iofSwitch == null) continue;
717 if (iofSwitch.getEnabledPorts() != null) {
718 for (OFPhysicalPort ofp: iofSwitch.getEnabledPorts()) {
719 if (isLinkDiscoverySuppressed(sw, ofp.getPortNumber()))
720 continue;
721 if (autoPortFastFeature && isFastPort(sw, ofp.getPortNumber()))
722 continue;
723
724 // sends forward LLDP only non-fastports.
725 sendDiscoveryMessage(sw, ofp.getPortNumber(), true, false);
726
727 // If the switch port is not alreayd in the maintenance
728 // queue, add it.
729 NodePortTuple npt = new NodePortTuple(sw, ofp.getPortNumber());
730 addToMaintenanceQueue(npt);
731 }
732 }
733 }
734 }
735
736 protected void setControllerTLV() {
737 //Setting the controllerTLVValue based on current nano time,
738 //controller's IP address, and the network interface object hash
739 //the corresponding IP address.
740
741 final int prime = 7867;
742 InetAddress localIPAddress = null;
743 NetworkInterface localInterface = null;
744
745 byte[] controllerTLVValue = new byte[] {0, 0, 0, 0, 0, 0, 0, 0}; // 8 byte value.
746 ByteBuffer bb = ByteBuffer.allocate(10);
747
748 try{
749 localIPAddress = java.net.InetAddress.getLocalHost();
750 localInterface = NetworkInterface.getByInetAddress(localIPAddress);
751 } catch (Exception e) {
752 e.printStackTrace();
753 }
754
755 long result = System.nanoTime();
756 if (localIPAddress != null)
757 result = result * prime + IPv4.toIPv4Address(localIPAddress.getHostAddress());
758 if (localInterface != null)
759 result = result * prime + localInterface.hashCode();
760 // set the first 4 bits to 0.
761 result = result & (0x0fffffffffffffffL);
762
763 bb.putLong(result);
764
765 bb.rewind();
766 bb.get(controllerTLVValue, 0, 8);
767
768 this.controllerTLV = new LLDPTLV().setType((byte) 0x0c).setLength((short) controllerTLVValue.length).setValue(controllerTLVValue);
769 }
770
771 @Override
772 public String getName() {
773 return "linkdiscovery";
774 }
775
776 @Override
777 public Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
778 switch (msg.getType()) {
779 case PACKET_IN:
780 return this.handlePacketIn(sw.getId(), (OFPacketIn) msg, cntx);
781 case PORT_STATUS:
782 return this.handlePortStatus(sw.getId(), (OFPortStatus) msg);
783 default:
784 break;
785 }
786 return Command.CONTINUE;
787 }
788
789 private Command handleLldp(LLDP lldp, long sw, OFPacketIn pi, boolean isStandard, FloodlightContext cntx) {
790 // If LLDP is suppressed on this port, ignore received packet as well
791 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
792 if (iofSwitch == null) {
793 return Command.STOP;
794 }
795
796 if (isLinkDiscoverySuppressed(sw, pi.getInPort()))
797 return Command.STOP;
798
799 // If this is a malformed LLDP, or not from us, exit
800 if (lldp.getPortId() == null || lldp.getPortId().getLength() != 3)
801 return Command.CONTINUE;
802
803 long myId = ByteBuffer.wrap(controllerTLV.getValue()).getLong();
804 long otherId = 0;
805 boolean myLLDP = false;
806 Boolean isReverse = null;
807
808 ByteBuffer portBB = ByteBuffer.wrap(lldp.getPortId().getValue());
809 portBB.position(1);
810
811 Short remotePort = portBB.getShort();
812 IOFSwitch remoteSwitch = null;
813
814 // Verify this LLDP packet matches what we're looking for
815 for (LLDPTLV lldptlv : lldp.getOptionalTLVList()) {
816 if (lldptlv.getType() == 127 && lldptlv.getLength() == 12 &&
817 lldptlv.getValue()[0] == 0x0 && lldptlv.getValue()[1] == 0x26 &&
818 lldptlv.getValue()[2] == (byte)0xe1 && lldptlv.getValue()[3] == 0x0) {
819 ByteBuffer dpidBB = ByteBuffer.wrap(lldptlv.getValue());
820 remoteSwitch = floodlightProvider.getSwitches().get(dpidBB.getLong(4));
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800821 if (remoteSwitch == null) {
822 // floodlight LLDP coming from a remote switch connected to a different controller
823 // add it to our cache of unconnected remote switches
824 remoteSwitch = addRemoteSwitch(dpidBB.getLong(4), remotePort);
825 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800826 } else if (lldptlv.getType() == 12 && lldptlv.getLength() == 8){
827 otherId = ByteBuffer.wrap(lldptlv.getValue()).getLong();
828 if (myId == otherId)
829 myLLDP = true;
830 } else if (lldptlv.getType() == TLV_DIRECTION_TYPE &&
831 lldptlv.getLength() == TLV_DIRECTION_LENGTH) {
832 if (lldptlv.getValue()[0] == TLV_DIRECTION_VALUE_FORWARD[0])
833 isReverse = false;
834 else if (lldptlv.getValue()[0] == TLV_DIRECTION_VALUE_REVERSE[0])
835 isReverse = true;
836 }
837 }
838
839 if (myLLDP == false) {
840 // This is not the LLDP sent by this controller.
841 // If the LLDP message has multicast bit set, then we need to broadcast
842 // the packet as a regular packet.
843 if (isStandard) {
844 if (log.isTraceEnabled()) {
845 log.trace("Getting standard LLDP from a different controller and quelching it.");
846 }
847 return Command.STOP;
848 }
849 else if (myId < otherId) {
850 if (log.isTraceEnabled()) {
851 log.trace("Getting BDDP packets from a different controller" +
852 "and letting it go through normal processing chain.");
853 }
854 return Command.CONTINUE;
855 }
856 }
857
858
859 if (remoteSwitch == null) {
860 // Ignore LLDPs not generated by Floodlight, or from a switch that has recently
861 // disconnected, or from a switch connected to another Floodlight instance
862 if (log.isTraceEnabled()) {
863 log.trace("Received LLDP from remote switch not connected to the controller");
864 }
865 return Command.STOP;
866 }
867
868 if (!remoteSwitch.portEnabled(remotePort)) {
869 if (log.isTraceEnabled()) {
870 log.trace("Ignoring link with disabled source port: switch {} port {}", remoteSwitch, remotePort);
871 }
872 return Command.STOP;
873 }
874 if (suppressLinkDiscovery.contains(new NodePortTuple(remoteSwitch.getId(),
875 remotePort))) {
876 if (log.isTraceEnabled()) {
877 log.trace("Ignoring link with suppressed src port: switch {} port {}",
878 remoteSwitch, remotePort);
879 }
880 return Command.STOP;
881 }
882 if (!iofSwitch.portEnabled(pi.getInPort())) {
883 if (log.isTraceEnabled()) {
884 log.trace("Ignoring link with disabled dest port: switch {} port {}", sw, pi.getInPort());
885 }
886 return Command.STOP;
887 }
888
889 OFPhysicalPort physicalPort = remoteSwitch.getPort(remotePort);
890 int srcPortState = (physicalPort != null) ? physicalPort.getState() : 0;
891 physicalPort = iofSwitch.getPort(pi.getInPort());
892 int dstPortState = (physicalPort != null) ? physicalPort.getState() : 0;
893
894 // Store the time of update to this link, and push it out to routingEngine
895 Link lt = new Link(remoteSwitch.getId(), remotePort, iofSwitch.getId(), pi.getInPort());
896
897
898 Long lastLldpTime = null;
899 Long lastBddpTime = null;
900
901 Long firstSeenTime = System.currentTimeMillis();
902
903 if (isStandard)
904 lastLldpTime = System.currentTimeMillis();
905 else
906 lastBddpTime = System.currentTimeMillis();
907
908 LinkInfo newLinkInfo =
909 new LinkInfo(firstSeenTime, lastLldpTime, lastBddpTime,
910 srcPortState, dstPortState);
911
912 addOrUpdateLink(lt, newLinkInfo);
913
914 // Check if reverse link exists.
915 // If it doesn't exist and if the forward link was seen
916 // first seen within a small interval, send probe on the
917 // reverse link.
918
919 newLinkInfo = links.get(lt);
920 if (newLinkInfo != null && isStandard && isReverse == false) {
921 Link reverseLink = new Link(lt.getDst(), lt.getDstPort(),
922 lt.getSrc(), lt.getSrcPort());
923 LinkInfo reverseInfo = links.get(reverseLink);
924 if (reverseInfo == null) {
925 // the reverse link does not exist.
926 if (newLinkInfo.getFirstSeenTime() > System.currentTimeMillis() - LINK_TIMEOUT) {
927 this.sendDiscoveryMessage(lt.getDst(), lt.getDstPort(), isStandard, true);
928 }
929 }
930 }
931
932 // If the received packet is a BDDP packet, then create a reverse BDDP
933 // link as well.
934 if (!isStandard) {
935 Link reverseLink = new Link(lt.getDst(), lt.getDstPort(),
936 lt.getSrc(), lt.getSrcPort());
937
938 // srcPortState and dstPort state are reversed.
939 LinkInfo reverseInfo =
940 new LinkInfo(firstSeenTime, lastLldpTime, lastBddpTime,
941 dstPortState, srcPortState);
942
943 addOrUpdateLink(reverseLink, reverseInfo);
944 }
945
946 // Remove the node ports from the quarantine and maintenance queues.
947 NodePortTuple nptSrc = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
948 NodePortTuple nptDst = new NodePortTuple(lt.getDst(), lt.getDstPort());
949 removeFromQuarantineQueue(nptSrc);
950 removeFromMaintenanceQueue(nptSrc);
951 removeFromQuarantineQueue(nptDst);
952 removeFromMaintenanceQueue(nptDst);
953
954 // Consume this message
955 return Command.STOP;
956 }
957
958 protected Command handlePacketIn(long sw, OFPacketIn pi,
959 FloodlightContext cntx) {
960 Ethernet eth =
961 IFloodlightProviderService.bcStore.get(cntx,
962 IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
963
964 if(eth.getEtherType() == Ethernet.TYPE_BSN) {
965 BSN bsn = (BSN) eth.getPayload();
966 if (bsn == null) return Command.STOP;
967 if (bsn.getPayload() == null) return Command.STOP;
968 // It could be a packet other than BSN LLDP, therefore
969 // continue with the regular processing.
970 if (bsn.getPayload() instanceof LLDP == false)
971 return Command.CONTINUE;
972 return handleLldp((LLDP) bsn.getPayload(), sw, pi, false, cntx);
973 } else if (eth.getEtherType() == Ethernet.TYPE_LLDP) {
974 return handleLldp((LLDP) eth.getPayload(), sw, pi, true, cntx);
975 } else if (eth.getEtherType() < 1500) {
976 long destMac = eth.getDestinationMAC().toLong();
977 if ((destMac & LINK_LOCAL_MASK) == LINK_LOCAL_VALUE){
978 if (log.isTraceEnabled()) {
979 log.trace("Ignoring packet addressed to 802.1D/Q " +
980 "reserved address.");
981 }
982 return Command.STOP;
983 }
984 }
985
986 // If packet-in is from a quarantine port, stop processing.
987 NodePortTuple npt = new NodePortTuple(sw, pi.getInPort());
988 if (quarantineQueue.contains(npt)) return Command.STOP;
989
990 return Command.CONTINUE;
991 }
992
993 protected UpdateOperation getUpdateOperation(int srcPortState,
994 int dstPortState) {
995 boolean added =
996 (((srcPortState &
997 OFPortState.OFPPS_STP_MASK.getValue()) !=
998 OFPortState.OFPPS_STP_BLOCK.getValue()) &&
999 ((dstPortState &
1000 OFPortState.OFPPS_STP_MASK.getValue()) !=
1001 OFPortState.OFPPS_STP_BLOCK.getValue()));
1002
1003 if (added) return UpdateOperation.LINK_UPDATED;
1004 return UpdateOperation.LINK_REMOVED;
1005 }
1006
1007
1008
1009 protected UpdateOperation getUpdateOperation(int srcPortState) {
1010 boolean portUp = ((srcPortState &
1011 OFPortState.OFPPS_STP_MASK.getValue()) !=
1012 OFPortState.OFPPS_STP_BLOCK.getValue());
1013
1014 if (portUp) return UpdateOperation.PORT_UP;
1015 else return UpdateOperation.PORT_DOWN;
1016 }
1017
1018 protected boolean addOrUpdateLink(Link lt, LinkInfo newInfo) {
1019
1020 NodePortTuple srcNpt, dstNpt;
1021 boolean linkChanged = false;
1022
1023 lock.writeLock().lock();
1024 try {
1025 // put the new info. if an old info exists, it will be returned.
1026 LinkInfo oldInfo = links.put(lt, newInfo);
1027 if (oldInfo != null &&
1028 oldInfo.getFirstSeenTime() < newInfo.getFirstSeenTime())
1029 newInfo.setFirstSeenTime(oldInfo.getFirstSeenTime());
1030
1031 if (log.isTraceEnabled()) {
1032 log.trace("addOrUpdateLink: {} {}",
1033 lt,
1034 (newInfo.getMulticastValidTime()!=null) ? "multicast" : "unicast");
1035 }
1036
1037 UpdateOperation updateOperation = null;
1038 linkChanged = false;
1039
1040 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1041 dstNpt = new NodePortTuple(lt.getDst(), lt.getDstPort());
1042
1043 if (oldInfo == null) {
1044 // index it by switch source
1045 if (!switchLinks.containsKey(lt.getSrc()))
1046 switchLinks.put(lt.getSrc(), new HashSet<Link>());
1047 switchLinks.get(lt.getSrc()).add(lt);
1048
1049 // index it by switch dest
1050 if (!switchLinks.containsKey(lt.getDst()))
1051 switchLinks.put(lt.getDst(), new HashSet<Link>());
1052 switchLinks.get(lt.getDst()).add(lt);
1053
1054 // index both ends by switch:port
1055 if (!portLinks.containsKey(srcNpt))
1056 portLinks.put(srcNpt, new HashSet<Link>());
1057 portLinks.get(srcNpt).add(lt);
1058
1059 if (!portLinks.containsKey(dstNpt))
1060 portLinks.put(dstNpt, new HashSet<Link>());
1061 portLinks.get(dstNpt).add(lt);
1062
1063 // Add to portNOFLinks if the unicast valid time is null
1064 if (newInfo.getUnicastValidTime() == null)
1065 addLinkToBroadcastDomain(lt);
1066
1067 writeLinkToStorage(lt, newInfo);
Umesh Krishnaswamy2b9d5642013-01-04 11:00:27 -08001068
1069 // Write link to network map
1070 linkStore.update(lt, newInfo, DM_OPERATION.INSERT);
1071
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001072 updateOperation = UpdateOperation.LINK_UPDATED;
1073 linkChanged = true;
1074
1075 // Add to event history
1076 evHistTopoLink(lt.getSrc(),
1077 lt.getDst(),
1078 lt.getSrcPort(),
1079 lt.getDstPort(),
1080 newInfo.getSrcPortState(), newInfo.getDstPortState(),
1081 getLinkType(lt, newInfo),
1082 EvAction.LINK_ADDED, "LLDP Recvd");
1083 } else {
1084 // Since the link info is already there, we need to
1085 // update the right fields.
1086 if (newInfo.getUnicastValidTime() == null) {
1087 // This is due to a multicast LLDP, so copy the old unicast
1088 // value.
1089 if (oldInfo.getUnicastValidTime() != null) {
1090 newInfo.setUnicastValidTime(oldInfo.getUnicastValidTime());
1091 }
1092 } else if (newInfo.getMulticastValidTime() == null) {
1093 // This is due to a unicast LLDP, so copy the old multicast
1094 // value.
1095 if (oldInfo.getMulticastValidTime() != null) {
1096 newInfo.setMulticastValidTime(oldInfo.getMulticastValidTime());
1097 }
1098 }
1099
1100 Long oldTime = oldInfo.getUnicastValidTime();
1101 Long newTime = newInfo.getUnicastValidTime();
1102 // the link has changed its state between openflow and non-openflow
1103 // if the unicastValidTimes are null or not null
1104 if (oldTime != null & newTime == null) {
1105 // openflow -> non-openflow transition
1106 // we need to add the link tuple to the portNOFLinks
1107 addLinkToBroadcastDomain(lt);
1108 linkChanged = true;
1109 } else if (oldTime == null & newTime != null) {
1110 // non-openflow -> openflow transition
1111 // we need to remove the link from the portNOFLinks
1112 removeLinkFromBroadcastDomain(lt);
1113 linkChanged = true;
1114 }
1115
1116 // Only update the port states if they've changed
1117 if (newInfo.getSrcPortState().intValue() !=
1118 oldInfo.getSrcPortState().intValue() ||
1119 newInfo.getDstPortState().intValue() !=
1120 oldInfo.getDstPortState().intValue())
1121 linkChanged = true;
1122
1123 // Write changes to storage. This will always write the updated
1124 // valid time, plus the port states if they've changed (i.e. if
1125 // they weren't set to null in the previous block of code.
1126 writeLinkToStorage(lt, newInfo);
1127
Umesh Krishnaswamy2b9d5642013-01-04 11:00:27 -08001128 // Write link to network map
1129 linkStore.update(lt, newInfo, DM_OPERATION.UPDATE);
1130
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001131 if (linkChanged) {
1132 updateOperation = getUpdateOperation(newInfo.getSrcPortState(),
1133 newInfo.getDstPortState());
1134 if (log.isTraceEnabled()) {
1135 log.trace("Updated link {}", lt);
1136 }
1137 // Add to event history
1138 evHistTopoLink(lt.getSrc(),
1139 lt.getDst(),
1140 lt.getSrcPort(),
1141 lt.getDstPort(),
1142 newInfo.getSrcPortState(), newInfo.getDstPortState(),
1143 getLinkType(lt, newInfo),
1144 EvAction.LINK_PORT_STATE_UPDATED,
1145 "LLDP Recvd");
1146 }
1147 }
1148
1149 if (linkChanged) {
1150 // find out if the link was added or removed here.
1151 updates.add(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
1152 lt.getDst(), lt.getDstPort(),
1153 getLinkType(lt, newInfo),
1154 updateOperation));
1155 }
1156 } finally {
1157 lock.writeLock().unlock();
1158 }
1159
1160 return linkChanged;
1161 }
1162
1163 public Map<Long, Set<Link>> getSwitchLinks() {
1164 return this.switchLinks;
1165 }
1166
1167 /**
1168 * Removes links from memory and storage.
1169 * @param links The List of @LinkTuple to delete.
1170 */
1171 protected void deleteLinks(List<Link> links, String reason) {
1172 NodePortTuple srcNpt, dstNpt;
1173
1174 lock.writeLock().lock();
1175 try {
1176 for (Link lt : links) {
1177 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1178 dstNpt =new NodePortTuple(lt.getDst(), lt.getDstPort());
1179
1180 switchLinks.get(lt.getSrc()).remove(lt);
1181 switchLinks.get(lt.getDst()).remove(lt);
1182 if (switchLinks.containsKey(lt.getSrc()) &&
1183 switchLinks.get(lt.getSrc()).isEmpty())
1184 this.switchLinks.remove(lt.getSrc());
1185 if (this.switchLinks.containsKey(lt.getDst()) &&
1186 this.switchLinks.get(lt.getDst()).isEmpty())
1187 this.switchLinks.remove(lt.getDst());
1188
1189 if (this.portLinks.get(srcNpt) != null) {
1190 this.portLinks.get(srcNpt).remove(lt);
1191 if (this.portLinks.get(srcNpt).isEmpty())
1192 this.portLinks.remove(srcNpt);
1193 }
1194 if (this.portLinks.get(dstNpt) != null) {
1195 this.portLinks.get(dstNpt).remove(lt);
1196 if (this.portLinks.get(dstNpt).isEmpty())
1197 this.portLinks.remove(dstNpt);
1198 }
1199
1200 LinkInfo info = this.links.remove(lt);
1201 updates.add(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
1202 lt.getDst(), lt.getDstPort(),
1203 getLinkType(lt, info),
1204 UpdateOperation.LINK_REMOVED));
1205
1206 // Update Event History
1207 evHistTopoLink(lt.getSrc(),
1208 lt.getDst(),
1209 lt.getSrcPort(),
1210 lt.getDstPort(),
1211 0, 0, // Port states
1212 ILinkDiscovery.LinkType.INVALID_LINK,
1213 EvAction.LINK_DELETED, reason);
1214
1215 // remove link from storage.
1216 removeLinkFromStorage(lt);
1217
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -08001218 // remote link from network map
Umesh Krishnaswamy2b9d5642013-01-04 11:00:27 -08001219 linkStore.update(lt, DM_OPERATION.DELETE);
1220
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001221 // TODO Whenever link is removed, it has to checked if
1222 // the switchports must be added to quarantine.
1223
1224 if (log.isTraceEnabled()) {
1225 log.trace("Deleted link {}", lt);
1226 }
1227 }
1228 } finally {
1229 lock.writeLock().unlock();
1230 }
1231 }
1232
1233 /**
1234 * Handles an OFPortStatus message from a switch. We will add or
1235 * delete LinkTupes as well re-compute the topology if needed.
1236 * @param sw The IOFSwitch that sent the port status message
1237 * @param ps The OFPortStatus message
1238 * @return The Command to continue or stop after we process this message
1239 */
1240 protected Command handlePortStatus(long sw, OFPortStatus ps) {
1241
1242 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
1243 if (iofSwitch == null) return Command.CONTINUE;
1244
1245 if (log.isTraceEnabled()) {
1246 log.trace("handlePortStatus: Switch {} port #{} reason {}; " +
1247 "config is {} state is {}",
1248 new Object[] {iofSwitch.getStringId(),
1249 ps.getDesc().getPortNumber(),
1250 ps.getReason(),
1251 ps.getDesc().getConfig(),
1252 ps.getDesc().getState()});
1253 }
1254
1255 short port = ps.getDesc().getPortNumber();
1256 NodePortTuple npt = new NodePortTuple(sw, port);
1257 boolean linkDeleted = false;
1258 boolean linkInfoChanged = false;
1259
1260 lock.writeLock().lock();
1261 try {
1262 // if ps is a delete, or a modify where the port is down or
1263 // configured down
1264 if ((byte)OFPortReason.OFPPR_DELETE.ordinal() == ps.getReason() ||
1265 ((byte)OFPortReason.OFPPR_MODIFY.ordinal() ==
1266 ps.getReason() && !portEnabled(ps.getDesc()))) {
1267 deleteLinksOnPort(npt, "Port Status Changed");
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -08001268 //swStore.deletePort(HexString.toHexString(npt.getNodeId()), npt.getPortId());
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001269 LDUpdate update = new LDUpdate(sw, port, UpdateOperation.PORT_DOWN);
1270 updates.add(update);
1271 linkDeleted = true;
1272 }
1273 else if (ps.getReason() ==
1274 (byte)OFPortReason.OFPPR_MODIFY.ordinal()) {
1275 // If ps is a port modification and the port state has changed
1276 // that affects links in the topology
1277
1278 if (this.portLinks.containsKey(npt)) {
1279 for (Link lt: this.portLinks.get(npt)) {
1280 LinkInfo linkInfo = links.get(lt);
1281 assert(linkInfo != null);
1282 Integer updatedSrcPortState = null;
1283 Integer updatedDstPortState = null;
1284 if (lt.getSrc() == npt.getNodeId() &&
1285 lt.getSrcPort() == npt.getPortId() &&
1286 (linkInfo.getSrcPortState() !=
1287 ps.getDesc().getState())) {
1288 updatedSrcPortState = ps.getDesc().getState();
1289 linkInfo.setSrcPortState(updatedSrcPortState);
1290 }
1291 if (lt.getDst() == npt.getNodeId() &&
1292 lt.getDstPort() == npt.getPortId() &&
1293 (linkInfo.getDstPortState() !=
1294 ps.getDesc().getState())) {
1295 updatedDstPortState = ps.getDesc().getState();
1296 linkInfo.setDstPortState(updatedDstPortState);
1297 }
1298 if ((updatedSrcPortState != null) ||
1299 (updatedDstPortState != null)) {
1300 // The link is already known to link discovery
1301 // manager and the status has changed, therefore
1302 // send an LDUpdate.
1303 UpdateOperation operation =
1304 getUpdateOperation(linkInfo.getSrcPortState(),
1305 linkInfo.getDstPortState());
1306 updates.add(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
1307 lt.getDst(), lt.getDstPort(),
1308 getLinkType(lt, linkInfo),
1309 operation));
1310 writeLinkToStorage(lt, linkInfo);
Umesh Krishnaswamy2b9d5642013-01-04 11:00:27 -08001311
1312 // Write the changed link to the network map
1313 linkStore.update(lt, linkInfo, DM_OPERATION.UPDATE);
1314
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001315 linkInfoChanged = true;
1316 }
1317 }
1318 }
1319
1320 UpdateOperation operation =
1321 getUpdateOperation(ps.getDesc().getState());
1322 updates.add(new LDUpdate(sw, port, operation));
1323 }
1324
1325 if (!linkDeleted && !linkInfoChanged){
1326 if (log.isTraceEnabled()) {
1327 log.trace("handlePortStatus: Switch {} port #{} reason {};"+
1328 " no links to update/remove",
1329 new Object[] {HexString.toHexString(sw),
1330 ps.getDesc().getPortNumber(),
1331 ps.getReason()});
1332 }
1333 }
1334 } finally {
1335 lock.writeLock().unlock();
1336 }
1337
1338 if (!linkDeleted) {
1339 // Send LLDP right away when port state is changed for faster
1340 // cluster-merge. If it is a link delete then there is not need
1341 // to send the LLDPs right away and instead we wait for the LLDPs
1342 // to be sent on the timer as it is normally done
1343 // do it outside the write-lock
1344 // sendLLDPTask.reschedule(1000, TimeUnit.MILLISECONDS);
1345 processNewPort(npt.getNodeId(), npt.getPortId());
1346 }
1347 return Command.CONTINUE;
1348 }
1349
1350 /**
1351 * Process a new port.
1352 * If link discovery is disabled on the port, then do nothing.
1353 * If autoportfast feature is enabled and the port is a fast port, then
1354 * do nothing.
1355 * Otherwise, send LLDP message. Add the port to quarantine.
1356 * @param sw
1357 * @param p
1358 */
1359 private void processNewPort(long sw, short p) {
1360 if (isLinkDiscoverySuppressed(sw, p)) {
1361 // Do nothing as link discovery is suppressed.
1362 }
1363 else if (autoPortFastFeature && isFastPort(sw, p)) {
1364 // Do nothing as the port is a fast port.
1365 }
1366 else {
1367 NodePortTuple npt = new NodePortTuple(sw, p);
1368 discover(sw, p);
1369 // if it is not a fast port, add it to quarantine.
1370 if (!isFastPort(sw, p)) {
1371 addToQuarantineQueue(npt);
1372 } else {
1373 // Add to maintenance queue to ensure that BDDP packets
1374 // are sent out.
1375 addToMaintenanceQueue(npt);
1376 }
1377 }
1378 }
1379
1380 /**
1381 * We send out LLDP messages when a switch is added to discover the topology
1382 * @param sw The IOFSwitch that connected to the controller
1383 */
1384 @Override
1385 public void addedSwitch(IOFSwitch sw) {
1386
1387 if (sw.getEnabledPorts() != null) {
1388 for (Short p : sw.getEnabledPortNumbers()) {
1389 processNewPort(sw.getId(), p);
1390 }
1391 }
1392 // Update event history
1393 evHistTopoSwitch(sw, EvAction.SWITCH_CONNECTED, "None");
1394 LDUpdate update = new LDUpdate(sw.getId(), null,
1395 UpdateOperation.SWITCH_UPDATED);
1396 updates.add(update);
1397 }
1398
1399 /**
1400 * When a switch disconnects we remove any links from our map and notify.
1401 * @param The id of the switch
1402 */
1403 @Override
1404 public void removedSwitch(IOFSwitch iofSwitch) {
1405 // Update event history
1406 long sw = iofSwitch.getId();
1407 evHistTopoSwitch(iofSwitch, EvAction.SWITCH_DISCONNECTED, "None");
1408 List<Link> eraseList = new ArrayList<Link>();
1409 lock.writeLock().lock();
1410 try {
1411 if (switchLinks.containsKey(sw)) {
1412 if (log.isTraceEnabled()) {
1413 log.trace("Handle switchRemoved. Switch {}; removing links {}",
1414 HexString.toHexString(sw), switchLinks.get(sw));
1415 }
1416 // add all tuples with an endpoint on this switch to erase list
1417 eraseList.addAll(switchLinks.get(sw));
1418 deleteLinks(eraseList, "Switch Removed");
1419
1420 // Send a switch removed update
1421 LDUpdate update = new LDUpdate(sw, null, UpdateOperation.SWITCH_REMOVED);
1422 updates.add(update);
1423 }
1424 } finally {
1425 lock.writeLock().unlock();
1426 }
1427 }
1428
1429 /**
1430 * We don't react the port changed notifications here. we listen for
1431 * OFPortStatus messages directly. Might consider using this notifier
1432 * instead
1433 */
1434 @Override
1435 public void switchPortChanged(Long switchId) {
1436 // no-op
1437 }
1438
1439 /**
1440 * Delete links incident on a given switch port.
1441 * @param npt
1442 * @param reason
1443 */
1444 protected void deleteLinksOnPort(NodePortTuple npt, String reason) {
1445 List<Link> eraseList = new ArrayList<Link>();
1446 if (this.portLinks.containsKey(npt)) {
1447 if (log.isTraceEnabled()) {
1448 log.trace("handlePortStatus: Switch {} port #{} " +
1449 "removing links {}",
1450 new Object[] {HexString.toHexString(npt.getNodeId()),
1451 npt.getPortId(),
1452 this.portLinks.get(npt)});
1453 }
1454 eraseList.addAll(this.portLinks.get(npt));
1455 deleteLinks(eraseList, reason);
1456 }
1457 }
1458
1459 /**
1460 * Iterates through the list of links and deletes if the
1461 * last discovery message reception time exceeds timeout values.
1462 */
1463 protected void timeoutLinks() {
1464 List<Link> eraseList = new ArrayList<Link>();
1465 Long curTime = System.currentTimeMillis();
1466 boolean linkChanged = false;
1467
1468 // reentrant required here because deleteLink also write locks
1469 lock.writeLock().lock();
1470 try {
1471 Iterator<Entry<Link, LinkInfo>> it =
1472 this.links.entrySet().iterator();
1473 while (it.hasNext()) {
1474 Entry<Link, LinkInfo> entry = it.next();
1475 Link lt = entry.getKey();
1476 LinkInfo info = entry.getValue();
1477
1478 // Timeout the unicast and multicast LLDP valid times
1479 // independently.
1480 if ((info.getUnicastValidTime() != null) &&
1481 (info.getUnicastValidTime() + (this.LINK_TIMEOUT * 1000) < curTime)){
1482 info.setUnicastValidTime(null);
1483
1484 if (info.getMulticastValidTime() != null)
1485 addLinkToBroadcastDomain(lt);
1486 // Note that even if mTime becomes null later on,
1487 // the link would be deleted, which would trigger updateClusters().
1488 linkChanged = true;
1489 }
1490 if ((info.getMulticastValidTime()!= null) &&
1491 (info.getMulticastValidTime()+ (this.LINK_TIMEOUT * 1000) < curTime)) {
1492 info.setMulticastValidTime(null);
1493 // if uTime is not null, then link will remain as openflow
1494 // link. If uTime is null, it will be deleted. So, we
1495 // don't care about linkChanged flag here.
1496 removeLinkFromBroadcastDomain(lt);
1497 linkChanged = true;
1498 }
1499 // Add to the erase list only if the unicast
1500 // time is null.
1501 if (info.getUnicastValidTime() == null &&
1502 info.getMulticastValidTime() == null){
1503 eraseList.add(entry.getKey());
1504 } else if (linkChanged) {
1505 UpdateOperation operation;
1506 operation = getUpdateOperation(info.getSrcPortState(),
1507 info.getDstPortState());
1508 updates.add(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
1509 lt.getDst(), lt.getDstPort(),
1510 getLinkType(lt, info),
1511 operation));
1512 }
1513 }
1514
1515 // if any link was deleted or any link was changed.
1516 if ((eraseList.size() > 0) || linkChanged) {
1517 deleteLinks(eraseList, "LLDP timeout");
1518 }
1519 } finally {
1520 lock.writeLock().unlock();
1521 }
1522 }
1523
1524 private boolean portEnabled(OFPhysicalPort port) {
1525 if (port == null)
1526 return false;
1527 if ((OFPortConfig.OFPPC_PORT_DOWN.getValue() & port.getConfig()) > 0)
1528 return false;
1529 if ((OFPortState.OFPPS_LINK_DOWN.getValue() & port.getState()) > 0)
1530 return false;
1531 // Port STP state doesn't work with multiple VLANs, so ignore it for now
1532 // if ((port.getState() & OFPortState.OFPPS_STP_MASK.getValue()) == OFPortState.OFPPS_STP_BLOCK.getValue())
1533 // return false;
1534 return true;
1535 }
1536
1537 public Map<NodePortTuple, Set<Link>> getPortBroadcastDomainLinks() {
1538 return portBroadcastDomainLinks;
1539 }
1540
1541 @Override
1542 public Map<Link, LinkInfo> getLinks() {
1543 lock.readLock().lock();
1544 Map<Link, LinkInfo> result;
1545 try {
1546 result = new HashMap<Link, LinkInfo>(links);
1547 } finally {
1548 lock.readLock().unlock();
1549 }
1550 return result;
1551 }
1552
1553 protected void addLinkToBroadcastDomain(Link lt) {
1554
1555 NodePortTuple srcNpt, dstNpt;
1556 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1557 dstNpt = new NodePortTuple(lt.getDst(), lt.getDstPort());
1558
1559 if (!portBroadcastDomainLinks.containsKey(lt.getSrc()))
1560 portBroadcastDomainLinks.put(srcNpt, new HashSet<Link>());
1561 portBroadcastDomainLinks.get(srcNpt).add(lt);
1562
1563 if (!portBroadcastDomainLinks.containsKey(lt.getDst()))
1564 portBroadcastDomainLinks.put(dstNpt, new HashSet<Link>());
1565 portBroadcastDomainLinks.get(dstNpt).add(lt);
1566 }
1567
1568 protected void removeLinkFromBroadcastDomain(Link lt) {
1569
1570 NodePortTuple srcNpt, dstNpt;
1571 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1572 dstNpt = new NodePortTuple(lt.getDst(), lt.getDstPort());
1573
1574 if (portBroadcastDomainLinks.containsKey(srcNpt)) {
1575 portBroadcastDomainLinks.get(srcNpt).remove(lt);
1576 if (portBroadcastDomainLinks.get(srcNpt).isEmpty())
1577 portBroadcastDomainLinks.remove(srcNpt);
1578 }
1579
1580 if (portBroadcastDomainLinks.containsKey(dstNpt)) {
1581 portBroadcastDomainLinks.get(dstNpt).remove(lt);
1582 if (portBroadcastDomainLinks.get(dstNpt).isEmpty())
1583 portBroadcastDomainLinks.remove(dstNpt);
1584 }
1585 }
1586
1587 // STORAGE METHODS
1588 /**
1589 * Deletes all links from storage
1590 */
1591 void clearAllLinks() {
1592 storageSource.deleteRowsAsync(LINK_TABLE_NAME, null);
1593 }
1594
1595 /**
1596 * Gets the storage key for a LinkTuple
1597 * @param lt The LinkTuple to get
1598 * @return The storage key as a String
1599 */
1600 private String getLinkId(Link lt) {
1601 return HexString.toHexString(lt.getSrc()) +
1602 "-" + lt.getSrcPort() + "-" +
1603 HexString.toHexString(lt.getDst())+
1604 "-" + lt.getDstPort();
1605 }
1606
1607 /**
1608 * Writes a LinkTuple and corresponding LinkInfo to storage
1609 * @param lt The LinkTuple to write
1610 * @param linkInfo The LinkInfo to write
1611 */
1612 protected void writeLinkToStorage(Link lt, LinkInfo linkInfo) {
1613 LinkType type = getLinkType(lt, linkInfo);
1614
1615 // Write only direct links. Do not write links to external
1616 // L2 network.
1617 // if (type != LinkType.DIRECT_LINK && type != LinkType.TUNNEL) {
1618 // return;
1619 // }
1620
1621 Map<String, Object> rowValues = new HashMap<String, Object>();
1622 String id = getLinkId(lt);
1623 rowValues.put(LINK_ID, id);
1624 rowValues.put(LINK_VALID_TIME, linkInfo.getUnicastValidTime());
1625 String srcDpid = HexString.toHexString(lt.getSrc());
1626 rowValues.put(LINK_SRC_SWITCH, srcDpid);
1627 rowValues.put(LINK_SRC_PORT, lt.getSrcPort());
1628
1629 if (type == LinkType.DIRECT_LINK)
1630 rowValues.put(LINK_TYPE, "internal");
1631 else if (type == LinkType.MULTIHOP_LINK)
1632 rowValues.put(LINK_TYPE, "external");
1633 else if (type == LinkType.TUNNEL)
1634 rowValues.put(LINK_TYPE, "tunnel");
1635 else rowValues.put(LINK_TYPE, "invalid");
1636
1637 if (linkInfo.linkStpBlocked()) {
1638 if (log.isTraceEnabled()) {
1639 log.trace("writeLink, link {}, info {}, srcPortState Blocked",
1640 lt, linkInfo);
1641 }
1642 rowValues.put(LINK_SRC_PORT_STATE,
1643 OFPhysicalPort.OFPortState.OFPPS_STP_BLOCK.getValue());
1644 } else {
1645 if (log.isTraceEnabled()) {
1646 log.trace("writeLink, link {}, info {}, srcPortState {}",
1647 new Object[]{ lt, linkInfo, linkInfo.getSrcPortState() });
1648 }
1649 rowValues.put(LINK_SRC_PORT_STATE, linkInfo.getSrcPortState());
1650 }
1651 String dstDpid = HexString.toHexString(lt.getDst());
1652 rowValues.put(LINK_DST_SWITCH, dstDpid);
1653 rowValues.put(LINK_DST_PORT, lt.getDstPort());
1654 if (linkInfo.linkStpBlocked()) {
1655 if (log.isTraceEnabled()) {
1656 log.trace("writeLink, link {}, info {}, dstPortState Blocked",
1657 lt, linkInfo);
1658 }
1659 rowValues.put(LINK_DST_PORT_STATE,
1660 OFPhysicalPort.OFPortState.OFPPS_STP_BLOCK.getValue());
1661 } else {
1662 if (log.isTraceEnabled()) {
1663 log.trace("writeLink, link {}, info {}, dstPortState {}",
1664 new Object[]{ lt, linkInfo, linkInfo.getDstPortState() });
1665 }
1666 rowValues.put(LINK_DST_PORT_STATE, linkInfo.getDstPortState());
1667 }
1668 storageSource.updateRowAsync(LINK_TABLE_NAME, rowValues);
1669 }
1670
1671 public Long readLinkValidTime(Link lt) {
1672 // FIXME: We're not currently using this right now, but if we start
1673 // to use this again, we probably shouldn't use it in its current
1674 // form, because it's doing synchronous storage calls. Depending
1675 // on the context this may still be OK, but if it's being called
1676 // on the packet in processing thread it should be reworked to
1677 // use asynchronous storage calls.
1678 Long validTime = null;
1679 IResultSet resultSet = null;
1680 try {
1681 String[] columns = { LINK_VALID_TIME };
1682 String id = getLinkId(lt);
1683 resultSet = storageSource.executeQuery(LINK_TABLE_NAME, columns,
1684 new OperatorPredicate(LINK_ID, OperatorPredicate.Operator.EQ, id), null);
1685 if (resultSet.next())
1686 validTime = resultSet.getLong(LINK_VALID_TIME);
1687 }
1688 finally {
1689 if (resultSet != null)
1690 resultSet.close();
1691 }
1692 return validTime;
1693 }
1694
1695 /**
1696 * Removes a link from storage using an asynchronous call.
1697 * @param lt The LinkTuple to delete.
1698 */
1699 protected void removeLinkFromStorage(Link lt) {
1700 String id = getLinkId(lt);
1701 storageSource.deleteRowAsync(LINK_TABLE_NAME, id);
1702 }
1703
1704 @Override
1705 public void addListener(ILinkDiscoveryListener listener) {
1706 linkDiscoveryAware.add(listener);
1707 }
1708
1709 /**
1710 * Register a link discovery aware component
1711 * @param linkDiscoveryAwareComponent
1712 */
1713 public void addLinkDiscoveryAware(ILinkDiscoveryListener linkDiscoveryAwareComponent) {
1714 // TODO make this a copy on write set or lock it somehow
1715 this.linkDiscoveryAware.add(linkDiscoveryAwareComponent);
1716 }
1717
1718 /**
1719 * Deregister a link discovery aware component
1720 * @param linkDiscoveryAwareComponent
1721 */
1722 public void removeLinkDiscoveryAware(ILinkDiscoveryListener linkDiscoveryAwareComponent) {
1723 // TODO make this a copy on write set or lock it somehow
1724 this.linkDiscoveryAware.remove(linkDiscoveryAwareComponent);
1725 }
1726
1727 /**
1728 * Sets the IStorageSource to use for ITology
1729 * @param storageSource the storage source to use
1730 */
1731 public void setStorageSource(IStorageSourceService storageSource) {
1732 this.storageSource = storageSource;
1733 }
1734
1735 /**
1736 * Gets the storage source for this ITopology
1737 * @return The IStorageSource ITopology is writing to
1738 */
1739 public IStorageSourceService getStorageSource() {
1740 return storageSource;
1741 }
1742
1743 @Override
1744 public boolean isCallbackOrderingPrereq(OFType type, String name) {
1745 return false;
1746 }
1747
1748 @Override
1749 public boolean isCallbackOrderingPostreq(OFType type, String name) {
1750 return false;
1751 }
1752
1753 @Override
1754 public void rowsModified(String tableName, Set<Object> rowKeys) {
1755 Map<Long, IOFSwitch> switches = floodlightProvider.getSwitches();
1756 ArrayList<IOFSwitch> updated_switches = new ArrayList<IOFSwitch>();
1757 for(Object key: rowKeys) {
1758 Long swId = new Long(HexString.toLong((String)key));
1759 if (switches.containsKey(swId)) {
1760 IOFSwitch sw = switches.get(swId);
1761 boolean curr_status = sw.hasAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH);
1762 boolean new_status = false;
1763 IResultSet resultSet = null;
1764
1765 try {
1766 resultSet = storageSource.getRow(tableName, key);
1767 for (Iterator<IResultSet> it = resultSet.iterator(); it.hasNext();) {
1768 // In case of multiple rows, use the status in last row?
1769 Map<String, Object> row = it.next().getRow();
1770 if (row.containsKey(SWITCH_CONFIG_CORE_SWITCH)) {
1771 new_status = ((String)row.get(SWITCH_CONFIG_CORE_SWITCH)).equals("true");
1772 }
1773 }
1774 }
1775 finally {
1776 if (resultSet != null)
1777 resultSet.close();
1778 }
1779
1780 if (curr_status != new_status) {
1781 updated_switches.add(sw);
1782 }
1783 } else {
1784 if (log.isTraceEnabled()) {
1785 log.trace("Update for switch which has no entry in switch " +
1786 "list (dpid={}), a delete action.", (String)key);
1787 }
1788 }
1789 }
1790
1791 for (IOFSwitch sw : updated_switches) {
1792 // Set SWITCH_IS_CORE_SWITCH to it's inverse value
1793 if (sw.hasAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH)) {
1794 sw.removeAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH);
1795 if (log.isTraceEnabled()) {
1796 log.trace("SWITCH_IS_CORE_SWITCH set to False for {}", sw);
1797 }
1798 updates.add(new LDUpdate(sw.getId(), SwitchType.BASIC_SWITCH,
1799 UpdateOperation.SWITCH_UPDATED));
1800 }
1801 else {
1802 sw.setAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH, new Boolean(true));
1803 if (log.isTraceEnabled()) {
1804 log.trace("SWITCH_IS_CORE_SWITCH set to True for {}", sw);
1805 }
1806 updates.add(new LDUpdate(sw.getId(), SwitchType.CORE_SWITCH,
1807 UpdateOperation.SWITCH_UPDATED));
1808 }
1809 }
1810 }
1811
1812 @Override
1813 public void rowsDeleted(String tableName, Set<Object> rowKeys) {
1814 // Ignore delete events, the switch delete will do the right thing on it's own
1815 }
1816
1817 // IFloodlightModule classes
1818
1819 @Override
1820 public Collection<Class<? extends IFloodlightService>> getModuleServices() {
1821 Collection<Class<? extends IFloodlightService>> l =
1822 new ArrayList<Class<? extends IFloodlightService>>();
1823 l.add(ILinkDiscoveryService.class);
1824 //l.add(ITopologyService.class);
1825 return l;
1826 }
1827
1828 @Override
1829 public Map<Class<? extends IFloodlightService>, IFloodlightService>
1830 getServiceImpls() {
1831 Map<Class<? extends IFloodlightService>,
1832 IFloodlightService> m =
1833 new HashMap<Class<? extends IFloodlightService>,
1834 IFloodlightService>();
1835 // We are the class that implements the service
1836 m.put(ILinkDiscoveryService.class, this);
1837 return m;
1838 }
1839
1840 @Override
1841 public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
1842 Collection<Class<? extends IFloodlightService>> l =
1843 new ArrayList<Class<? extends IFloodlightService>>();
1844 l.add(IFloodlightProviderService.class);
1845 l.add(IStorageSourceService.class);
1846 l.add(IThreadPoolService.class);
1847 l.add(IRestApiService.class);
1848 return l;
1849 }
1850
1851 @Override
1852 public void init(FloodlightModuleContext context)
1853 throws FloodlightModuleException {
1854 floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
1855 storageSource = context.getServiceImpl(IStorageSourceService.class);
1856 threadPool = context.getServiceImpl(IThreadPoolService.class);
1857 restApi = context.getServiceImpl(IRestApiService.class);
1858
1859 // Set the autoportfast feature to false.
1860 this.autoPortFastFeature = false;
1861
1862 // We create this here because there is no ordering guarantee
1863 this.linkDiscoveryAware = new ArrayList<ILinkDiscoveryListener>();
1864 this.lock = new ReentrantReadWriteLock();
1865 this.updates = new LinkedBlockingQueue<LDUpdate>();
1866 this.links = new HashMap<Link, LinkInfo>();
1867 this.portLinks = new HashMap<NodePortTuple, Set<Link>>();
1868 this.suppressLinkDiscovery =
1869 Collections.synchronizedSet(new HashSet<NodePortTuple>());
1870 this.portBroadcastDomainLinks = new HashMap<NodePortTuple, Set<Link>>();
1871 this.switchLinks = new HashMap<Long, Set<Link>>();
1872 this.quarantineQueue = new LinkedBlockingQueue<NodePortTuple>();
1873 this.maintenanceQueue = new LinkedBlockingQueue<NodePortTuple>();
Umesh Krishnaswamyc56a8cc2013-01-24 21:47:51 -08001874 this.remoteSwitches = new HashMap<Long, IOFSwitch>();
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001875
1876 this.evHistTopologySwitch =
1877 new EventHistory<EventHistoryTopologySwitch>("Topology: Switch");
1878 this.evHistTopologyLink =
1879 new EventHistory<EventHistoryTopologyLink>("Topology: Link");
1880 this.evHistTopologyCluster =
1881 new EventHistory<EventHistoryTopologyCluster>("Topology: Cluster");
1882 }
1883
1884 @Override
1885 @LogMessageDocs({
1886 @LogMessageDoc(level="ERROR",
1887 message="No storage source found.",
1888 explanation="Storage source was not initialized; cannot initialize " +
1889 "link discovery.",
1890 recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
1891 @LogMessageDoc(level="ERROR",
1892 message="Error in installing listener for " +
1893 "switch config table {table}",
1894 explanation="Failed to install storage notification for the " +
1895 "switch config table",
1896 recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
1897 @LogMessageDoc(level="ERROR",
1898 message="No storage source found.",
1899 explanation="Storage source was not initialized; cannot initialize " +
1900 "link discovery.",
1901 recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
1902 @LogMessageDoc(level="ERROR",
1903 message="Exception in LLDP send timer.",
1904 explanation="An unknown error occured while sending LLDP " +
1905 "messages to switches.",
1906 recommendation=LogMessageDoc.CHECK_SWITCH)
1907 })
1908 public void startUp(FloodlightModuleContext context) {
1909 // Create our storage tables
1910 if (storageSource == null) {
1911 log.error("No storage source found.");
1912 return;
1913 }
1914
1915 storageSource.createTable(LINK_TABLE_NAME, null);
1916 storageSource.setTablePrimaryKeyName(LINK_TABLE_NAME, LINK_ID);
1917 storageSource.deleteMatchingRows(LINK_TABLE_NAME, null);
1918 // Register for storage updates for the switch table
1919 try {
1920 storageSource.addListener(SWITCH_CONFIG_TABLE_NAME, this);
1921 } catch (StorageException ex) {
1922 log.error("Error in installing listener for " +
1923 "switch table {}", SWITCH_CONFIG_TABLE_NAME);
1924 }
Pankaj Berdec125e622013-01-25 06:39:39 -08001925
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001926 ScheduledExecutorService ses = threadPool.getScheduledExecutor();
1927
1928 // To be started by the first switch connection
1929 discoveryTask = new SingletonTask(ses, new Runnable() {
1930 @Override
1931 public void run() {
1932 try {
1933 discoverLinks();
1934 } catch (StorageException e) {
1935 log.error("Storage exception in LLDP send timer; " +
1936 "terminating process", e);
1937 floodlightProvider.terminate();
1938 } catch (Exception e) {
1939 log.error("Exception in LLDP send timer.", e);
1940 } finally {
1941 if (!shuttingDown) {
1942 // null role implies HA mode is not enabled.
1943 Role role = floodlightProvider.getRole();
1944 if (role == null || role == Role.MASTER) {
1945 log.trace("Rescheduling discovery task as role = {}", role);
1946 discoveryTask.reschedule(DISCOVERY_TASK_INTERVAL,
1947 TimeUnit.SECONDS);
1948 } else {
1949 log.trace("Stopped LLDP rescheduling due to role = {}.", role);
1950 }
1951 }
1952 }
1953 }
1954 });
1955
1956 // null role implies HA mode is not enabled.
1957 Role role = floodlightProvider.getRole();
1958 if (role == null || role == Role.MASTER) {
1959 log.trace("Setup: Rescheduling discovery task. role = {}", role);
1960 discoveryTask.reschedule(DISCOVERY_TASK_INTERVAL, TimeUnit.SECONDS);
1961 } else {
1962 log.trace("Setup: Not scheduling LLDP as role = {}.", role);
1963 }
1964
1965 // Setup the BDDP task. It is invoked whenever switch port tuples
1966 // are added to the quarantine list.
1967 bddpTask = new SingletonTask(ses, new QuarantineWorker());
1968 bddpTask.reschedule(BDDP_TASK_INTERVAL, TimeUnit.MILLISECONDS);
1969
1970 updatesThread = new Thread(new Runnable () {
1971 @Override
1972 public void run() {
1973 while (true) {
1974 try {
1975 doUpdatesThread();
1976 } catch (InterruptedException e) {
1977 return;
1978 }
1979 }
1980 }}, "Topology Updates");
1981 updatesThread.start();
1982
1983
1984
1985 // Register for the OpenFlow messages we want to receive
1986 floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
1987 floodlightProvider.addOFMessageListener(OFType.PORT_STATUS, this);
1988 // Register for switch updates
1989 floodlightProvider.addOFSwitchListener(this);
1990 floodlightProvider.addHAListener(this);
1991 floodlightProvider.addInfoProvider("summary", this);
1992 if (restApi != null)
1993 restApi.addRestletRoutable(new LinkDiscoveryWebRoutable());
1994 setControllerTLV();
1995 }
1996
1997 // ****************************************************
1998 // Topology Manager's Event History members and methods
1999 // ****************************************************
2000
2001 // Topology Manager event history
2002 public EventHistory<EventHistoryTopologySwitch> evHistTopologySwitch;
2003 public EventHistory<EventHistoryTopologyLink> evHistTopologyLink;
2004 public EventHistory<EventHistoryTopologyCluster> evHistTopologyCluster;
2005 public EventHistoryTopologySwitch evTopoSwitch;
2006 public EventHistoryTopologyLink evTopoLink;
2007 public EventHistoryTopologyCluster evTopoCluster;
2008
2009 // Switch Added/Deleted
2010 private void evHistTopoSwitch(IOFSwitch sw, EvAction actn, String reason) {
2011 if (evTopoSwitch == null) {
2012 evTopoSwitch = new EventHistoryTopologySwitch();
2013 }
2014 evTopoSwitch.dpid = sw.getId();
2015 if ((sw.getChannel() != null) &&
2016 (SocketAddress.class.isInstance(
2017 sw.getChannel().getRemoteAddress()))) {
2018 evTopoSwitch.ipv4Addr =
2019 IPv4.toIPv4Address(((InetSocketAddress)(sw.getChannel().
2020 getRemoteAddress())).getAddress().getAddress());
2021 evTopoSwitch.l4Port =
2022 ((InetSocketAddress)(sw.getChannel().
2023 getRemoteAddress())).getPort();
2024 } else {
2025 evTopoSwitch.ipv4Addr = 0;
2026 evTopoSwitch.l4Port = 0;
2027 }
2028 evTopoSwitch.reason = reason;
2029 evTopoSwitch = evHistTopologySwitch.put(evTopoSwitch, actn);
2030 }
2031
2032 private void evHistTopoLink(long srcDpid, long dstDpid, short srcPort,
2033 short dstPort, int srcPortState, int dstPortState,
2034 ILinkDiscovery.LinkType linkType,
2035 EvAction actn, String reason) {
2036 if (evTopoLink == null) {
2037 evTopoLink = new EventHistoryTopologyLink();
2038 }
2039 evTopoLink.srcSwDpid = srcDpid;
2040 evTopoLink.dstSwDpid = dstDpid;
2041 evTopoLink.srcSwport = srcPort & 0xffff;
2042 evTopoLink.dstSwport = dstPort & 0xffff;
2043 evTopoLink.srcPortState = srcPortState;
2044 evTopoLink.dstPortState = dstPortState;
2045 evTopoLink.reason = reason;
2046 switch (linkType) {
2047 case DIRECT_LINK:
2048 evTopoLink.linkType = "DIRECT_LINK";
2049 break;
2050 case MULTIHOP_LINK:
2051 evTopoLink.linkType = "MULTIHOP_LINK";
2052 break;
2053 case TUNNEL:
2054 evTopoLink.linkType = "TUNNEL";
2055 break;
2056 case INVALID_LINK:
2057 default:
2058 evTopoLink.linkType = "Unknown";
2059 break;
2060 }
2061 evTopoLink = evHistTopologyLink.put(evTopoLink, actn);
2062 }
2063
2064 public void evHistTopoCluster(long dpid, long clusterIdOld,
2065 long clusterIdNew, EvAction action, String reason) {
2066 if (evTopoCluster == null) {
2067 evTopoCluster = new EventHistoryTopologyCluster();
2068 }
2069 evTopoCluster.dpid = dpid;
2070 evTopoCluster.clusterIdOld = clusterIdOld;
2071 evTopoCluster.clusterIdNew = clusterIdNew;
2072 evTopoCluster.reason = reason;
2073 evTopoCluster = evHistTopologyCluster.put(evTopoCluster, action);
2074 }
2075
2076 @Override
2077 public Map<String, Object> getInfo(String type) {
2078 if (!"summary".equals(type)) return null;
2079
2080 Map<String, Object> info = new HashMap<String, Object>();
2081
2082 int num_links = 0;
2083 for (Set<Link> links : switchLinks.values())
2084 num_links += links.size();
2085 info.put("# inter-switch links", num_links / 2);
2086
2087 return info;
2088 }
2089
2090 // IHARoleListener
2091 @Override
2092 public void roleChanged(Role oldRole, Role newRole) {
2093 switch(newRole) {
2094 case MASTER:
2095 if (oldRole == Role.SLAVE) {
2096 if (log.isTraceEnabled()) {
2097 log.trace("Sending LLDPs " +
2098 "to HA change from SLAVE->MASTER");
2099 }
2100 clearAllLinks();
2101 log.debug("Role Change to Master: Rescheduling discovery task.");
2102 discoveryTask.reschedule(1, TimeUnit.MICROSECONDS);
2103 }
2104 break;
2105 case SLAVE:
2106 if (log.isTraceEnabled()) {
2107 log.trace("Clearing links due to " +
2108 "HA change to SLAVE");
2109 }
2110 switchLinks.clear();
2111 links.clear();
2112 portLinks.clear();
2113 portBroadcastDomainLinks.clear();
2114 discoverOnAllPorts();
2115 break;
2116 default:
2117 break;
2118 }
2119 }
2120
2121 @Override
2122 public void controllerNodeIPsChanged(
2123 Map<String, String> curControllerNodeIPs,
2124 Map<String, String> addedControllerNodeIPs,
2125 Map<String, String> removedControllerNodeIPs) {
2126 // ignore
2127 }
2128
2129 public boolean isAutoPortFastFeature() {
2130 return autoPortFastFeature;
2131 }
2132
2133 public void setAutoPortFastFeature(boolean autoPortFastFeature) {
2134 this.autoPortFastFeature = autoPortFastFeature;
2135 }
2136}