blob: 6d7c90121dbf64643f8ebf9330cf282c8c61fcf0 [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;
Umesh Krishnaswamy68c118c2013-01-25 11:07:09 -0800183 protected final int LINK_TIMEOUT = 5; // decreased timeout as part of LLDP process from 35 secs
184 protected final int LLDP_TO_ALL_INTERVAL = 2 ; //decreased from 15 seconds.
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800185 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.
Umesh Krishnaswamy68c118c2013-01-25 11:07:09 -0800189 protected final int LLDP_TO_KNOWN_INTERVAL= 2; // LLDP frequency for known links from 20 secs
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800190
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
Umesh Krishnaswamy68c118c2013-01-25 11:07:09 -0800547 if (remotesw.getPort(port) == null) {
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800548 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);
Umesh Krishnaswamy82dcd982013-02-01 15:36:15 -0800554 log.debug("addRemoteSwitch(): added fake remote port {} to sw {}", remoteport, remotesw.getId());
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800555 }
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;
Ubuntu9cbb4ca2013-02-07 17:19:59 +0000972 return handleLldp((LLDP) bsn.getPayload(), sw, pi, false, cntx);
973 //return Command.STOP;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800974 } else if (eth.getEtherType() == Ethernet.TYPE_LLDP) {
975 return handleLldp((LLDP) eth.getPayload(), sw, pi, true, cntx);
976 } else if (eth.getEtherType() < 1500) {
977 long destMac = eth.getDestinationMAC().toLong();
978 if ((destMac & LINK_LOCAL_MASK) == LINK_LOCAL_VALUE){
979 if (log.isTraceEnabled()) {
980 log.trace("Ignoring packet addressed to 802.1D/Q " +
981 "reserved address.");
982 }
983 return Command.STOP;
984 }
985 }
986
987 // If packet-in is from a quarantine port, stop processing.
988 NodePortTuple npt = new NodePortTuple(sw, pi.getInPort());
989 if (quarantineQueue.contains(npt)) return Command.STOP;
990
991 return Command.CONTINUE;
992 }
993
994 protected UpdateOperation getUpdateOperation(int srcPortState,
995 int dstPortState) {
996 boolean added =
997 (((srcPortState &
998 OFPortState.OFPPS_STP_MASK.getValue()) !=
999 OFPortState.OFPPS_STP_BLOCK.getValue()) &&
1000 ((dstPortState &
1001 OFPortState.OFPPS_STP_MASK.getValue()) !=
1002 OFPortState.OFPPS_STP_BLOCK.getValue()));
1003
1004 if (added) return UpdateOperation.LINK_UPDATED;
1005 return UpdateOperation.LINK_REMOVED;
1006 }
1007
1008
1009
1010 protected UpdateOperation getUpdateOperation(int srcPortState) {
1011 boolean portUp = ((srcPortState &
1012 OFPortState.OFPPS_STP_MASK.getValue()) !=
1013 OFPortState.OFPPS_STP_BLOCK.getValue());
1014
1015 if (portUp) return UpdateOperation.PORT_UP;
1016 else return UpdateOperation.PORT_DOWN;
1017 }
1018
1019 protected boolean addOrUpdateLink(Link lt, LinkInfo newInfo) {
1020
1021 NodePortTuple srcNpt, dstNpt;
1022 boolean linkChanged = false;
1023
1024 lock.writeLock().lock();
1025 try {
1026 // put the new info. if an old info exists, it will be returned.
1027 LinkInfo oldInfo = links.put(lt, newInfo);
1028 if (oldInfo != null &&
1029 oldInfo.getFirstSeenTime() < newInfo.getFirstSeenTime())
1030 newInfo.setFirstSeenTime(oldInfo.getFirstSeenTime());
1031
1032 if (log.isTraceEnabled()) {
1033 log.trace("addOrUpdateLink: {} {}",
1034 lt,
1035 (newInfo.getMulticastValidTime()!=null) ? "multicast" : "unicast");
1036 }
1037
1038 UpdateOperation updateOperation = null;
1039 linkChanged = false;
1040
1041 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1042 dstNpt = new NodePortTuple(lt.getDst(), lt.getDstPort());
1043
1044 if (oldInfo == null) {
1045 // index it by switch source
1046 if (!switchLinks.containsKey(lt.getSrc()))
1047 switchLinks.put(lt.getSrc(), new HashSet<Link>());
1048 switchLinks.get(lt.getSrc()).add(lt);
1049
1050 // index it by switch dest
1051 if (!switchLinks.containsKey(lt.getDst()))
1052 switchLinks.put(lt.getDst(), new HashSet<Link>());
1053 switchLinks.get(lt.getDst()).add(lt);
1054
1055 // index both ends by switch:port
1056 if (!portLinks.containsKey(srcNpt))
1057 portLinks.put(srcNpt, new HashSet<Link>());
1058 portLinks.get(srcNpt).add(lt);
1059
1060 if (!portLinks.containsKey(dstNpt))
1061 portLinks.put(dstNpt, new HashSet<Link>());
1062 portLinks.get(dstNpt).add(lt);
1063
1064 // Add to portNOFLinks if the unicast valid time is null
1065 if (newInfo.getUnicastValidTime() == null)
1066 addLinkToBroadcastDomain(lt);
1067
1068 writeLinkToStorage(lt, newInfo);
Umesh Krishnaswamy2b9d5642013-01-04 11:00:27 -08001069
1070 // Write link to network map
1071 linkStore.update(lt, newInfo, DM_OPERATION.INSERT);
1072
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001073 updateOperation = UpdateOperation.LINK_UPDATED;
1074 linkChanged = true;
1075
1076 // Add to event history
1077 evHistTopoLink(lt.getSrc(),
1078 lt.getDst(),
1079 lt.getSrcPort(),
1080 lt.getDstPort(),
1081 newInfo.getSrcPortState(), newInfo.getDstPortState(),
1082 getLinkType(lt, newInfo),
1083 EvAction.LINK_ADDED, "LLDP Recvd");
1084 } else {
1085 // Since the link info is already there, we need to
1086 // update the right fields.
1087 if (newInfo.getUnicastValidTime() == null) {
1088 // This is due to a multicast LLDP, so copy the old unicast
1089 // value.
1090 if (oldInfo.getUnicastValidTime() != null) {
1091 newInfo.setUnicastValidTime(oldInfo.getUnicastValidTime());
1092 }
1093 } else if (newInfo.getMulticastValidTime() == null) {
1094 // This is due to a unicast LLDP, so copy the old multicast
1095 // value.
1096 if (oldInfo.getMulticastValidTime() != null) {
1097 newInfo.setMulticastValidTime(oldInfo.getMulticastValidTime());
1098 }
1099 }
1100
1101 Long oldTime = oldInfo.getUnicastValidTime();
1102 Long newTime = newInfo.getUnicastValidTime();
1103 // the link has changed its state between openflow and non-openflow
1104 // if the unicastValidTimes are null or not null
1105 if (oldTime != null & newTime == null) {
1106 // openflow -> non-openflow transition
1107 // we need to add the link tuple to the portNOFLinks
1108 addLinkToBroadcastDomain(lt);
1109 linkChanged = true;
1110 } else if (oldTime == null & newTime != null) {
1111 // non-openflow -> openflow transition
1112 // we need to remove the link from the portNOFLinks
1113 removeLinkFromBroadcastDomain(lt);
1114 linkChanged = true;
1115 }
1116
1117 // Only update the port states if they've changed
1118 if (newInfo.getSrcPortState().intValue() !=
1119 oldInfo.getSrcPortState().intValue() ||
1120 newInfo.getDstPortState().intValue() !=
1121 oldInfo.getDstPortState().intValue())
1122 linkChanged = true;
1123
1124 // Write changes to storage. This will always write the updated
1125 // valid time, plus the port states if they've changed (i.e. if
1126 // they weren't set to null in the previous block of code.
1127 writeLinkToStorage(lt, newInfo);
1128
Umesh Krishnaswamy2b9d5642013-01-04 11:00:27 -08001129 // Write link to network map
1130 linkStore.update(lt, newInfo, DM_OPERATION.UPDATE);
1131
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001132 if (linkChanged) {
1133 updateOperation = getUpdateOperation(newInfo.getSrcPortState(),
1134 newInfo.getDstPortState());
1135 if (log.isTraceEnabled()) {
1136 log.trace("Updated link {}", lt);
1137 }
1138 // Add to event history
1139 evHistTopoLink(lt.getSrc(),
1140 lt.getDst(),
1141 lt.getSrcPort(),
1142 lt.getDstPort(),
1143 newInfo.getSrcPortState(), newInfo.getDstPortState(),
1144 getLinkType(lt, newInfo),
1145 EvAction.LINK_PORT_STATE_UPDATED,
1146 "LLDP Recvd");
1147 }
1148 }
1149
1150 if (linkChanged) {
1151 // find out if the link was added or removed here.
1152 updates.add(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
1153 lt.getDst(), lt.getDstPort(),
1154 getLinkType(lt, newInfo),
1155 updateOperation));
1156 }
1157 } finally {
1158 lock.writeLock().unlock();
1159 }
1160
1161 return linkChanged;
1162 }
1163
1164 public Map<Long, Set<Link>> getSwitchLinks() {
1165 return this.switchLinks;
1166 }
1167
1168 /**
1169 * Removes links from memory and storage.
1170 * @param links The List of @LinkTuple to delete.
1171 */
1172 protected void deleteLinks(List<Link> links, String reason) {
1173 NodePortTuple srcNpt, dstNpt;
1174
1175 lock.writeLock().lock();
1176 try {
1177 for (Link lt : links) {
1178 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1179 dstNpt =new NodePortTuple(lt.getDst(), lt.getDstPort());
1180
1181 switchLinks.get(lt.getSrc()).remove(lt);
1182 switchLinks.get(lt.getDst()).remove(lt);
1183 if (switchLinks.containsKey(lt.getSrc()) &&
1184 switchLinks.get(lt.getSrc()).isEmpty())
1185 this.switchLinks.remove(lt.getSrc());
1186 if (this.switchLinks.containsKey(lt.getDst()) &&
1187 this.switchLinks.get(lt.getDst()).isEmpty())
1188 this.switchLinks.remove(lt.getDst());
1189
1190 if (this.portLinks.get(srcNpt) != null) {
1191 this.portLinks.get(srcNpt).remove(lt);
1192 if (this.portLinks.get(srcNpt).isEmpty())
1193 this.portLinks.remove(srcNpt);
1194 }
1195 if (this.portLinks.get(dstNpt) != null) {
1196 this.portLinks.get(dstNpt).remove(lt);
1197 if (this.portLinks.get(dstNpt).isEmpty())
1198 this.portLinks.remove(dstNpt);
1199 }
1200
1201 LinkInfo info = this.links.remove(lt);
1202 updates.add(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
1203 lt.getDst(), lt.getDstPort(),
1204 getLinkType(lt, info),
1205 UpdateOperation.LINK_REMOVED));
1206
1207 // Update Event History
1208 evHistTopoLink(lt.getSrc(),
1209 lt.getDst(),
1210 lt.getSrcPort(),
1211 lt.getDstPort(),
1212 0, 0, // Port states
1213 ILinkDiscovery.LinkType.INVALID_LINK,
1214 EvAction.LINK_DELETED, reason);
1215
1216 // remove link from storage.
1217 removeLinkFromStorage(lt);
1218
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -08001219 // remote link from network map
Umesh Krishnaswamy2b9d5642013-01-04 11:00:27 -08001220 linkStore.update(lt, DM_OPERATION.DELETE);
1221
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001222 // TODO Whenever link is removed, it has to checked if
1223 // the switchports must be added to quarantine.
1224
1225 if (log.isTraceEnabled()) {
1226 log.trace("Deleted link {}", lt);
1227 }
1228 }
1229 } finally {
1230 lock.writeLock().unlock();
1231 }
1232 }
1233
1234 /**
1235 * Handles an OFPortStatus message from a switch. We will add or
1236 * delete LinkTupes as well re-compute the topology if needed.
1237 * @param sw The IOFSwitch that sent the port status message
1238 * @param ps The OFPortStatus message
1239 * @return The Command to continue or stop after we process this message
1240 */
1241 protected Command handlePortStatus(long sw, OFPortStatus ps) {
1242
1243 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
1244 if (iofSwitch == null) return Command.CONTINUE;
1245
1246 if (log.isTraceEnabled()) {
1247 log.trace("handlePortStatus: Switch {} port #{} reason {}; " +
1248 "config is {} state is {}",
1249 new Object[] {iofSwitch.getStringId(),
1250 ps.getDesc().getPortNumber(),
1251 ps.getReason(),
1252 ps.getDesc().getConfig(),
1253 ps.getDesc().getState()});
1254 }
1255
1256 short port = ps.getDesc().getPortNumber();
1257 NodePortTuple npt = new NodePortTuple(sw, port);
1258 boolean linkDeleted = false;
1259 boolean linkInfoChanged = false;
1260
1261 lock.writeLock().lock();
1262 try {
1263 // if ps is a delete, or a modify where the port is down or
1264 // configured down
1265 if ((byte)OFPortReason.OFPPR_DELETE.ordinal() == ps.getReason() ||
1266 ((byte)OFPortReason.OFPPR_MODIFY.ordinal() ==
1267 ps.getReason() && !portEnabled(ps.getDesc()))) {
1268 deleteLinksOnPort(npt, "Port Status Changed");
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -08001269 //swStore.deletePort(HexString.toHexString(npt.getNodeId()), npt.getPortId());
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001270 LDUpdate update = new LDUpdate(sw, port, UpdateOperation.PORT_DOWN);
1271 updates.add(update);
1272 linkDeleted = true;
1273 }
1274 else if (ps.getReason() ==
1275 (byte)OFPortReason.OFPPR_MODIFY.ordinal()) {
1276 // If ps is a port modification and the port state has changed
1277 // that affects links in the topology
1278
1279 if (this.portLinks.containsKey(npt)) {
1280 for (Link lt: this.portLinks.get(npt)) {
1281 LinkInfo linkInfo = links.get(lt);
1282 assert(linkInfo != null);
1283 Integer updatedSrcPortState = null;
1284 Integer updatedDstPortState = null;
1285 if (lt.getSrc() == npt.getNodeId() &&
1286 lt.getSrcPort() == npt.getPortId() &&
1287 (linkInfo.getSrcPortState() !=
1288 ps.getDesc().getState())) {
1289 updatedSrcPortState = ps.getDesc().getState();
1290 linkInfo.setSrcPortState(updatedSrcPortState);
1291 }
1292 if (lt.getDst() == npt.getNodeId() &&
1293 lt.getDstPort() == npt.getPortId() &&
1294 (linkInfo.getDstPortState() !=
1295 ps.getDesc().getState())) {
1296 updatedDstPortState = ps.getDesc().getState();
1297 linkInfo.setDstPortState(updatedDstPortState);
1298 }
1299 if ((updatedSrcPortState != null) ||
1300 (updatedDstPortState != null)) {
1301 // The link is already known to link discovery
1302 // manager and the status has changed, therefore
1303 // send an LDUpdate.
1304 UpdateOperation operation =
1305 getUpdateOperation(linkInfo.getSrcPortState(),
1306 linkInfo.getDstPortState());
1307 updates.add(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
1308 lt.getDst(), lt.getDstPort(),
1309 getLinkType(lt, linkInfo),
1310 operation));
1311 writeLinkToStorage(lt, linkInfo);
Umesh Krishnaswamy2b9d5642013-01-04 11:00:27 -08001312
1313 // Write the changed link to the network map
1314 linkStore.update(lt, linkInfo, DM_OPERATION.UPDATE);
1315
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001316 linkInfoChanged = true;
1317 }
1318 }
1319 }
1320
1321 UpdateOperation operation =
1322 getUpdateOperation(ps.getDesc().getState());
1323 updates.add(new LDUpdate(sw, port, operation));
1324 }
1325
1326 if (!linkDeleted && !linkInfoChanged){
1327 if (log.isTraceEnabled()) {
1328 log.trace("handlePortStatus: Switch {} port #{} reason {};"+
1329 " no links to update/remove",
1330 new Object[] {HexString.toHexString(sw),
1331 ps.getDesc().getPortNumber(),
1332 ps.getReason()});
1333 }
1334 }
1335 } finally {
1336 lock.writeLock().unlock();
1337 }
1338
1339 if (!linkDeleted) {
1340 // Send LLDP right away when port state is changed for faster
1341 // cluster-merge. If it is a link delete then there is not need
1342 // to send the LLDPs right away and instead we wait for the LLDPs
1343 // to be sent on the timer as it is normally done
1344 // do it outside the write-lock
1345 // sendLLDPTask.reschedule(1000, TimeUnit.MILLISECONDS);
1346 processNewPort(npt.getNodeId(), npt.getPortId());
1347 }
1348 return Command.CONTINUE;
1349 }
1350
1351 /**
1352 * Process a new port.
1353 * If link discovery is disabled on the port, then do nothing.
1354 * If autoportfast feature is enabled and the port is a fast port, then
1355 * do nothing.
1356 * Otherwise, send LLDP message. Add the port to quarantine.
1357 * @param sw
1358 * @param p
1359 */
1360 private void processNewPort(long sw, short p) {
1361 if (isLinkDiscoverySuppressed(sw, p)) {
1362 // Do nothing as link discovery is suppressed.
1363 }
1364 else if (autoPortFastFeature && isFastPort(sw, p)) {
1365 // Do nothing as the port is a fast port.
1366 }
1367 else {
1368 NodePortTuple npt = new NodePortTuple(sw, p);
1369 discover(sw, p);
1370 // if it is not a fast port, add it to quarantine.
1371 if (!isFastPort(sw, p)) {
1372 addToQuarantineQueue(npt);
1373 } else {
1374 // Add to maintenance queue to ensure that BDDP packets
1375 // are sent out.
1376 addToMaintenanceQueue(npt);
1377 }
1378 }
1379 }
1380
1381 /**
1382 * We send out LLDP messages when a switch is added to discover the topology
1383 * @param sw The IOFSwitch that connected to the controller
1384 */
1385 @Override
1386 public void addedSwitch(IOFSwitch sw) {
1387
1388 if (sw.getEnabledPorts() != null) {
1389 for (Short p : sw.getEnabledPortNumbers()) {
1390 processNewPort(sw.getId(), p);
1391 }
1392 }
1393 // Update event history
1394 evHistTopoSwitch(sw, EvAction.SWITCH_CONNECTED, "None");
1395 LDUpdate update = new LDUpdate(sw.getId(), null,
1396 UpdateOperation.SWITCH_UPDATED);
1397 updates.add(update);
1398 }
1399
1400 /**
1401 * When a switch disconnects we remove any links from our map and notify.
1402 * @param The id of the switch
1403 */
1404 @Override
1405 public void removedSwitch(IOFSwitch iofSwitch) {
1406 // Update event history
1407 long sw = iofSwitch.getId();
1408 evHistTopoSwitch(iofSwitch, EvAction.SWITCH_DISCONNECTED, "None");
1409 List<Link> eraseList = new ArrayList<Link>();
1410 lock.writeLock().lock();
1411 try {
1412 if (switchLinks.containsKey(sw)) {
1413 if (log.isTraceEnabled()) {
1414 log.trace("Handle switchRemoved. Switch {}; removing links {}",
1415 HexString.toHexString(sw), switchLinks.get(sw));
1416 }
1417 // add all tuples with an endpoint on this switch to erase list
1418 eraseList.addAll(switchLinks.get(sw));
1419 deleteLinks(eraseList, "Switch Removed");
1420
1421 // Send a switch removed update
1422 LDUpdate update = new LDUpdate(sw, null, UpdateOperation.SWITCH_REMOVED);
1423 updates.add(update);
1424 }
1425 } finally {
1426 lock.writeLock().unlock();
1427 }
1428 }
1429
1430 /**
1431 * We don't react the port changed notifications here. we listen for
1432 * OFPortStatus messages directly. Might consider using this notifier
1433 * instead
1434 */
1435 @Override
1436 public void switchPortChanged(Long switchId) {
1437 // no-op
1438 }
1439
1440 /**
1441 * Delete links incident on a given switch port.
1442 * @param npt
1443 * @param reason
1444 */
1445 protected void deleteLinksOnPort(NodePortTuple npt, String reason) {
1446 List<Link> eraseList = new ArrayList<Link>();
1447 if (this.portLinks.containsKey(npt)) {
1448 if (log.isTraceEnabled()) {
1449 log.trace("handlePortStatus: Switch {} port #{} " +
1450 "removing links {}",
1451 new Object[] {HexString.toHexString(npt.getNodeId()),
1452 npt.getPortId(),
1453 this.portLinks.get(npt)});
1454 }
1455 eraseList.addAll(this.portLinks.get(npt));
1456 deleteLinks(eraseList, reason);
1457 }
1458 }
1459
1460 /**
1461 * Iterates through the list of links and deletes if the
1462 * last discovery message reception time exceeds timeout values.
1463 */
1464 protected void timeoutLinks() {
1465 List<Link> eraseList = new ArrayList<Link>();
1466 Long curTime = System.currentTimeMillis();
1467 boolean linkChanged = false;
1468
1469 // reentrant required here because deleteLink also write locks
1470 lock.writeLock().lock();
1471 try {
1472 Iterator<Entry<Link, LinkInfo>> it =
1473 this.links.entrySet().iterator();
1474 while (it.hasNext()) {
1475 Entry<Link, LinkInfo> entry = it.next();
1476 Link lt = entry.getKey();
1477 LinkInfo info = entry.getValue();
1478
1479 // Timeout the unicast and multicast LLDP valid times
1480 // independently.
1481 if ((info.getUnicastValidTime() != null) &&
1482 (info.getUnicastValidTime() + (this.LINK_TIMEOUT * 1000) < curTime)){
1483 info.setUnicastValidTime(null);
1484
1485 if (info.getMulticastValidTime() != null)
1486 addLinkToBroadcastDomain(lt);
1487 // Note that even if mTime becomes null later on,
1488 // the link would be deleted, which would trigger updateClusters().
1489 linkChanged = true;
1490 }
1491 if ((info.getMulticastValidTime()!= null) &&
1492 (info.getMulticastValidTime()+ (this.LINK_TIMEOUT * 1000) < curTime)) {
1493 info.setMulticastValidTime(null);
1494 // if uTime is not null, then link will remain as openflow
1495 // link. If uTime is null, it will be deleted. So, we
1496 // don't care about linkChanged flag here.
1497 removeLinkFromBroadcastDomain(lt);
1498 linkChanged = true;
1499 }
1500 // Add to the erase list only if the unicast
1501 // time is null.
1502 if (info.getUnicastValidTime() == null &&
1503 info.getMulticastValidTime() == null){
1504 eraseList.add(entry.getKey());
1505 } else if (linkChanged) {
1506 UpdateOperation operation;
1507 operation = getUpdateOperation(info.getSrcPortState(),
1508 info.getDstPortState());
1509 updates.add(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
1510 lt.getDst(), lt.getDstPort(),
1511 getLinkType(lt, info),
1512 operation));
1513 }
1514 }
1515
1516 // if any link was deleted or any link was changed.
1517 if ((eraseList.size() > 0) || linkChanged) {
1518 deleteLinks(eraseList, "LLDP timeout");
1519 }
1520 } finally {
1521 lock.writeLock().unlock();
1522 }
1523 }
1524
1525 private boolean portEnabled(OFPhysicalPort port) {
1526 if (port == null)
1527 return false;
1528 if ((OFPortConfig.OFPPC_PORT_DOWN.getValue() & port.getConfig()) > 0)
1529 return false;
1530 if ((OFPortState.OFPPS_LINK_DOWN.getValue() & port.getState()) > 0)
1531 return false;
1532 // Port STP state doesn't work with multiple VLANs, so ignore it for now
1533 // if ((port.getState() & OFPortState.OFPPS_STP_MASK.getValue()) == OFPortState.OFPPS_STP_BLOCK.getValue())
1534 // return false;
1535 return true;
1536 }
1537
1538 public Map<NodePortTuple, Set<Link>> getPortBroadcastDomainLinks() {
1539 return portBroadcastDomainLinks;
1540 }
1541
1542 @Override
1543 public Map<Link, LinkInfo> getLinks() {
1544 lock.readLock().lock();
1545 Map<Link, LinkInfo> result;
1546 try {
1547 result = new HashMap<Link, LinkInfo>(links);
1548 } finally {
1549 lock.readLock().unlock();
1550 }
1551 return result;
1552 }
1553
1554 protected void addLinkToBroadcastDomain(Link lt) {
1555
1556 NodePortTuple srcNpt, dstNpt;
1557 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1558 dstNpt = new NodePortTuple(lt.getDst(), lt.getDstPort());
1559
1560 if (!portBroadcastDomainLinks.containsKey(lt.getSrc()))
1561 portBroadcastDomainLinks.put(srcNpt, new HashSet<Link>());
1562 portBroadcastDomainLinks.get(srcNpt).add(lt);
1563
1564 if (!portBroadcastDomainLinks.containsKey(lt.getDst()))
1565 portBroadcastDomainLinks.put(dstNpt, new HashSet<Link>());
1566 portBroadcastDomainLinks.get(dstNpt).add(lt);
1567 }
1568
1569 protected void removeLinkFromBroadcastDomain(Link lt) {
1570
1571 NodePortTuple srcNpt, dstNpt;
1572 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1573 dstNpt = new NodePortTuple(lt.getDst(), lt.getDstPort());
1574
1575 if (portBroadcastDomainLinks.containsKey(srcNpt)) {
1576 portBroadcastDomainLinks.get(srcNpt).remove(lt);
1577 if (portBroadcastDomainLinks.get(srcNpt).isEmpty())
1578 portBroadcastDomainLinks.remove(srcNpt);
1579 }
1580
1581 if (portBroadcastDomainLinks.containsKey(dstNpt)) {
1582 portBroadcastDomainLinks.get(dstNpt).remove(lt);
1583 if (portBroadcastDomainLinks.get(dstNpt).isEmpty())
1584 portBroadcastDomainLinks.remove(dstNpt);
1585 }
1586 }
1587
1588 // STORAGE METHODS
1589 /**
1590 * Deletes all links from storage
1591 */
1592 void clearAllLinks() {
1593 storageSource.deleteRowsAsync(LINK_TABLE_NAME, null);
1594 }
1595
1596 /**
1597 * Gets the storage key for a LinkTuple
1598 * @param lt The LinkTuple to get
1599 * @return The storage key as a String
1600 */
1601 private String getLinkId(Link lt) {
1602 return HexString.toHexString(lt.getSrc()) +
1603 "-" + lt.getSrcPort() + "-" +
1604 HexString.toHexString(lt.getDst())+
1605 "-" + lt.getDstPort();
1606 }
1607
1608 /**
1609 * Writes a LinkTuple and corresponding LinkInfo to storage
1610 * @param lt The LinkTuple to write
1611 * @param linkInfo The LinkInfo to write
1612 */
1613 protected void writeLinkToStorage(Link lt, LinkInfo linkInfo) {
1614 LinkType type = getLinkType(lt, linkInfo);
1615
1616 // Write only direct links. Do not write links to external
1617 // L2 network.
1618 // if (type != LinkType.DIRECT_LINK && type != LinkType.TUNNEL) {
1619 // return;
1620 // }
1621
1622 Map<String, Object> rowValues = new HashMap<String, Object>();
1623 String id = getLinkId(lt);
1624 rowValues.put(LINK_ID, id);
1625 rowValues.put(LINK_VALID_TIME, linkInfo.getUnicastValidTime());
1626 String srcDpid = HexString.toHexString(lt.getSrc());
1627 rowValues.put(LINK_SRC_SWITCH, srcDpid);
1628 rowValues.put(LINK_SRC_PORT, lt.getSrcPort());
1629
1630 if (type == LinkType.DIRECT_LINK)
1631 rowValues.put(LINK_TYPE, "internal");
1632 else if (type == LinkType.MULTIHOP_LINK)
1633 rowValues.put(LINK_TYPE, "external");
1634 else if (type == LinkType.TUNNEL)
1635 rowValues.put(LINK_TYPE, "tunnel");
1636 else rowValues.put(LINK_TYPE, "invalid");
1637
1638 if (linkInfo.linkStpBlocked()) {
1639 if (log.isTraceEnabled()) {
1640 log.trace("writeLink, link {}, info {}, srcPortState Blocked",
1641 lt, linkInfo);
1642 }
1643 rowValues.put(LINK_SRC_PORT_STATE,
1644 OFPhysicalPort.OFPortState.OFPPS_STP_BLOCK.getValue());
1645 } else {
1646 if (log.isTraceEnabled()) {
1647 log.trace("writeLink, link {}, info {}, srcPortState {}",
1648 new Object[]{ lt, linkInfo, linkInfo.getSrcPortState() });
1649 }
1650 rowValues.put(LINK_SRC_PORT_STATE, linkInfo.getSrcPortState());
1651 }
1652 String dstDpid = HexString.toHexString(lt.getDst());
1653 rowValues.put(LINK_DST_SWITCH, dstDpid);
1654 rowValues.put(LINK_DST_PORT, lt.getDstPort());
1655 if (linkInfo.linkStpBlocked()) {
1656 if (log.isTraceEnabled()) {
1657 log.trace("writeLink, link {}, info {}, dstPortState Blocked",
1658 lt, linkInfo);
1659 }
1660 rowValues.put(LINK_DST_PORT_STATE,
1661 OFPhysicalPort.OFPortState.OFPPS_STP_BLOCK.getValue());
1662 } else {
1663 if (log.isTraceEnabled()) {
1664 log.trace("writeLink, link {}, info {}, dstPortState {}",
1665 new Object[]{ lt, linkInfo, linkInfo.getDstPortState() });
1666 }
1667 rowValues.put(LINK_DST_PORT_STATE, linkInfo.getDstPortState());
1668 }
1669 storageSource.updateRowAsync(LINK_TABLE_NAME, rowValues);
1670 }
1671
1672 public Long readLinkValidTime(Link lt) {
1673 // FIXME: We're not currently using this right now, but if we start
1674 // to use this again, we probably shouldn't use it in its current
1675 // form, because it's doing synchronous storage calls. Depending
1676 // on the context this may still be OK, but if it's being called
1677 // on the packet in processing thread it should be reworked to
1678 // use asynchronous storage calls.
1679 Long validTime = null;
1680 IResultSet resultSet = null;
1681 try {
1682 String[] columns = { LINK_VALID_TIME };
1683 String id = getLinkId(lt);
1684 resultSet = storageSource.executeQuery(LINK_TABLE_NAME, columns,
1685 new OperatorPredicate(LINK_ID, OperatorPredicate.Operator.EQ, id), null);
1686 if (resultSet.next())
1687 validTime = resultSet.getLong(LINK_VALID_TIME);
1688 }
1689 finally {
1690 if (resultSet != null)
1691 resultSet.close();
1692 }
1693 return validTime;
1694 }
1695
1696 /**
1697 * Removes a link from storage using an asynchronous call.
1698 * @param lt The LinkTuple to delete.
1699 */
1700 protected void removeLinkFromStorage(Link lt) {
1701 String id = getLinkId(lt);
1702 storageSource.deleteRowAsync(LINK_TABLE_NAME, id);
1703 }
1704
1705 @Override
1706 public void addListener(ILinkDiscoveryListener listener) {
1707 linkDiscoveryAware.add(listener);
1708 }
1709
1710 /**
1711 * Register a link discovery aware component
1712 * @param linkDiscoveryAwareComponent
1713 */
1714 public void addLinkDiscoveryAware(ILinkDiscoveryListener linkDiscoveryAwareComponent) {
1715 // TODO make this a copy on write set or lock it somehow
1716 this.linkDiscoveryAware.add(linkDiscoveryAwareComponent);
1717 }
1718
1719 /**
1720 * Deregister a link discovery aware component
1721 * @param linkDiscoveryAwareComponent
1722 */
1723 public void removeLinkDiscoveryAware(ILinkDiscoveryListener linkDiscoveryAwareComponent) {
1724 // TODO make this a copy on write set or lock it somehow
1725 this.linkDiscoveryAware.remove(linkDiscoveryAwareComponent);
1726 }
1727
1728 /**
1729 * Sets the IStorageSource to use for ITology
1730 * @param storageSource the storage source to use
1731 */
1732 public void setStorageSource(IStorageSourceService storageSource) {
1733 this.storageSource = storageSource;
1734 }
1735
1736 /**
1737 * Gets the storage source for this ITopology
1738 * @return The IStorageSource ITopology is writing to
1739 */
1740 public IStorageSourceService getStorageSource() {
1741 return storageSource;
1742 }
1743
1744 @Override
1745 public boolean isCallbackOrderingPrereq(OFType type, String name) {
1746 return false;
1747 }
1748
1749 @Override
1750 public boolean isCallbackOrderingPostreq(OFType type, String name) {
1751 return false;
1752 }
1753
1754 @Override
1755 public void rowsModified(String tableName, Set<Object> rowKeys) {
1756 Map<Long, IOFSwitch> switches = floodlightProvider.getSwitches();
1757 ArrayList<IOFSwitch> updated_switches = new ArrayList<IOFSwitch>();
1758 for(Object key: rowKeys) {
1759 Long swId = new Long(HexString.toLong((String)key));
1760 if (switches.containsKey(swId)) {
1761 IOFSwitch sw = switches.get(swId);
1762 boolean curr_status = sw.hasAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH);
1763 boolean new_status = false;
1764 IResultSet resultSet = null;
1765
1766 try {
1767 resultSet = storageSource.getRow(tableName, key);
1768 for (Iterator<IResultSet> it = resultSet.iterator(); it.hasNext();) {
1769 // In case of multiple rows, use the status in last row?
1770 Map<String, Object> row = it.next().getRow();
1771 if (row.containsKey(SWITCH_CONFIG_CORE_SWITCH)) {
1772 new_status = ((String)row.get(SWITCH_CONFIG_CORE_SWITCH)).equals("true");
1773 }
1774 }
1775 }
1776 finally {
1777 if (resultSet != null)
1778 resultSet.close();
1779 }
1780
1781 if (curr_status != new_status) {
1782 updated_switches.add(sw);
1783 }
1784 } else {
1785 if (log.isTraceEnabled()) {
1786 log.trace("Update for switch which has no entry in switch " +
1787 "list (dpid={}), a delete action.", (String)key);
1788 }
1789 }
1790 }
1791
1792 for (IOFSwitch sw : updated_switches) {
1793 // Set SWITCH_IS_CORE_SWITCH to it's inverse value
1794 if (sw.hasAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH)) {
1795 sw.removeAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH);
1796 if (log.isTraceEnabled()) {
1797 log.trace("SWITCH_IS_CORE_SWITCH set to False for {}", sw);
1798 }
1799 updates.add(new LDUpdate(sw.getId(), SwitchType.BASIC_SWITCH,
1800 UpdateOperation.SWITCH_UPDATED));
1801 }
1802 else {
1803 sw.setAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH, new Boolean(true));
1804 if (log.isTraceEnabled()) {
1805 log.trace("SWITCH_IS_CORE_SWITCH set to True for {}", sw);
1806 }
1807 updates.add(new LDUpdate(sw.getId(), SwitchType.CORE_SWITCH,
1808 UpdateOperation.SWITCH_UPDATED));
1809 }
1810 }
1811 }
1812
1813 @Override
1814 public void rowsDeleted(String tableName, Set<Object> rowKeys) {
1815 // Ignore delete events, the switch delete will do the right thing on it's own
1816 }
1817
1818 // IFloodlightModule classes
1819
1820 @Override
1821 public Collection<Class<? extends IFloodlightService>> getModuleServices() {
1822 Collection<Class<? extends IFloodlightService>> l =
1823 new ArrayList<Class<? extends IFloodlightService>>();
1824 l.add(ILinkDiscoveryService.class);
1825 //l.add(ITopologyService.class);
1826 return l;
1827 }
1828
1829 @Override
1830 public Map<Class<? extends IFloodlightService>, IFloodlightService>
1831 getServiceImpls() {
1832 Map<Class<? extends IFloodlightService>,
1833 IFloodlightService> m =
1834 new HashMap<Class<? extends IFloodlightService>,
1835 IFloodlightService>();
1836 // We are the class that implements the service
1837 m.put(ILinkDiscoveryService.class, this);
1838 return m;
1839 }
1840
1841 @Override
1842 public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
1843 Collection<Class<? extends IFloodlightService>> l =
1844 new ArrayList<Class<? extends IFloodlightService>>();
1845 l.add(IFloodlightProviderService.class);
1846 l.add(IStorageSourceService.class);
1847 l.add(IThreadPoolService.class);
1848 l.add(IRestApiService.class);
1849 return l;
1850 }
1851
1852 @Override
1853 public void init(FloodlightModuleContext context)
1854 throws FloodlightModuleException {
1855 floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
1856 storageSource = context.getServiceImpl(IStorageSourceService.class);
1857 threadPool = context.getServiceImpl(IThreadPoolService.class);
1858 restApi = context.getServiceImpl(IRestApiService.class);
1859
1860 // Set the autoportfast feature to false.
1861 this.autoPortFastFeature = false;
1862
1863 // We create this here because there is no ordering guarantee
1864 this.linkDiscoveryAware = new ArrayList<ILinkDiscoveryListener>();
1865 this.lock = new ReentrantReadWriteLock();
1866 this.updates = new LinkedBlockingQueue<LDUpdate>();
1867 this.links = new HashMap<Link, LinkInfo>();
1868 this.portLinks = new HashMap<NodePortTuple, Set<Link>>();
1869 this.suppressLinkDiscovery =
1870 Collections.synchronizedSet(new HashSet<NodePortTuple>());
1871 this.portBroadcastDomainLinks = new HashMap<NodePortTuple, Set<Link>>();
1872 this.switchLinks = new HashMap<Long, Set<Link>>();
1873 this.quarantineQueue = new LinkedBlockingQueue<NodePortTuple>();
1874 this.maintenanceQueue = new LinkedBlockingQueue<NodePortTuple>();
Umesh Krishnaswamyc56a8cc2013-01-24 21:47:51 -08001875 this.remoteSwitches = new HashMap<Long, IOFSwitch>();
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001876
1877 this.evHistTopologySwitch =
1878 new EventHistory<EventHistoryTopologySwitch>("Topology: Switch");
1879 this.evHistTopologyLink =
1880 new EventHistory<EventHistoryTopologyLink>("Topology: Link");
1881 this.evHistTopologyCluster =
1882 new EventHistory<EventHistoryTopologyCluster>("Topology: Cluster");
1883 }
1884
1885 @Override
1886 @LogMessageDocs({
1887 @LogMessageDoc(level="ERROR",
1888 message="No storage source found.",
1889 explanation="Storage source was not initialized; cannot initialize " +
1890 "link discovery.",
1891 recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
1892 @LogMessageDoc(level="ERROR",
1893 message="Error in installing listener for " +
1894 "switch config table {table}",
1895 explanation="Failed to install storage notification for the " +
1896 "switch config table",
1897 recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
1898 @LogMessageDoc(level="ERROR",
1899 message="No storage source found.",
1900 explanation="Storage source was not initialized; cannot initialize " +
1901 "link discovery.",
1902 recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
1903 @LogMessageDoc(level="ERROR",
1904 message="Exception in LLDP send timer.",
1905 explanation="An unknown error occured while sending LLDP " +
1906 "messages to switches.",
1907 recommendation=LogMessageDoc.CHECK_SWITCH)
1908 })
1909 public void startUp(FloodlightModuleContext context) {
1910 // Create our storage tables
1911 if (storageSource == null) {
1912 log.error("No storage source found.");
1913 return;
1914 }
1915
1916 storageSource.createTable(LINK_TABLE_NAME, null);
1917 storageSource.setTablePrimaryKeyName(LINK_TABLE_NAME, LINK_ID);
1918 storageSource.deleteMatchingRows(LINK_TABLE_NAME, null);
1919 // Register for storage updates for the switch table
1920 try {
1921 storageSource.addListener(SWITCH_CONFIG_TABLE_NAME, this);
1922 } catch (StorageException ex) {
1923 log.error("Error in installing listener for " +
1924 "switch table {}", SWITCH_CONFIG_TABLE_NAME);
1925 }
Pankaj Berdec125e622013-01-25 06:39:39 -08001926
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001927 ScheduledExecutorService ses = threadPool.getScheduledExecutor();
1928
1929 // To be started by the first switch connection
1930 discoveryTask = new SingletonTask(ses, new Runnable() {
1931 @Override
1932 public void run() {
1933 try {
1934 discoverLinks();
1935 } catch (StorageException e) {
1936 log.error("Storage exception in LLDP send timer; " +
1937 "terminating process", e);
1938 floodlightProvider.terminate();
1939 } catch (Exception e) {
1940 log.error("Exception in LLDP send timer.", e);
1941 } finally {
1942 if (!shuttingDown) {
1943 // null role implies HA mode is not enabled.
1944 Role role = floodlightProvider.getRole();
1945 if (role == null || role == Role.MASTER) {
1946 log.trace("Rescheduling discovery task as role = {}", role);
1947 discoveryTask.reschedule(DISCOVERY_TASK_INTERVAL,
1948 TimeUnit.SECONDS);
1949 } else {
1950 log.trace("Stopped LLDP rescheduling due to role = {}.", role);
1951 }
1952 }
1953 }
1954 }
1955 });
1956
1957 // null role implies HA mode is not enabled.
1958 Role role = floodlightProvider.getRole();
1959 if (role == null || role == Role.MASTER) {
1960 log.trace("Setup: Rescheduling discovery task. role = {}", role);
1961 discoveryTask.reschedule(DISCOVERY_TASK_INTERVAL, TimeUnit.SECONDS);
1962 } else {
1963 log.trace("Setup: Not scheduling LLDP as role = {}.", role);
1964 }
1965
1966 // Setup the BDDP task. It is invoked whenever switch port tuples
1967 // are added to the quarantine list.
1968 bddpTask = new SingletonTask(ses, new QuarantineWorker());
1969 bddpTask.reschedule(BDDP_TASK_INTERVAL, TimeUnit.MILLISECONDS);
1970
1971 updatesThread = new Thread(new Runnable () {
1972 @Override
1973 public void run() {
1974 while (true) {
1975 try {
1976 doUpdatesThread();
1977 } catch (InterruptedException e) {
1978 return;
1979 }
1980 }
1981 }}, "Topology Updates");
1982 updatesThread.start();
1983
1984
1985
1986 // Register for the OpenFlow messages we want to receive
1987 floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
1988 floodlightProvider.addOFMessageListener(OFType.PORT_STATUS, this);
1989 // Register for switch updates
1990 floodlightProvider.addOFSwitchListener(this);
1991 floodlightProvider.addHAListener(this);
1992 floodlightProvider.addInfoProvider("summary", this);
1993 if (restApi != null)
1994 restApi.addRestletRoutable(new LinkDiscoveryWebRoutable());
1995 setControllerTLV();
1996 }
1997
1998 // ****************************************************
1999 // Topology Manager's Event History members and methods
2000 // ****************************************************
2001
2002 // Topology Manager event history
2003 public EventHistory<EventHistoryTopologySwitch> evHistTopologySwitch;
2004 public EventHistory<EventHistoryTopologyLink> evHistTopologyLink;
2005 public EventHistory<EventHistoryTopologyCluster> evHistTopologyCluster;
2006 public EventHistoryTopologySwitch evTopoSwitch;
2007 public EventHistoryTopologyLink evTopoLink;
2008 public EventHistoryTopologyCluster evTopoCluster;
2009
2010 // Switch Added/Deleted
2011 private void evHistTopoSwitch(IOFSwitch sw, EvAction actn, String reason) {
2012 if (evTopoSwitch == null) {
2013 evTopoSwitch = new EventHistoryTopologySwitch();
2014 }
2015 evTopoSwitch.dpid = sw.getId();
2016 if ((sw.getChannel() != null) &&
2017 (SocketAddress.class.isInstance(
2018 sw.getChannel().getRemoteAddress()))) {
2019 evTopoSwitch.ipv4Addr =
2020 IPv4.toIPv4Address(((InetSocketAddress)(sw.getChannel().
2021 getRemoteAddress())).getAddress().getAddress());
2022 evTopoSwitch.l4Port =
2023 ((InetSocketAddress)(sw.getChannel().
2024 getRemoteAddress())).getPort();
2025 } else {
2026 evTopoSwitch.ipv4Addr = 0;
2027 evTopoSwitch.l4Port = 0;
2028 }
2029 evTopoSwitch.reason = reason;
2030 evTopoSwitch = evHistTopologySwitch.put(evTopoSwitch, actn);
2031 }
2032
2033 private void evHistTopoLink(long srcDpid, long dstDpid, short srcPort,
2034 short dstPort, int srcPortState, int dstPortState,
2035 ILinkDiscovery.LinkType linkType,
2036 EvAction actn, String reason) {
2037 if (evTopoLink == null) {
2038 evTopoLink = new EventHistoryTopologyLink();
2039 }
2040 evTopoLink.srcSwDpid = srcDpid;
2041 evTopoLink.dstSwDpid = dstDpid;
2042 evTopoLink.srcSwport = srcPort & 0xffff;
2043 evTopoLink.dstSwport = dstPort & 0xffff;
2044 evTopoLink.srcPortState = srcPortState;
2045 evTopoLink.dstPortState = dstPortState;
2046 evTopoLink.reason = reason;
2047 switch (linkType) {
2048 case DIRECT_LINK:
2049 evTopoLink.linkType = "DIRECT_LINK";
2050 break;
2051 case MULTIHOP_LINK:
2052 evTopoLink.linkType = "MULTIHOP_LINK";
2053 break;
2054 case TUNNEL:
2055 evTopoLink.linkType = "TUNNEL";
2056 break;
2057 case INVALID_LINK:
2058 default:
2059 evTopoLink.linkType = "Unknown";
2060 break;
2061 }
2062 evTopoLink = evHistTopologyLink.put(evTopoLink, actn);
2063 }
2064
2065 public void evHistTopoCluster(long dpid, long clusterIdOld,
2066 long clusterIdNew, EvAction action, String reason) {
2067 if (evTopoCluster == null) {
2068 evTopoCluster = new EventHistoryTopologyCluster();
2069 }
2070 evTopoCluster.dpid = dpid;
2071 evTopoCluster.clusterIdOld = clusterIdOld;
2072 evTopoCluster.clusterIdNew = clusterIdNew;
2073 evTopoCluster.reason = reason;
2074 evTopoCluster = evHistTopologyCluster.put(evTopoCluster, action);
2075 }
2076
2077 @Override
2078 public Map<String, Object> getInfo(String type) {
2079 if (!"summary".equals(type)) return null;
2080
2081 Map<String, Object> info = new HashMap<String, Object>();
2082
2083 int num_links = 0;
2084 for (Set<Link> links : switchLinks.values())
2085 num_links += links.size();
2086 info.put("# inter-switch links", num_links / 2);
2087
2088 return info;
2089 }
2090
2091 // IHARoleListener
2092 @Override
2093 public void roleChanged(Role oldRole, Role newRole) {
2094 switch(newRole) {
2095 case MASTER:
2096 if (oldRole == Role.SLAVE) {
2097 if (log.isTraceEnabled()) {
2098 log.trace("Sending LLDPs " +
2099 "to HA change from SLAVE->MASTER");
2100 }
2101 clearAllLinks();
2102 log.debug("Role Change to Master: Rescheduling discovery task.");
2103 discoveryTask.reschedule(1, TimeUnit.MICROSECONDS);
2104 }
2105 break;
2106 case SLAVE:
2107 if (log.isTraceEnabled()) {
2108 log.trace("Clearing links due to " +
2109 "HA change to SLAVE");
2110 }
2111 switchLinks.clear();
2112 links.clear();
2113 portLinks.clear();
2114 portBroadcastDomainLinks.clear();
2115 discoverOnAllPorts();
2116 break;
2117 default:
2118 break;
2119 }
2120 }
2121
2122 @Override
2123 public void controllerNodeIPsChanged(
2124 Map<String, String> curControllerNodeIPs,
2125 Map<String, String> addedControllerNodeIPs,
2126 Map<String, String> removedControllerNodeIPs) {
2127 // ignore
2128 }
2129
2130 public boolean isAutoPortFastFeature() {
2131 return autoPortFastFeature;
2132 }
2133
2134 public void setAutoPortFastFeature(boolean autoPortFastFeature) {
2135 this.autoPortFastFeature = autoPortFastFeature;
2136 }
2137}