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