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