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