blob: 7716781d9e069581e3acd5bfa733dffd4d4dcef1 [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
HIGUCHI Yutaa56fbde2013-06-17 14:26:05 -070018package net.onrc.onos.ofcontroller.linkdiscovery.internal;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080019
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;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080036import java.util.concurrent.LinkedBlockingQueue;
37import java.util.concurrent.ScheduledExecutorService;
38import java.util.concurrent.TimeUnit;
39import java.util.concurrent.locks.ReentrantReadWriteLock;
40
41import net.floodlightcontroller.core.FloodlightContext;
42import net.floodlightcontroller.core.IFloodlightProviderService;
43import net.floodlightcontroller.core.IFloodlightProviderService.Role;
44import net.floodlightcontroller.core.IHAListener;
45import net.floodlightcontroller.core.IInfoProvider;
46import net.floodlightcontroller.core.IOFMessageListener;
47import net.floodlightcontroller.core.IOFSwitch;
48import net.floodlightcontroller.core.IOFSwitchListener;
49import net.floodlightcontroller.core.annotations.LogMessageCategory;
50import net.floodlightcontroller.core.annotations.LogMessageDoc;
51import net.floodlightcontroller.core.annotations.LogMessageDocs;
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -070052import net.floodlightcontroller.core.internal.OFSwitchImpl;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080053import net.floodlightcontroller.core.module.FloodlightModuleContext;
54import net.floodlightcontroller.core.module.FloodlightModuleException;
55import net.floodlightcontroller.core.module.IFloodlightModule;
56import net.floodlightcontroller.core.module.IFloodlightService;
57import net.floodlightcontroller.core.util.SingletonTask;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080058import net.floodlightcontroller.packet.BSN;
59import net.floodlightcontroller.packet.Ethernet;
60import net.floodlightcontroller.packet.IPv4;
61import net.floodlightcontroller.packet.LLDP;
62import net.floodlightcontroller.packet.LLDPTLV;
63import net.floodlightcontroller.restserver.IRestApiService;
64import net.floodlightcontroller.routing.Link;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080065import net.floodlightcontroller.threadpool.IThreadPoolService;
66import net.floodlightcontroller.topology.NodePortTuple;
67import net.floodlightcontroller.util.EventHistory;
68import net.floodlightcontroller.util.EventHistory.EvAction;
HIGUCHI Yuta7677a6f2013-06-14 14:13:35 -070069import net.onrc.onos.ofcontroller.core.IOnosRemoteSwitch;
HIGUCHI Yutaa56fbde2013-06-17 14:26:05 -070070import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery;
Jonathan Hart2fa28062013-11-25 20:16:28 -080071import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery.LDUpdate;
72import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery.UpdateOperation;
HIGUCHI Yutaa56fbde2013-06-17 14:26:05 -070073import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscoveryListener;
74import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscoveryService;
75import net.onrc.onos.ofcontroller.linkdiscovery.LinkInfo;
HIGUCHI Yutaa56fbde2013-06-17 14:26:05 -070076import net.onrc.onos.ofcontroller.linkdiscovery.web.LinkDiscoveryWebRoutable;
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -070077import net.onrc.onos.registry.controller.IControllerRegistryService;
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -070078
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080079import org.openflow.protocol.OFMessage;
80import org.openflow.protocol.OFPacketIn;
81import org.openflow.protocol.OFPacketOut;
82import org.openflow.protocol.OFPhysicalPort;
83import org.openflow.protocol.OFPhysicalPort.OFPortConfig;
84import org.openflow.protocol.OFPhysicalPort.OFPortState;
85import org.openflow.protocol.OFPort;
86import org.openflow.protocol.OFPortStatus;
87import org.openflow.protocol.OFPortStatus.OFPortReason;
88import org.openflow.protocol.OFType;
89import org.openflow.protocol.action.OFAction;
90import org.openflow.protocol.action.OFActionOutput;
91import org.openflow.util.HexString;
92import org.slf4j.Logger;
93import org.slf4j.LoggerFactory;
94
95/**
96 * This class sends out LLDP messages containing the sending switch's datapath
97 * id as well as the outgoing port number. Received LLrescDP messages that
98 * match a known switch cause a new LinkTuple to be created according to the
99 * invariant rules listed below. This new LinkTuple is also passed to routing
100 * if it exists to trigger updates.
101 *
102 * This class also handles removing links that are associated to switch ports
103 * that go down, and switches that are disconnected.
104 *
105 * Invariants:
106 * -portLinks and switchLinks will not contain empty Sets outside of
107 * critical sections
108 * -portLinks contains LinkTuples where one of the src or dst
109 * SwitchPortTuple matches the map key
110 * -switchLinks contains LinkTuples where one of the src or dst
111 * SwitchPortTuple's id matches the switch id
112 * -Each LinkTuple will be indexed into switchLinks for both
113 * src.id and dst.id, and portLinks for each src and dst
114 * -The updates queue is only added to from within a held write lock
115 */
116@LogMessageCategory("Network Topology")
117public class LinkDiscoveryManager
118implements IOFMessageListener, IOFSwitchListener,
Jonathan Hart2fa28062013-11-25 20:16:28 -0800119ILinkDiscoveryService,
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800120IFloodlightModule, IInfoProvider, IHAListener {
Pankaj Berdedc73bb12013-08-14 13:46:38 -0700121 protected IFloodlightProviderService controller;
Yuta HIGUCHI6ac8d182013-10-22 15:24:56 -0700122 protected final static Logger log = LoggerFactory.getLogger(LinkDiscoveryManager.class);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800123
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800124 protected IFloodlightProviderService floodlightProvider;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800125 protected IThreadPoolService threadPool;
126 protected IRestApiService restApi;
HIGUCHI Yuta30d03302013-06-14 13:47:36 -0700127 // Registry Service for ONOS
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -0700128 protected IControllerRegistryService registryService;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800129
HIGUCHI Yutae0515e52013-06-14 13:00:40 -0700130
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800131 // LLDP and BDDP fields
132 private static final byte[] LLDP_STANDARD_DST_MAC_STRING =
133 HexString.fromHexString("01:80:c2:00:00:0e");
134 private static final long LINK_LOCAL_MASK = 0xfffffffffff0L;
135 private static final long LINK_LOCAL_VALUE = 0x0180c2000000L;
136
137 // BigSwitch OUI is 5C:16:C7, so 5D:16:C7 is the multicast version
Masayoshi Kobayashi71137362013-07-12 15:54:52 -0700138 // private static final String LLDP_BSN_DST_MAC_STRING = "5d:16:c7:00:00:01";
139 private static final String LLDP_BSN_DST_MAC_STRING = "ff:ff:ff:ff:ff:ff";
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800140
141
142 // Direction TLVs are used to indicate if the LLDPs were sent
143 // periodically or in response to a recieved LLDP
144 private static final byte TLV_DIRECTION_TYPE = 0x73;
145 private static final short TLV_DIRECTION_LENGTH = 1; // 1 byte
146 private static final byte TLV_DIRECTION_VALUE_FORWARD[] = {0x01};
147 private static final byte TLV_DIRECTION_VALUE_REVERSE[] = {0x02};
148 private static final LLDPTLV forwardTLV
149 = new LLDPTLV().
150 setType((byte)TLV_DIRECTION_TYPE).
151 setLength((short)TLV_DIRECTION_LENGTH).
152 setValue(TLV_DIRECTION_VALUE_FORWARD);
153
154 private static final LLDPTLV reverseTLV
155 = new LLDPTLV().
156 setType((byte)TLV_DIRECTION_TYPE).
157 setLength((short)TLV_DIRECTION_LENGTH).
158 setValue(TLV_DIRECTION_VALUE_REVERSE);
159
160 // Link discovery task details.
161 protected SingletonTask discoveryTask;
162 protected final int DISCOVERY_TASK_INTERVAL = 1;
Umesh Krishnaswamy77601202013-04-03 21:46:01 -0700163 protected final int LINK_TIMEOUT = 35; // original 35 secs, aggressive 5 secs
164 protected final int LLDP_TO_ALL_INTERVAL = 15 ; //original 15 seconds, aggressive 2 secs.
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800165 protected long lldpClock = 0;
166 // This value is intentionally kept higher than LLDP_TO_ALL_INTERVAL.
167 // If we want to identify link failures faster, we could decrease this
168 // value to a small number, say 1 or 2 sec.
Umesh Krishnaswamy77601202013-04-03 21:46:01 -0700169 protected final int LLDP_TO_KNOWN_INTERVAL= 20; // LLDP frequency for known links
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800170
171 protected LLDPTLV controllerTLV;
172 protected ReentrantReadWriteLock lock;
173 int lldpTimeCount = 0;
HIGUCHI Yutae0515e52013-06-14 13:00:40 -0700174
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800175 /**
176 * Flag to indicate if automatic port fast is enabled or not.
177 * Default is set to false -- Initialized in the init method as well.
178 */
179 boolean autoPortFastFeature = false;
180
181 /**
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800182 * Map of remote switches that are not connected to this controller. This
HIGUCHI Yuta30d03302013-06-14 13:47:36 -0700183 * is used to learn remote switches in a distributed controller ONOS.
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800184 */
HIGUCHI Yuta7677a6f2013-06-14 14:13:35 -0700185 protected Map<Long, IOnosRemoteSwitch> remoteSwitches;
HIGUCHI Yuta3d96f652013-06-17 12:07:48 -0700186
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800187 /**
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800188 * Map from link to the most recent time it was verified functioning
189 */
190 protected Map<Link, LinkInfo> links;
191
192 /**
193 * Map from switch id to a set of all links with it as an endpoint
194 */
195 protected Map<Long, Set<Link>> switchLinks;
196
197 /**
198 * Map from a id:port to the set of links containing it as an endpoint
199 */
200 protected Map<NodePortTuple, Set<Link>> portLinks;
201
202 /**
203 * Set of link tuples over which multicast LLDPs are received
204 * and unicast LLDPs are not received.
205 */
206 protected Map<NodePortTuple, Set<Link>> portBroadcastDomainLinks;
207
208 protected volatile boolean shuttingDown = false;
209
210 /* topology aware components are called in the order they were added to the
211 * the array */
212 protected ArrayList<ILinkDiscoveryListener> linkDiscoveryAware;
Pankaj Berdedc73bb12013-08-14 13:46:38 -0700213
214 protected class LinkUpdate extends LDUpdate {
215
216 public LinkUpdate(LDUpdate old) {
217 super(old);
218 }
219 @LogMessageDoc(level="ERROR",
220 message="Error in link discovery updates loop",
221 explanation="An unknown error occured while dispatching " +
222 "link update notifications",
223 recommendation=LogMessageDoc.GENERIC_ACTION)
224 @Override
225 public void dispatch() {
Jonathan Hartb0904bf2013-11-26 14:41:11 -0800226 if (linkDiscoveryAware != null) {
227 if (log.isTraceEnabled()) {
228 log.trace("Dispatching link discovery update {} {} {} {} {} for {}",
229 new Object[]{this.getOperation(),
230 HexString.toHexString(this.getSrc()), this.getSrcPort(),
231 HexString.toHexString(this.getDst()), this.getDstPort(),
232 linkDiscoveryAware});
233 }
234 try {
235 for (ILinkDiscoveryListener lda : linkDiscoveryAware) { // order maintained
236 lda.linkDiscoveryUpdate(this);
237 }
238 }
239 catch (Exception e) {
240 log.error("Error in link discovery updates loop", e);
241 }
242 }
Pankaj Berdedc73bb12013-08-14 13:46:38 -0700243 }
Pankaj Berdedc73bb12013-08-14 13:46:38 -0700244 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800245
246 /**
247 * List of ports through which LLDP/BDDPs are not sent.
248 */
249 protected Set<NodePortTuple> suppressLinkDiscovery;
250
251 /** A list of ports that are quarantined for discovering links through
252 * them. Data traffic from these ports are not allowed until the ports
253 * are released from quarantine.
254 */
255 protected LinkedBlockingQueue<NodePortTuple> quarantineQueue;
256 protected LinkedBlockingQueue<NodePortTuple> maintenanceQueue;
257 /**
258 * Quarantine task
259 */
260 protected SingletonTask bddpTask;
261 protected final int BDDP_TASK_INTERVAL = 100; // 100 ms.
262 protected final int BDDP_TASK_SIZE = 5; // # of ports per iteration
263
264 /**
265 * Map of broadcast domain ports and the last time a BDDP was either
266 * sent or received on that port.
267 */
268 protected Map<NodePortTuple, Long> broadcastDomainPortTimeMap;
269
270 /**
271 * Get the LLDP sending period in seconds.
272 * @return LLDP sending period in seconds.
273 */
274 public int getLldpFrequency() {
275 return LLDP_TO_KNOWN_INTERVAL;
276 }
277
278 /**
279 * Get the LLDP timeout value in seconds
280 * @return LLDP timeout value in seconds
281 */
282 public int getLldpTimeout() {
283 return LINK_TIMEOUT;
284 }
285
286 public Map<NodePortTuple, Set<Link>> getPortLinks() {
287 return portLinks;
288 }
289
290 public Set<NodePortTuple> getSuppressLLDPsInfo() {
291 return suppressLinkDiscovery;
292 }
293
294 /**
295 * Add a switch port to the suppressed LLDP list.
296 * Remove any known links on the switch port.
297 */
298 public void AddToSuppressLLDPs(long sw, short port)
299 {
300 NodePortTuple npt = new NodePortTuple(sw, port);
301 this.suppressLinkDiscovery.add(npt);
302 deleteLinksOnPort(npt, "LLDP suppressed.");
303 }
304
305 /**
306 * Remove a switch port from the suppressed LLDP list.
307 * Discover links on that switchport.
308 */
309 public void RemoveFromSuppressLLDPs(long sw, short port)
310 {
311 NodePortTuple npt = new NodePortTuple(sw, port);
312 this.suppressLinkDiscovery.remove(npt);
313 discover(npt);
314 }
315
316 public boolean isShuttingDown() {
317 return shuttingDown;
318 }
319
320 public boolean isFastPort(long sw, short port) {
321 return false;
322 }
323
324 public ILinkDiscovery.LinkType getLinkType(Link lt, LinkInfo info) {
325 if (info.getUnicastValidTime() != null) {
326 return ILinkDiscovery.LinkType.DIRECT_LINK;
327 } else if (info.getMulticastValidTime() != null) {
328 return ILinkDiscovery.LinkType.MULTIHOP_LINK;
329 }
330 return ILinkDiscovery.LinkType.INVALID_LINK;
331 }
332
Pankaj Berdedc73bb12013-08-14 13:46:38 -0700333
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800334 private boolean isLinkDiscoverySuppressed(long sw, short portNumber) {
335 return this.suppressLinkDiscovery.contains(new NodePortTuple(sw, portNumber));
336 }
337
338 protected void discoverLinks() {
339
340 // timeout known links.
341 timeoutLinks();
342
343 //increment LLDP clock
344 lldpClock = (lldpClock + 1)% LLDP_TO_ALL_INTERVAL;
345
346 if (lldpClock == 0) {
347 log.debug("Sending LLDP out on all ports.");
348 discoverOnAllPorts();
349 }
350 }
351
352
353 /**
354 * Quarantine Ports.
355 */
356 protected class QuarantineWorker implements Runnable {
357 @Override
358 public void run() {
359 try {
360 processBDDPLists();
361 }
362 catch (Exception e) {
363 log.error("Error in quarantine worker thread", e);
364 } finally {
365 bddpTask.reschedule(BDDP_TASK_INTERVAL,
366 TimeUnit.MILLISECONDS);
367 }
368 }
369 }
370
371 /**
372 * Add a switch port to the quarantine queue. Schedule the
373 * quarantine task if the quarantine queue was empty before adding
374 * this switch port.
375 * @param npt
376 */
377 protected void addToQuarantineQueue(NodePortTuple npt) {
378 if (quarantineQueue.contains(npt) == false)
379 quarantineQueue.add(npt);
380 }
381
382 /**
383 * Remove a switch port from the quarantine queue.
384 */
385 protected void removeFromQuarantineQueue(NodePortTuple npt) {
386 // Remove all occurrences of the node port tuple from the list.
387 while (quarantineQueue.remove(npt));
388 }
389
390 /**
391 * Add a switch port to maintenance queue.
392 * @param npt
393 */
394 protected void addToMaintenanceQueue(NodePortTuple npt) {
395 // TODO We are not checking if the switch port tuple is already
396 // in the maintenance list or not. This will be an issue for
397 // really large number of switch ports in the network.
398 if (maintenanceQueue.contains(npt) == false)
399 maintenanceQueue.add(npt);
400 }
401
402 /**
403 * Remove a switch port from maintenance queue.
404 * @param npt
405 */
406 protected void removeFromMaintenanceQueue(NodePortTuple npt) {
407 // Remove all occurrences of the node port tuple from the queue.
408 while (maintenanceQueue.remove(npt));
409 }
410
411 /**
412 * This method processes the quarantine list in bursts. The task is
413 * at most once per BDDP_TASK_INTERVAL.
414 * One each call, BDDP_TASK_SIZE number of switch ports are processed.
415 * Once the BDDP packets are sent out through the switch ports, the ports
416 * are removed from the quarantine list.
417 */
418
419 protected void processBDDPLists() {
420 int count = 0;
421 Set<NodePortTuple> nptList = new HashSet<NodePortTuple>();
422
423 while(count < BDDP_TASK_SIZE && quarantineQueue.peek() !=null) {
424 NodePortTuple npt;
425 npt = quarantineQueue.remove();
426 sendDiscoveryMessage(npt.getNodeId(), npt.getPortId(), false, false);
427 nptList.add(npt);
428 count++;
429 }
430
431 count = 0;
432 while (count < BDDP_TASK_SIZE && maintenanceQueue.peek() != null) {
433 NodePortTuple npt;
434 npt = maintenanceQueue.remove();
435 sendDiscoveryMessage(npt.getNodeId(), npt.getPortId(), false, false);
436 count++;
437 }
438
439 for(NodePortTuple npt:nptList) {
440 generateSwitchPortStatusUpdate(npt.getNodeId(), npt.getPortId());
441 }
442 }
443
444 public Set<Short> getQuarantinedPorts(long sw) {
445 Set<Short> qPorts = new HashSet<Short>();
446
447 Iterator<NodePortTuple> iter = quarantineQueue.iterator();
448 while (iter.hasNext()) {
449 NodePortTuple npt = iter.next();
450 if (npt.getNodeId() == sw) {
451 qPorts.add(npt.getPortId());
452 }
453 }
454 return qPorts;
455 }
456
457 private void generateSwitchPortStatusUpdate(long sw, short port) {
458 UpdateOperation operation;
459
460 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
461 if (iofSwitch == null) return;
462
463 OFPhysicalPort ofp = iofSwitch.getPort(port);
464 if (ofp == null) return;
465
466 int srcPortState = ofp.getState();
467 boolean portUp = ((srcPortState &
468 OFPortState.OFPPS_STP_MASK.getValue()) !=
469 OFPortState.OFPPS_STP_BLOCK.getValue());
470
471 if (portUp) operation = UpdateOperation.PORT_UP;
472 else operation = UpdateOperation.PORT_DOWN;
473
Pankaj Berdedc73bb12013-08-14 13:46:38 -0700474 LinkUpdate update = new LinkUpdate(new LDUpdate(sw, port, operation));
475
476
477 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800478 }
479
480 /**
481 * Send LLDP on known ports
482 */
483 protected void discoverOnKnownLinkPorts() {
484 // Copy the port set.
485 Set<NodePortTuple> nptSet = new HashSet<NodePortTuple>();
486 nptSet.addAll(portLinks.keySet());
487
488 // Send LLDP from each of them.
489 for(NodePortTuple npt: nptSet) {
490 discover(npt);
491 }
492 }
493
494 protected void discover(NodePortTuple npt) {
495 discover(npt.getNodeId(), npt.getPortId());
496 }
497
498 protected void discover(long sw, short port) {
499 sendDiscoveryMessage(sw, port, true, false);
500 }
501
502 /**
HIGUCHI Yuta30d03302013-06-14 13:47:36 -0700503 * Learn remote switches when running as a distributed controller ONOS
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800504 */
505 protected IOFSwitch addRemoteSwitch(long sw, short port) {
HIGUCHI Yuta7677a6f2013-06-14 14:13:35 -0700506 IOnosRemoteSwitch remotesw = null;
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800507
508 // add a switch if we have not seen it before
Umesh Krishnaswamy4c8e1082013-01-24 23:15:37 -0800509 remotesw = remoteSwitches.get(sw);
Jonathan Harte7231052013-01-25 00:01:14 -0800510
Pankaj Berdec125e622013-01-25 06:39:39 -0800511 if (remotesw == null) {
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800512 remotesw = new OFSwitchImpl();
513 remotesw.setupRemoteSwitch(sw);
514 remoteSwitches.put(remotesw.getId(), remotesw);
515 log.debug("addRemoteSwitch(): added fake remote sw {}", remotesw);
516 }
517
518 // add the port if we have not seen it before
Umesh Krishnaswamy68c118c2013-01-25 11:07:09 -0800519 if (remotesw.getPort(port) == null) {
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800520 OFPhysicalPort remoteport = new OFPhysicalPort();
521 remoteport.setPortNumber(port);
522 remoteport.setName("fake_" + port);
523 remoteport.setConfig(0);
524 remoteport.setState(0);
525 remotesw.setPort(remoteport);
Umesh Krishnaswamy82dcd982013-02-01 15:36:15 -0800526 log.debug("addRemoteSwitch(): added fake remote port {} to sw {}", remoteport, remotesw.getId());
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800527 }
528
529 return remotesw;
530 }
531
532 /**
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800533 * Send link discovery message out of a given switch port.
534 * The discovery message may be a standard LLDP or a modified
535 * LLDP, where the dst mac address is set to :ff.
536 *
537 * TODO: The modified LLDP will updated in the future and may
538 * use a different eth-type.
539 * @param sw
540 * @param port
541 * @param isStandard indicates standard or modified LLDP
542 * @param isReverse indicates whether the LLDP was sent as a response
543 */
544 @LogMessageDoc(level="ERROR",
545 message="Failure sending LLDP out port {port} on switch {switch}",
546 explanation="An I/O error occured while sending LLDP message " +
547 "to the switch.",
548 recommendation=LogMessageDoc.CHECK_SWITCH)
549 protected void sendDiscoveryMessage(long sw, short port,
550 boolean isStandard,
551 boolean isReverse) {
552
553 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
554 if (iofSwitch == null) {
555 return;
556 }
557
558 if (port == OFPort.OFPP_LOCAL.getValue())
559 return;
560
561 OFPhysicalPort ofpPort = iofSwitch.getPort(port);
562
563 if (ofpPort == null) {
564 if (log.isTraceEnabled()) {
565 log.trace("Null physical port. sw={}, port={}", sw, port);
566 }
567 return;
568 }
569
570 if (isLinkDiscoverySuppressed(sw, port)) {
571 /* Dont send LLDPs out of this port as suppressLLDPs set
572 *
573 */
574 return;
575 }
576
577 // For fast ports, do not send forward LLDPs or BDDPs.
578 if (!isReverse && autoPortFastFeature && isFastPort(sw, port))
579 return;
580
581 if (log.isTraceEnabled()) {
582 log.trace("Sending LLDP packet out of swich: {}, port: {}",
583 sw, port);
584 }
585
586 // using "nearest customer bridge" MAC address for broadest possible propagation
587 // through provider and TPMR bridges (see IEEE 802.1AB-2009 and 802.1Q-2011),
588 // in particular the Linux bridge which behaves mostly like a provider bridge
589 byte[] chassisId = new byte[] {4, 0, 0, 0, 0, 0, 0}; // filled in later
590 byte[] portId = new byte[] {2, 0, 0}; // filled in later
591 byte[] ttlValue = new byte[] {0, 0x78};
592 // OpenFlow OUI - 00-26-E1
593 byte[] dpidTLVValue = new byte[] {0x0, 0x26, (byte) 0xe1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
594 LLDPTLV dpidTLV = new LLDPTLV().setType((byte) 127).setLength((short) dpidTLVValue.length).setValue(dpidTLVValue);
595
596 byte[] dpidArray = new byte[8];
597 ByteBuffer dpidBB = ByteBuffer.wrap(dpidArray);
598 ByteBuffer portBB = ByteBuffer.wrap(portId, 1, 2);
599
600 Long dpid = sw;
601 dpidBB.putLong(dpid);
602 // set the ethernet source mac to last 6 bytes of dpid
603 System.arraycopy(dpidArray, 2, ofpPort.getHardwareAddress(), 0, 6);
604 // set the chassis id's value to last 6 bytes of dpid
605 System.arraycopy(dpidArray, 2, chassisId, 1, 6);
606 // set the optional tlv to the full dpid
607 System.arraycopy(dpidArray, 0, dpidTLVValue, 4, 8);
608
609
610 // set the portId to the outgoing port
611 portBB.putShort(port);
612 if (log.isTraceEnabled()) {
613 log.trace("Sending LLDP out of interface: {}/{}",
614 HexString.toHexString(sw), port);
615 }
616
617 LLDP lldp = new LLDP();
618 lldp.setChassisId(new LLDPTLV().setType((byte) 1).setLength((short) chassisId.length).setValue(chassisId));
619 lldp.setPortId(new LLDPTLV().setType((byte) 2).setLength((short) portId.length).setValue(portId));
620 lldp.setTtl(new LLDPTLV().setType((byte) 3).setLength((short) ttlValue.length).setValue(ttlValue));
621 lldp.getOptionalTLVList().add(dpidTLV);
622
623 // Add the controller identifier to the TLV value.
624 lldp.getOptionalTLVList().add(controllerTLV);
625 if (isReverse) {
626 lldp.getOptionalTLVList().add(reverseTLV);
627 }else {
628 lldp.getOptionalTLVList().add(forwardTLV);
629 }
630
631 Ethernet ethernet;
632 if (isStandard) {
633 ethernet = new Ethernet()
634 .setSourceMACAddress(ofpPort.getHardwareAddress())
635 .setDestinationMACAddress(LLDP_STANDARD_DST_MAC_STRING)
636 .setEtherType(Ethernet.TYPE_LLDP);
637 ethernet.setPayload(lldp);
638 } else {
639 BSN bsn = new BSN(BSN.BSN_TYPE_BDDP);
640 bsn.setPayload(lldp);
641
642 ethernet = new Ethernet()
643 .setSourceMACAddress(ofpPort.getHardwareAddress())
644 .setDestinationMACAddress(LLDP_BSN_DST_MAC_STRING)
645 .setEtherType(Ethernet.TYPE_BSN);
646 ethernet.setPayload(bsn);
647 }
648
649
650 // serialize and wrap in a packet out
651 byte[] data = ethernet.serialize();
652 OFPacketOut po = (OFPacketOut) floodlightProvider.getOFMessageFactory().getMessage(OFType.PACKET_OUT);
653 po.setBufferId(OFPacketOut.BUFFER_ID_NONE);
654 po.setInPort(OFPort.OFPP_NONE);
655
656 // set actions
657 List<OFAction> actions = new ArrayList<OFAction>();
658 actions.add(new OFActionOutput(port, (short) 0));
659 po.setActions(actions);
660 po.setActionsLength((short) OFActionOutput.MINIMUM_LENGTH);
661
662 // set data
663 po.setLengthU(OFPacketOut.MINIMUM_LENGTH + po.getActionsLength() + data.length);
664 po.setPacketData(data);
665
666 // send
667 try {
668 iofSwitch.write(po, null);
669 iofSwitch.flush();
670 } catch (IOException e) {
671 log.error("Failure sending LLDP out port {} on switch {}",
672 new Object[]{ port, iofSwitch.getStringId() }, e);
673 }
674
675 }
676
677 /**
678 * Send LLDPs to all switch-ports
679 */
680 protected void discoverOnAllPorts() {
681 if (log.isTraceEnabled()) {
682 log.trace("Sending LLDP packets out of all the enabled ports on switch {}");
683 }
684 Set<Long> switches = floodlightProvider.getSwitches().keySet();
685 // Send standard LLDPs
686 for (long sw: switches) {
687 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
688 if (iofSwitch == null) continue;
689 if (iofSwitch.getEnabledPorts() != null) {
690 for (OFPhysicalPort ofp: iofSwitch.getEnabledPorts()) {
691 if (isLinkDiscoverySuppressed(sw, ofp.getPortNumber()))
692 continue;
693 if (autoPortFastFeature && isFastPort(sw, ofp.getPortNumber()))
694 continue;
695
696 // sends forward LLDP only non-fastports.
697 sendDiscoveryMessage(sw, ofp.getPortNumber(), true, false);
698
699 // If the switch port is not alreayd in the maintenance
700 // queue, add it.
701 NodePortTuple npt = new NodePortTuple(sw, ofp.getPortNumber());
702 addToMaintenanceQueue(npt);
703 }
704 }
705 }
706 }
707
708 protected void setControllerTLV() {
709 //Setting the controllerTLVValue based on current nano time,
710 //controller's IP address, and the network interface object hash
711 //the corresponding IP address.
712
713 final int prime = 7867;
714 InetAddress localIPAddress = null;
715 NetworkInterface localInterface = null;
716
717 byte[] controllerTLVValue = new byte[] {0, 0, 0, 0, 0, 0, 0, 0}; // 8 byte value.
718 ByteBuffer bb = ByteBuffer.allocate(10);
719
720 try{
721 localIPAddress = java.net.InetAddress.getLocalHost();
722 localInterface = NetworkInterface.getByInetAddress(localIPAddress);
723 } catch (Exception e) {
724 e.printStackTrace();
725 }
726
727 long result = System.nanoTime();
728 if (localIPAddress != null)
729 result = result * prime + IPv4.toIPv4Address(localIPAddress.getHostAddress());
730 if (localInterface != null)
731 result = result * prime + localInterface.hashCode();
732 // set the first 4 bits to 0.
733 result = result & (0x0fffffffffffffffL);
734
735 bb.putLong(result);
736
737 bb.rewind();
738 bb.get(controllerTLVValue, 0, 8);
739
740 this.controllerTLV = new LLDPTLV().setType((byte) 0x0c).setLength((short) controllerTLVValue.length).setValue(controllerTLVValue);
741 }
742
743 @Override
744 public String getName() {
745 return "linkdiscovery";
746 }
747
748 @Override
749 public Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
750 switch (msg.getType()) {
751 case PACKET_IN:
752 return this.handlePacketIn(sw.getId(), (OFPacketIn) msg, cntx);
753 case PORT_STATUS:
754 return this.handlePortStatus(sw.getId(), (OFPortStatus) msg);
755 default:
756 break;
757 }
758 return Command.CONTINUE;
759 }
760
761 private Command handleLldp(LLDP lldp, long sw, OFPacketIn pi, boolean isStandard, FloodlightContext cntx) {
762 // If LLDP is suppressed on this port, ignore received packet as well
763 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
764 if (iofSwitch == null) {
765 return Command.STOP;
766 }
767
768 if (isLinkDiscoverySuppressed(sw, pi.getInPort()))
769 return Command.STOP;
770
771 // If this is a malformed LLDP, or not from us, exit
772 if (lldp.getPortId() == null || lldp.getPortId().getLength() != 3)
773 return Command.CONTINUE;
774
775 long myId = ByteBuffer.wrap(controllerTLV.getValue()).getLong();
776 long otherId = 0;
777 boolean myLLDP = false;
778 Boolean isReverse = null;
779
780 ByteBuffer portBB = ByteBuffer.wrap(lldp.getPortId().getValue());
781 portBB.position(1);
782
783 Short remotePort = portBB.getShort();
784 IOFSwitch remoteSwitch = null;
785
786 // Verify this LLDP packet matches what we're looking for
787 for (LLDPTLV lldptlv : lldp.getOptionalTLVList()) {
788 if (lldptlv.getType() == 127 && lldptlv.getLength() == 12 &&
789 lldptlv.getValue()[0] == 0x0 && lldptlv.getValue()[1] == 0x26 &&
790 lldptlv.getValue()[2] == (byte)0xe1 && lldptlv.getValue()[3] == 0x0) {
791 ByteBuffer dpidBB = ByteBuffer.wrap(lldptlv.getValue());
792 remoteSwitch = floodlightProvider.getSwitches().get(dpidBB.getLong(4));
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800793 if (remoteSwitch == null) {
HIGUCHI Yuta30d03302013-06-14 13:47:36 -0700794 // Added by ONOS
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800795 // floodlight LLDP coming from a remote switch connected to a different controller
796 // add it to our cache of unconnected remote switches
797 remoteSwitch = addRemoteSwitch(dpidBB.getLong(4), remotePort);
798 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800799 } else if (lldptlv.getType() == 12 && lldptlv.getLength() == 8){
800 otherId = ByteBuffer.wrap(lldptlv.getValue()).getLong();
801 if (myId == otherId)
802 myLLDP = true;
803 } else if (lldptlv.getType() == TLV_DIRECTION_TYPE &&
804 lldptlv.getLength() == TLV_DIRECTION_LENGTH) {
805 if (lldptlv.getValue()[0] == TLV_DIRECTION_VALUE_FORWARD[0])
806 isReverse = false;
807 else if (lldptlv.getValue()[0] == TLV_DIRECTION_VALUE_REVERSE[0])
808 isReverse = true;
809 }
810 }
811
812 if (myLLDP == false) {
813 // This is not the LLDP sent by this controller.
814 // If the LLDP message has multicast bit set, then we need to broadcast
815 // the packet as a regular packet.
816 if (isStandard) {
817 if (log.isTraceEnabled()) {
818 log.trace("Getting standard LLDP from a different controller and quelching it.");
819 }
820 return Command.STOP;
821 }
822 else if (myId < otherId) {
823 if (log.isTraceEnabled()) {
824 log.trace("Getting BDDP packets from a different controller" +
825 "and letting it go through normal processing chain.");
826 }
HIGUCHI Yuta30d03302013-06-14 13:47:36 -0700827 //XXX ONOS: Fix the BDDP broadcast issue
Jonathan Hart0b2c76a2013-02-27 17:09:33 -0800828 //return Command.CONTINUE;
829 return Command.STOP;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800830 }
831 }
832
833
834 if (remoteSwitch == null) {
835 // Ignore LLDPs not generated by Floodlight, or from a switch that has recently
836 // disconnected, or from a switch connected to another Floodlight instance
837 if (log.isTraceEnabled()) {
838 log.trace("Received LLDP from remote switch not connected to the controller");
839 }
840 return Command.STOP;
841 }
842
843 if (!remoteSwitch.portEnabled(remotePort)) {
844 if (log.isTraceEnabled()) {
845 log.trace("Ignoring link with disabled source port: switch {} port {}", remoteSwitch, remotePort);
846 }
847 return Command.STOP;
848 }
849 if (suppressLinkDiscovery.contains(new NodePortTuple(remoteSwitch.getId(),
850 remotePort))) {
851 if (log.isTraceEnabled()) {
852 log.trace("Ignoring link with suppressed src port: switch {} port {}",
853 remoteSwitch, remotePort);
854 }
855 return Command.STOP;
856 }
857 if (!iofSwitch.portEnabled(pi.getInPort())) {
858 if (log.isTraceEnabled()) {
859 log.trace("Ignoring link with disabled dest port: switch {} port {}", sw, pi.getInPort());
860 }
861 return Command.STOP;
862 }
863
864 OFPhysicalPort physicalPort = remoteSwitch.getPort(remotePort);
865 int srcPortState = (physicalPort != null) ? physicalPort.getState() : 0;
866 physicalPort = iofSwitch.getPort(pi.getInPort());
867 int dstPortState = (physicalPort != null) ? physicalPort.getState() : 0;
868
869 // Store the time of update to this link, and push it out to routingEngine
870 Link lt = new Link(remoteSwitch.getId(), remotePort, iofSwitch.getId(), pi.getInPort());
871
872
873 Long lastLldpTime = null;
874 Long lastBddpTime = null;
875
876 Long firstSeenTime = System.currentTimeMillis();
877
878 if (isStandard)
879 lastLldpTime = System.currentTimeMillis();
880 else
881 lastBddpTime = System.currentTimeMillis();
882
883 LinkInfo newLinkInfo =
884 new LinkInfo(firstSeenTime, lastLldpTime, lastBddpTime,
885 srcPortState, dstPortState);
886
887 addOrUpdateLink(lt, newLinkInfo);
888
889 // Check if reverse link exists.
890 // If it doesn't exist and if the forward link was seen
891 // first seen within a small interval, send probe on the
892 // reverse link.
893
894 newLinkInfo = links.get(lt);
895 if (newLinkInfo != null && isStandard && isReverse == false) {
896 Link reverseLink = new Link(lt.getDst(), lt.getDstPort(),
897 lt.getSrc(), lt.getSrcPort());
898 LinkInfo reverseInfo = links.get(reverseLink);
899 if (reverseInfo == null) {
900 // the reverse link does not exist.
901 if (newLinkInfo.getFirstSeenTime() > System.currentTimeMillis() - LINK_TIMEOUT) {
902 this.sendDiscoveryMessage(lt.getDst(), lt.getDstPort(), isStandard, true);
903 }
904 }
905 }
906
907 // If the received packet is a BDDP packet, then create a reverse BDDP
908 // link as well.
909 if (!isStandard) {
910 Link reverseLink = new Link(lt.getDst(), lt.getDstPort(),
911 lt.getSrc(), lt.getSrcPort());
912
913 // srcPortState and dstPort state are reversed.
914 LinkInfo reverseInfo =
915 new LinkInfo(firstSeenTime, lastLldpTime, lastBddpTime,
916 dstPortState, srcPortState);
917
918 addOrUpdateLink(reverseLink, reverseInfo);
919 }
920
921 // Remove the node ports from the quarantine and maintenance queues.
922 NodePortTuple nptSrc = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
923 NodePortTuple nptDst = new NodePortTuple(lt.getDst(), lt.getDstPort());
924 removeFromQuarantineQueue(nptSrc);
925 removeFromMaintenanceQueue(nptSrc);
926 removeFromQuarantineQueue(nptDst);
927 removeFromMaintenanceQueue(nptDst);
928
929 // Consume this message
930 return Command.STOP;
931 }
932
933 protected Command handlePacketIn(long sw, OFPacketIn pi,
934 FloodlightContext cntx) {
935 Ethernet eth =
936 IFloodlightProviderService.bcStore.get(cntx,
937 IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
938
939 if(eth.getEtherType() == Ethernet.TYPE_BSN) {
940 BSN bsn = (BSN) eth.getPayload();
941 if (bsn == null) return Command.STOP;
942 if (bsn.getPayload() == null) return Command.STOP;
943 // It could be a packet other than BSN LLDP, therefore
944 // continue with the regular processing.
945 if (bsn.getPayload() instanceof LLDP == false)
946 return Command.CONTINUE;
Ubuntu9cbb4ca2013-02-07 17:19:59 +0000947 return handleLldp((LLDP) bsn.getPayload(), sw, pi, false, cntx);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800948 } else if (eth.getEtherType() == Ethernet.TYPE_LLDP) {
949 return handleLldp((LLDP) eth.getPayload(), sw, pi, true, cntx);
950 } else if (eth.getEtherType() < 1500) {
951 long destMac = eth.getDestinationMAC().toLong();
952 if ((destMac & LINK_LOCAL_MASK) == LINK_LOCAL_VALUE){
953 if (log.isTraceEnabled()) {
954 log.trace("Ignoring packet addressed to 802.1D/Q " +
955 "reserved address.");
956 }
957 return Command.STOP;
958 }
959 }
960
961 // If packet-in is from a quarantine port, stop processing.
962 NodePortTuple npt = new NodePortTuple(sw, pi.getInPort());
963 if (quarantineQueue.contains(npt)) return Command.STOP;
964
965 return Command.CONTINUE;
966 }
967
968 protected UpdateOperation getUpdateOperation(int srcPortState,
969 int dstPortState) {
970 boolean added =
971 (((srcPortState &
972 OFPortState.OFPPS_STP_MASK.getValue()) !=
973 OFPortState.OFPPS_STP_BLOCK.getValue()) &&
974 ((dstPortState &
975 OFPortState.OFPPS_STP_MASK.getValue()) !=
976 OFPortState.OFPPS_STP_BLOCK.getValue()));
977
978 if (added) return UpdateOperation.LINK_UPDATED;
979 return UpdateOperation.LINK_REMOVED;
980 }
981
982
983
984 protected UpdateOperation getUpdateOperation(int srcPortState) {
985 boolean portUp = ((srcPortState &
986 OFPortState.OFPPS_STP_MASK.getValue()) !=
987 OFPortState.OFPPS_STP_BLOCK.getValue());
988
989 if (portUp) return UpdateOperation.PORT_UP;
990 else return UpdateOperation.PORT_DOWN;
991 }
992
993 protected boolean addOrUpdateLink(Link lt, LinkInfo newInfo) {
994
995 NodePortTuple srcNpt, dstNpt;
996 boolean linkChanged = false;
997
998 lock.writeLock().lock();
999 try {
1000 // put the new info. if an old info exists, it will be returned.
1001 LinkInfo oldInfo = links.put(lt, newInfo);
1002 if (oldInfo != null &&
1003 oldInfo.getFirstSeenTime() < newInfo.getFirstSeenTime())
1004 newInfo.setFirstSeenTime(oldInfo.getFirstSeenTime());
1005
1006 if (log.isTraceEnabled()) {
1007 log.trace("addOrUpdateLink: {} {}",
1008 lt,
1009 (newInfo.getMulticastValidTime()!=null) ? "multicast" : "unicast");
1010 }
1011
1012 UpdateOperation updateOperation = null;
1013 linkChanged = false;
1014
1015 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1016 dstNpt = new NodePortTuple(lt.getDst(), lt.getDstPort());
1017
1018 if (oldInfo == null) {
1019 // index it by switch source
1020 if (!switchLinks.containsKey(lt.getSrc()))
1021 switchLinks.put(lt.getSrc(), new HashSet<Link>());
1022 switchLinks.get(lt.getSrc()).add(lt);
1023
1024 // index it by switch dest
1025 if (!switchLinks.containsKey(lt.getDst()))
1026 switchLinks.put(lt.getDst(), new HashSet<Link>());
1027 switchLinks.get(lt.getDst()).add(lt);
1028
1029 // index both ends by switch:port
1030 if (!portLinks.containsKey(srcNpt))
1031 portLinks.put(srcNpt, new HashSet<Link>());
1032 portLinks.get(srcNpt).add(lt);
1033
1034 if (!portLinks.containsKey(dstNpt))
1035 portLinks.put(dstNpt, new HashSet<Link>());
1036 portLinks.get(dstNpt).add(lt);
1037
1038 // Add to portNOFLinks if the unicast valid time is null
1039 if (newInfo.getUnicastValidTime() == null)
1040 addLinkToBroadcastDomain(lt);
Umesh Krishnaswamy2b9d5642013-01-04 11:00:27 -08001041
HIGUCHI Yuta30d03302013-06-14 13:47:36 -07001042 // ONOS: Distinguish added event separately from updated event
Pankaj Berdea41016d2013-06-10 21:18:18 -07001043 updateOperation = UpdateOperation.LINK_ADDED;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001044 linkChanged = true;
1045
1046 // Add to event history
1047 evHistTopoLink(lt.getSrc(),
1048 lt.getDst(),
1049 lt.getSrcPort(),
1050 lt.getDstPort(),
1051 newInfo.getSrcPortState(), newInfo.getDstPortState(),
1052 getLinkType(lt, newInfo),
1053 EvAction.LINK_ADDED, "LLDP Recvd");
1054 } else {
1055 // Since the link info is already there, we need to
1056 // update the right fields.
1057 if (newInfo.getUnicastValidTime() == null) {
1058 // This is due to a multicast LLDP, so copy the old unicast
1059 // value.
1060 if (oldInfo.getUnicastValidTime() != null) {
1061 newInfo.setUnicastValidTime(oldInfo.getUnicastValidTime());
1062 }
1063 } else if (newInfo.getMulticastValidTime() == null) {
1064 // This is due to a unicast LLDP, so copy the old multicast
1065 // value.
1066 if (oldInfo.getMulticastValidTime() != null) {
1067 newInfo.setMulticastValidTime(oldInfo.getMulticastValidTime());
1068 }
1069 }
1070
1071 Long oldTime = oldInfo.getUnicastValidTime();
1072 Long newTime = newInfo.getUnicastValidTime();
1073 // the link has changed its state between openflow and non-openflow
1074 // if the unicastValidTimes are null or not null
1075 if (oldTime != null & newTime == null) {
1076 // openflow -> non-openflow transition
1077 // we need to add the link tuple to the portNOFLinks
1078 addLinkToBroadcastDomain(lt);
1079 linkChanged = true;
1080 } else if (oldTime == null & newTime != null) {
1081 // non-openflow -> openflow transition
1082 // we need to remove the link from the portNOFLinks
1083 removeLinkFromBroadcastDomain(lt);
1084 linkChanged = true;
1085 }
1086
1087 // Only update the port states if they've changed
1088 if (newInfo.getSrcPortState().intValue() !=
1089 oldInfo.getSrcPortState().intValue() ||
1090 newInfo.getDstPortState().intValue() !=
1091 oldInfo.getDstPortState().intValue())
1092 linkChanged = true;
1093
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001094 if (linkChanged) {
1095 updateOperation = getUpdateOperation(newInfo.getSrcPortState(),
1096 newInfo.getDstPortState());
1097 if (log.isTraceEnabled()) {
1098 log.trace("Updated link {}", lt);
1099 }
1100 // Add to event history
1101 evHistTopoLink(lt.getSrc(),
1102 lt.getDst(),
1103 lt.getSrcPort(),
1104 lt.getDstPort(),
1105 newInfo.getSrcPortState(), newInfo.getDstPortState(),
1106 getLinkType(lt, newInfo),
1107 EvAction.LINK_PORT_STATE_UPDATED,
1108 "LLDP Recvd");
1109 }
1110 }
1111
1112 if (linkChanged) {
1113 // find out if the link was added or removed here.
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001114 LinkUpdate update = new LinkUpdate(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001115 lt.getDst(), lt.getDstPort(),
1116 getLinkType(lt, newInfo),
1117 updateOperation));
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001118 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001119 }
1120 } finally {
1121 lock.writeLock().unlock();
1122 }
1123
1124 return linkChanged;
1125 }
1126
1127 public Map<Long, Set<Link>> getSwitchLinks() {
1128 return this.switchLinks;
1129 }
1130
1131 /**
1132 * Removes links from memory and storage.
1133 * @param links The List of @LinkTuple to delete.
1134 */
1135 protected void deleteLinks(List<Link> links, String reason) {
1136 NodePortTuple srcNpt, dstNpt;
1137
1138 lock.writeLock().lock();
1139 try {
1140 for (Link lt : links) {
1141 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1142 dstNpt =new NodePortTuple(lt.getDst(), lt.getDstPort());
1143
1144 switchLinks.get(lt.getSrc()).remove(lt);
1145 switchLinks.get(lt.getDst()).remove(lt);
1146 if (switchLinks.containsKey(lt.getSrc()) &&
1147 switchLinks.get(lt.getSrc()).isEmpty())
1148 this.switchLinks.remove(lt.getSrc());
1149 if (this.switchLinks.containsKey(lt.getDst()) &&
1150 this.switchLinks.get(lt.getDst()).isEmpty())
1151 this.switchLinks.remove(lt.getDst());
1152
1153 if (this.portLinks.get(srcNpt) != null) {
1154 this.portLinks.get(srcNpt).remove(lt);
1155 if (this.portLinks.get(srcNpt).isEmpty())
1156 this.portLinks.remove(srcNpt);
1157 }
1158 if (this.portLinks.get(dstNpt) != null) {
1159 this.portLinks.get(dstNpt).remove(lt);
1160 if (this.portLinks.get(dstNpt).isEmpty())
1161 this.portLinks.remove(dstNpt);
1162 }
1163
1164 LinkInfo info = this.links.remove(lt);
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001165 LinkUpdate update = new LinkUpdate(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001166 lt.getDst(), lt.getDstPort(),
1167 getLinkType(lt, info),
1168 UpdateOperation.LINK_REMOVED));
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001169 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001170
1171 // Update Event History
1172 evHistTopoLink(lt.getSrc(),
1173 lt.getDst(),
1174 lt.getSrcPort(),
1175 lt.getDstPort(),
1176 0, 0, // Port states
1177 ILinkDiscovery.LinkType.INVALID_LINK,
1178 EvAction.LINK_DELETED, reason);
1179
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001180 // TODO Whenever link is removed, it has to checked if
1181 // the switchports must be added to quarantine.
1182
1183 if (log.isTraceEnabled()) {
1184 log.trace("Deleted link {}", lt);
1185 }
1186 }
1187 } finally {
1188 lock.writeLock().unlock();
1189 }
1190 }
1191
1192 /**
1193 * Handles an OFPortStatus message from a switch. We will add or
1194 * delete LinkTupes as well re-compute the topology if needed.
1195 * @param sw The IOFSwitch that sent the port status message
1196 * @param ps The OFPortStatus message
1197 * @return The Command to continue or stop after we process this message
1198 */
1199 protected Command handlePortStatus(long sw, OFPortStatus ps) {
1200
1201 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
1202 if (iofSwitch == null) return Command.CONTINUE;
HIGUCHI Yutaa89b2842013-06-17 13:54:57 -07001203
HIGUCHI Yuta30d03302013-06-14 13:47:36 -07001204 // ONOS: If we do not control this switch, then we should not process its port status messages
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -07001205 if (!registryService.hasControl(iofSwitch.getId())) return Command.CONTINUE;
1206
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001207 if (log.isTraceEnabled()) {
1208 log.trace("handlePortStatus: Switch {} port #{} reason {}; " +
1209 "config is {} state is {}",
1210 new Object[] {iofSwitch.getStringId(),
1211 ps.getDesc().getPortNumber(),
1212 ps.getReason(),
1213 ps.getDesc().getConfig(),
1214 ps.getDesc().getState()});
1215 }
1216
1217 short port = ps.getDesc().getPortNumber();
1218 NodePortTuple npt = new NodePortTuple(sw, port);
1219 boolean linkDeleted = false;
1220 boolean linkInfoChanged = false;
1221
1222 lock.writeLock().lock();
1223 try {
1224 // if ps is a delete, or a modify where the port is down or
1225 // configured down
1226 if ((byte)OFPortReason.OFPPR_DELETE.ordinal() == ps.getReason() ||
1227 ((byte)OFPortReason.OFPPR_MODIFY.ordinal() ==
1228 ps.getReason() && !portEnabled(ps.getDesc()))) {
1229 deleteLinksOnPort(npt, "Port Status Changed");
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001230 LinkUpdate update = new LinkUpdate(new LDUpdate(sw, port, UpdateOperation.PORT_DOWN));
1231 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001232 linkDeleted = true;
1233 }
1234 else if (ps.getReason() ==
1235 (byte)OFPortReason.OFPPR_MODIFY.ordinal()) {
1236 // If ps is a port modification and the port state has changed
1237 // that affects links in the topology
1238
1239 if (this.portLinks.containsKey(npt)) {
1240 for (Link lt: this.portLinks.get(npt)) {
1241 LinkInfo linkInfo = links.get(lt);
1242 assert(linkInfo != null);
1243 Integer updatedSrcPortState = null;
1244 Integer updatedDstPortState = null;
1245 if (lt.getSrc() == npt.getNodeId() &&
1246 lt.getSrcPort() == npt.getPortId() &&
1247 (linkInfo.getSrcPortState() !=
1248 ps.getDesc().getState())) {
1249 updatedSrcPortState = ps.getDesc().getState();
1250 linkInfo.setSrcPortState(updatedSrcPortState);
1251 }
1252 if (lt.getDst() == npt.getNodeId() &&
1253 lt.getDstPort() == npt.getPortId() &&
1254 (linkInfo.getDstPortState() !=
1255 ps.getDesc().getState())) {
1256 updatedDstPortState = ps.getDesc().getState();
1257 linkInfo.setDstPortState(updatedDstPortState);
1258 }
1259 if ((updatedSrcPortState != null) ||
1260 (updatedDstPortState != null)) {
1261 // The link is already known to link discovery
1262 // manager and the status has changed, therefore
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001263 // send an LinkUpdate.
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001264 UpdateOperation operation =
1265 getUpdateOperation(linkInfo.getSrcPortState(),
1266 linkInfo.getDstPortState());
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001267 LinkUpdate update = new LinkUpdate(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001268 lt.getDst(), lt.getDstPort(),
1269 getLinkType(lt, linkInfo),
1270 operation));
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001271 controller.publishUpdate(update);
Jonathan Hart2fa28062013-11-25 20:16:28 -08001272
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001273 linkInfoChanged = true;
1274 }
1275 }
1276 }
1277
1278 UpdateOperation operation =
1279 getUpdateOperation(ps.getDesc().getState());
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001280 LinkUpdate update = new LinkUpdate(new LDUpdate(sw, port, operation));
1281 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001282 }
1283
1284 if (!linkDeleted && !linkInfoChanged){
1285 if (log.isTraceEnabled()) {
1286 log.trace("handlePortStatus: Switch {} port #{} reason {};"+
1287 " no links to update/remove",
1288 new Object[] {HexString.toHexString(sw),
1289 ps.getDesc().getPortNumber(),
1290 ps.getReason()});
1291 }
1292 }
1293 } finally {
1294 lock.writeLock().unlock();
1295 }
1296
1297 if (!linkDeleted) {
1298 // Send LLDP right away when port state is changed for faster
1299 // cluster-merge. If it is a link delete then there is not need
1300 // to send the LLDPs right away and instead we wait for the LLDPs
1301 // to be sent on the timer as it is normally done
1302 // do it outside the write-lock
1303 // sendLLDPTask.reschedule(1000, TimeUnit.MILLISECONDS);
1304 processNewPort(npt.getNodeId(), npt.getPortId());
1305 }
1306 return Command.CONTINUE;
1307 }
1308
1309 /**
1310 * Process a new port.
1311 * If link discovery is disabled on the port, then do nothing.
1312 * If autoportfast feature is enabled and the port is a fast port, then
1313 * do nothing.
1314 * Otherwise, send LLDP message. Add the port to quarantine.
1315 * @param sw
1316 * @param p
1317 */
1318 private void processNewPort(long sw, short p) {
1319 if (isLinkDiscoverySuppressed(sw, p)) {
1320 // Do nothing as link discovery is suppressed.
1321 }
1322 else if (autoPortFastFeature && isFastPort(sw, p)) {
1323 // Do nothing as the port is a fast port.
1324 }
1325 else {
1326 NodePortTuple npt = new NodePortTuple(sw, p);
1327 discover(sw, p);
1328 // if it is not a fast port, add it to quarantine.
1329 if (!isFastPort(sw, p)) {
1330 addToQuarantineQueue(npt);
1331 } else {
1332 // Add to maintenance queue to ensure that BDDP packets
1333 // are sent out.
1334 addToMaintenanceQueue(npt);
1335 }
1336 }
1337 }
1338
1339 /**
1340 * We send out LLDP messages when a switch is added to discover the topology
1341 * @param sw The IOFSwitch that connected to the controller
1342 */
1343 @Override
1344 public void addedSwitch(IOFSwitch sw) {
1345
1346 if (sw.getEnabledPorts() != null) {
1347 for (Short p : sw.getEnabledPortNumbers()) {
1348 processNewPort(sw.getId(), p);
1349 }
1350 }
1351 // Update event history
1352 evHistTopoSwitch(sw, EvAction.SWITCH_CONNECTED, "None");
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001353 LinkUpdate update = new LinkUpdate(new LDUpdate(sw.getId(), null,
1354 UpdateOperation.SWITCH_UPDATED));
1355 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001356 }
1357
1358 /**
1359 * When a switch disconnects we remove any links from our map and notify.
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001360 */
1361 @Override
1362 public void removedSwitch(IOFSwitch iofSwitch) {
1363 // Update event history
1364 long sw = iofSwitch.getId();
1365 evHistTopoSwitch(iofSwitch, EvAction.SWITCH_DISCONNECTED, "None");
1366 List<Link> eraseList = new ArrayList<Link>();
1367 lock.writeLock().lock();
1368 try {
1369 if (switchLinks.containsKey(sw)) {
1370 if (log.isTraceEnabled()) {
1371 log.trace("Handle switchRemoved. Switch {}; removing links {}",
1372 HexString.toHexString(sw), switchLinks.get(sw));
1373 }
1374 // add all tuples with an endpoint on this switch to erase list
1375 eraseList.addAll(switchLinks.get(sw));
HIGUCHI Yutaa89b2842013-06-17 13:54:57 -07001376 deleteLinks(eraseList, "Switch Removed");
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001377
1378 // Send a switch removed update
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001379 LinkUpdate update = new LinkUpdate(new LDUpdate(sw, null, UpdateOperation.SWITCH_REMOVED));
1380 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001381 }
1382 } finally {
1383 lock.writeLock().unlock();
1384 }
1385 }
1386
1387 /**
1388 * We don't react the port changed notifications here. we listen for
1389 * OFPortStatus messages directly. Might consider using this notifier
1390 * instead
1391 */
1392 @Override
1393 public void switchPortChanged(Long switchId) {
1394 // no-op
1395 }
1396
1397 /**
1398 * Delete links incident on a given switch port.
1399 * @param npt
1400 * @param reason
1401 */
1402 protected void deleteLinksOnPort(NodePortTuple npt, String reason) {
1403 List<Link> eraseList = new ArrayList<Link>();
1404 if (this.portLinks.containsKey(npt)) {
1405 if (log.isTraceEnabled()) {
1406 log.trace("handlePortStatus: Switch {} port #{} " +
1407 "removing links {}",
1408 new Object[] {HexString.toHexString(npt.getNodeId()),
1409 npt.getPortId(),
1410 this.portLinks.get(npt)});
1411 }
1412 eraseList.addAll(this.portLinks.get(npt));
1413 deleteLinks(eraseList, reason);
1414 }
1415 }
1416
1417 /**
1418 * Iterates through the list of links and deletes if the
1419 * last discovery message reception time exceeds timeout values.
1420 */
1421 protected void timeoutLinks() {
1422 List<Link> eraseList = new ArrayList<Link>();
1423 Long curTime = System.currentTimeMillis();
1424 boolean linkChanged = false;
1425
1426 // reentrant required here because deleteLink also write locks
1427 lock.writeLock().lock();
1428 try {
1429 Iterator<Entry<Link, LinkInfo>> it =
1430 this.links.entrySet().iterator();
1431 while (it.hasNext()) {
1432 Entry<Link, LinkInfo> entry = it.next();
1433 Link lt = entry.getKey();
1434 LinkInfo info = entry.getValue();
1435
1436 // Timeout the unicast and multicast LLDP valid times
1437 // independently.
1438 if ((info.getUnicastValidTime() != null) &&
1439 (info.getUnicastValidTime() + (this.LINK_TIMEOUT * 1000) < curTime)){
1440 info.setUnicastValidTime(null);
1441
1442 if (info.getMulticastValidTime() != null)
1443 addLinkToBroadcastDomain(lt);
1444 // Note that even if mTime becomes null later on,
1445 // the link would be deleted, which would trigger updateClusters().
1446 linkChanged = true;
1447 }
1448 if ((info.getMulticastValidTime()!= null) &&
1449 (info.getMulticastValidTime()+ (this.LINK_TIMEOUT * 1000) < curTime)) {
1450 info.setMulticastValidTime(null);
1451 // if uTime is not null, then link will remain as openflow
1452 // link. If uTime is null, it will be deleted. So, we
1453 // don't care about linkChanged flag here.
1454 removeLinkFromBroadcastDomain(lt);
1455 linkChanged = true;
1456 }
1457 // Add to the erase list only if the unicast
1458 // time is null.
1459 if (info.getUnicastValidTime() == null &&
1460 info.getMulticastValidTime() == null){
1461 eraseList.add(entry.getKey());
1462 } else if (linkChanged) {
1463 UpdateOperation operation;
1464 operation = getUpdateOperation(info.getSrcPortState(),
1465 info.getDstPortState());
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001466 LinkUpdate update = new LinkUpdate(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001467 lt.getDst(), lt.getDstPort(),
1468 getLinkType(lt, info),
1469 operation));
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001470 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001471 }
1472 }
1473
1474 // if any link was deleted or any link was changed.
1475 if ((eraseList.size() > 0) || linkChanged) {
1476 deleteLinks(eraseList, "LLDP timeout");
1477 }
1478 } finally {
1479 lock.writeLock().unlock();
1480 }
1481 }
1482
1483 private boolean portEnabled(OFPhysicalPort port) {
1484 if (port == null)
1485 return false;
1486 if ((OFPortConfig.OFPPC_PORT_DOWN.getValue() & port.getConfig()) > 0)
1487 return false;
1488 if ((OFPortState.OFPPS_LINK_DOWN.getValue() & port.getState()) > 0)
1489 return false;
1490 // Port STP state doesn't work with multiple VLANs, so ignore it for now
1491 // if ((port.getState() & OFPortState.OFPPS_STP_MASK.getValue()) == OFPortState.OFPPS_STP_BLOCK.getValue())
1492 // return false;
1493 return true;
1494 }
1495
1496 public Map<NodePortTuple, Set<Link>> getPortBroadcastDomainLinks() {
1497 return portBroadcastDomainLinks;
1498 }
1499
1500 @Override
1501 public Map<Link, LinkInfo> getLinks() {
1502 lock.readLock().lock();
1503 Map<Link, LinkInfo> result;
1504 try {
1505 result = new HashMap<Link, LinkInfo>(links);
1506 } finally {
1507 lock.readLock().unlock();
1508 }
1509 return result;
1510 }
1511
1512 protected void addLinkToBroadcastDomain(Link lt) {
1513
1514 NodePortTuple srcNpt, dstNpt;
1515 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1516 dstNpt = new NodePortTuple(lt.getDst(), lt.getDstPort());
1517
1518 if (!portBroadcastDomainLinks.containsKey(lt.getSrc()))
1519 portBroadcastDomainLinks.put(srcNpt, new HashSet<Link>());
1520 portBroadcastDomainLinks.get(srcNpt).add(lt);
1521
1522 if (!portBroadcastDomainLinks.containsKey(lt.getDst()))
1523 portBroadcastDomainLinks.put(dstNpt, new HashSet<Link>());
1524 portBroadcastDomainLinks.get(dstNpt).add(lt);
1525 }
1526
1527 protected void removeLinkFromBroadcastDomain(Link lt) {
1528
1529 NodePortTuple srcNpt, dstNpt;
1530 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1531 dstNpt = new NodePortTuple(lt.getDst(), lt.getDstPort());
1532
1533 if (portBroadcastDomainLinks.containsKey(srcNpt)) {
1534 portBroadcastDomainLinks.get(srcNpt).remove(lt);
1535 if (portBroadcastDomainLinks.get(srcNpt).isEmpty())
1536 portBroadcastDomainLinks.remove(srcNpt);
1537 }
1538
1539 if (portBroadcastDomainLinks.containsKey(dstNpt)) {
1540 portBroadcastDomainLinks.get(dstNpt).remove(lt);
1541 if (portBroadcastDomainLinks.get(dstNpt).isEmpty())
1542 portBroadcastDomainLinks.remove(dstNpt);
1543 }
1544 }
1545
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001546 @Override
1547 public void addListener(ILinkDiscoveryListener listener) {
1548 linkDiscoveryAware.add(listener);
1549 }
1550
1551 /**
1552 * Register a link discovery aware component
1553 * @param linkDiscoveryAwareComponent
1554 */
1555 public void addLinkDiscoveryAware(ILinkDiscoveryListener linkDiscoveryAwareComponent) {
1556 // TODO make this a copy on write set or lock it somehow
1557 this.linkDiscoveryAware.add(linkDiscoveryAwareComponent);
1558 }
1559
1560 /**
1561 * Deregister a link discovery aware component
1562 * @param linkDiscoveryAwareComponent
1563 */
1564 public void removeLinkDiscoveryAware(ILinkDiscoveryListener linkDiscoveryAwareComponent) {
1565 // TODO make this a copy on write set or lock it somehow
1566 this.linkDiscoveryAware.remove(linkDiscoveryAwareComponent);
1567 }
1568
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001569 @Override
1570 public boolean isCallbackOrderingPrereq(OFType type, String name) {
1571 return false;
1572 }
1573
1574 @Override
1575 public boolean isCallbackOrderingPostreq(OFType type, String name) {
1576 return false;
1577 }
1578
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001579 // IFloodlightModule classes
1580
1581 @Override
1582 public Collection<Class<? extends IFloodlightService>> getModuleServices() {
1583 Collection<Class<? extends IFloodlightService>> l =
1584 new ArrayList<Class<? extends IFloodlightService>>();
1585 l.add(ILinkDiscoveryService.class);
1586 //l.add(ITopologyService.class);
1587 return l;
1588 }
1589
1590 @Override
1591 public Map<Class<? extends IFloodlightService>, IFloodlightService>
1592 getServiceImpls() {
1593 Map<Class<? extends IFloodlightService>,
1594 IFloodlightService> m =
1595 new HashMap<Class<? extends IFloodlightService>,
1596 IFloodlightService>();
1597 // We are the class that implements the service
1598 m.put(ILinkDiscoveryService.class, this);
1599 return m;
1600 }
1601
1602 @Override
1603 public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
1604 Collection<Class<? extends IFloodlightService>> l =
1605 new ArrayList<Class<? extends IFloodlightService>>();
1606 l.add(IFloodlightProviderService.class);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001607 l.add(IThreadPoolService.class);
1608 l.add(IRestApiService.class);
HIGUCHI Yuta30d03302013-06-14 13:47:36 -07001609 // Added by ONOS
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -07001610 l.add(IControllerRegistryService.class);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001611 return l;
1612 }
1613
1614 @Override
1615 public void init(FloodlightModuleContext context)
1616 throws FloodlightModuleException {
1617 floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001618 threadPool = context.getServiceImpl(IThreadPoolService.class);
1619 restApi = context.getServiceImpl(IRestApiService.class);
HIGUCHI Yuta30d03302013-06-14 13:47:36 -07001620 // Added by ONOS
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -07001621 registryService = context.getServiceImpl(IControllerRegistryService.class);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001622
1623 // Set the autoportfast feature to false.
1624 this.autoPortFastFeature = false;
1625
1626 // We create this here because there is no ordering guarantee
1627 this.linkDiscoveryAware = new ArrayList<ILinkDiscoveryListener>();
1628 this.lock = new ReentrantReadWriteLock();
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001629 this.links = new HashMap<Link, LinkInfo>();
1630 this.portLinks = new HashMap<NodePortTuple, Set<Link>>();
1631 this.suppressLinkDiscovery =
1632 Collections.synchronizedSet(new HashSet<NodePortTuple>());
1633 this.portBroadcastDomainLinks = new HashMap<NodePortTuple, Set<Link>>();
1634 this.switchLinks = new HashMap<Long, Set<Link>>();
1635 this.quarantineQueue = new LinkedBlockingQueue<NodePortTuple>();
1636 this.maintenanceQueue = new LinkedBlockingQueue<NodePortTuple>();
HIGUCHI Yuta30d03302013-06-14 13:47:36 -07001637 // Added by ONOS
HIGUCHI Yuta7677a6f2013-06-14 14:13:35 -07001638 this.remoteSwitches = new HashMap<Long, IOnosRemoteSwitch>();
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001639
1640 this.evHistTopologySwitch =
1641 new EventHistory<EventHistoryTopologySwitch>("Topology: Switch");
1642 this.evHistTopologyLink =
1643 new EventHistory<EventHistoryTopologyLink>("Topology: Link");
1644 this.evHistTopologyCluster =
1645 new EventHistory<EventHistoryTopologyCluster>("Topology: Cluster");
1646 }
1647
1648 @Override
1649 @LogMessageDocs({
1650 @LogMessageDoc(level="ERROR",
1651 message="No storage source found.",
1652 explanation="Storage source was not initialized; cannot initialize " +
1653 "link discovery.",
1654 recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
1655 @LogMessageDoc(level="ERROR",
1656 message="Error in installing listener for " +
1657 "switch config table {table}",
1658 explanation="Failed to install storage notification for the " +
1659 "switch config table",
1660 recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
1661 @LogMessageDoc(level="ERROR",
1662 message="No storage source found.",
1663 explanation="Storage source was not initialized; cannot initialize " +
1664 "link discovery.",
1665 recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
1666 @LogMessageDoc(level="ERROR",
1667 message="Exception in LLDP send timer.",
1668 explanation="An unknown error occured while sending LLDP " +
1669 "messages to switches.",
1670 recommendation=LogMessageDoc.CHECK_SWITCH)
1671 })
1672 public void startUp(FloodlightModuleContext context) {
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001673 ScheduledExecutorService ses = threadPool.getScheduledExecutor();
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001674 controller =
1675 context.getServiceImpl(IFloodlightProviderService.class);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001676
1677 // To be started by the first switch connection
1678 discoveryTask = new SingletonTask(ses, new Runnable() {
1679 @Override
1680 public void run() {
1681 try {
1682 discoverLinks();
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001683 } catch (Exception e) {
1684 log.error("Exception in LLDP send timer.", e);
1685 } finally {
1686 if (!shuttingDown) {
1687 // null role implies HA mode is not enabled.
1688 Role role = floodlightProvider.getRole();
1689 if (role == null || role == Role.MASTER) {
1690 log.trace("Rescheduling discovery task as role = {}", role);
1691 discoveryTask.reschedule(DISCOVERY_TASK_INTERVAL,
1692 TimeUnit.SECONDS);
1693 } else {
1694 log.trace("Stopped LLDP rescheduling due to role = {}.", role);
1695 }
1696 }
1697 }
1698 }
1699 });
1700
1701 // null role implies HA mode is not enabled.
1702 Role role = floodlightProvider.getRole();
1703 if (role == null || role == Role.MASTER) {
1704 log.trace("Setup: Rescheduling discovery task. role = {}", role);
1705 discoveryTask.reschedule(DISCOVERY_TASK_INTERVAL, TimeUnit.SECONDS);
1706 } else {
1707 log.trace("Setup: Not scheduling LLDP as role = {}.", role);
1708 }
1709
1710 // Setup the BDDP task. It is invoked whenever switch port tuples
1711 // are added to the quarantine list.
1712 bddpTask = new SingletonTask(ses, new QuarantineWorker());
1713 bddpTask.reschedule(BDDP_TASK_INTERVAL, TimeUnit.MILLISECONDS);
1714
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001715
1716 // Register for the OpenFlow messages we want to receive
1717 floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
1718 floodlightProvider.addOFMessageListener(OFType.PORT_STATUS, this);
1719 // Register for switch updates
1720 floodlightProvider.addOFSwitchListener(this);
1721 floodlightProvider.addHAListener(this);
1722 floodlightProvider.addInfoProvider("summary", this);
1723 if (restApi != null)
1724 restApi.addRestletRoutable(new LinkDiscoveryWebRoutable());
1725 setControllerTLV();
1726 }
1727
1728 // ****************************************************
1729 // Topology Manager's Event History members and methods
1730 // ****************************************************
1731
1732 // Topology Manager event history
1733 public EventHistory<EventHistoryTopologySwitch> evHistTopologySwitch;
1734 public EventHistory<EventHistoryTopologyLink> evHistTopologyLink;
1735 public EventHistory<EventHistoryTopologyCluster> evHistTopologyCluster;
1736 public EventHistoryTopologySwitch evTopoSwitch;
1737 public EventHistoryTopologyLink evTopoLink;
1738 public EventHistoryTopologyCluster evTopoCluster;
1739
1740 // Switch Added/Deleted
1741 private void evHistTopoSwitch(IOFSwitch sw, EvAction actn, String reason) {
1742 if (evTopoSwitch == null) {
1743 evTopoSwitch = new EventHistoryTopologySwitch();
1744 }
1745 evTopoSwitch.dpid = sw.getId();
1746 if ((sw.getChannel() != null) &&
1747 (SocketAddress.class.isInstance(
1748 sw.getChannel().getRemoteAddress()))) {
1749 evTopoSwitch.ipv4Addr =
1750 IPv4.toIPv4Address(((InetSocketAddress)(sw.getChannel().
1751 getRemoteAddress())).getAddress().getAddress());
1752 evTopoSwitch.l4Port =
1753 ((InetSocketAddress)(sw.getChannel().
1754 getRemoteAddress())).getPort();
1755 } else {
1756 evTopoSwitch.ipv4Addr = 0;
1757 evTopoSwitch.l4Port = 0;
1758 }
1759 evTopoSwitch.reason = reason;
1760 evTopoSwitch = evHistTopologySwitch.put(evTopoSwitch, actn);
1761 }
1762
1763 private void evHistTopoLink(long srcDpid, long dstDpid, short srcPort,
1764 short dstPort, int srcPortState, int dstPortState,
1765 ILinkDiscovery.LinkType linkType,
1766 EvAction actn, String reason) {
1767 if (evTopoLink == null) {
1768 evTopoLink = new EventHistoryTopologyLink();
1769 }
1770 evTopoLink.srcSwDpid = srcDpid;
1771 evTopoLink.dstSwDpid = dstDpid;
1772 evTopoLink.srcSwport = srcPort & 0xffff;
1773 evTopoLink.dstSwport = dstPort & 0xffff;
1774 evTopoLink.srcPortState = srcPortState;
1775 evTopoLink.dstPortState = dstPortState;
1776 evTopoLink.reason = reason;
1777 switch (linkType) {
1778 case DIRECT_LINK:
1779 evTopoLink.linkType = "DIRECT_LINK";
1780 break;
1781 case MULTIHOP_LINK:
1782 evTopoLink.linkType = "MULTIHOP_LINK";
1783 break;
1784 case TUNNEL:
1785 evTopoLink.linkType = "TUNNEL";
1786 break;
1787 case INVALID_LINK:
1788 default:
1789 evTopoLink.linkType = "Unknown";
1790 break;
1791 }
1792 evTopoLink = evHistTopologyLink.put(evTopoLink, actn);
1793 }
1794
1795 public void evHistTopoCluster(long dpid, long clusterIdOld,
1796 long clusterIdNew, EvAction action, String reason) {
1797 if (evTopoCluster == null) {
1798 evTopoCluster = new EventHistoryTopologyCluster();
1799 }
1800 evTopoCluster.dpid = dpid;
1801 evTopoCluster.clusterIdOld = clusterIdOld;
1802 evTopoCluster.clusterIdNew = clusterIdNew;
1803 evTopoCluster.reason = reason;
1804 evTopoCluster = evHistTopologyCluster.put(evTopoCluster, action);
1805 }
1806
1807 @Override
1808 public Map<String, Object> getInfo(String type) {
1809 if (!"summary".equals(type)) return null;
1810
1811 Map<String, Object> info = new HashMap<String, Object>();
1812
1813 int num_links = 0;
1814 for (Set<Link> links : switchLinks.values())
1815 num_links += links.size();
1816 info.put("# inter-switch links", num_links / 2);
1817
1818 return info;
1819 }
1820
1821 // IHARoleListener
1822 @Override
1823 public void roleChanged(Role oldRole, Role newRole) {
1824 switch(newRole) {
1825 case MASTER:
1826 if (oldRole == Role.SLAVE) {
1827 if (log.isTraceEnabled()) {
1828 log.trace("Sending LLDPs " +
1829 "to HA change from SLAVE->MASTER");
1830 }
Jonathan Hart2fa28062013-11-25 20:16:28 -08001831 //clearAllLinks();
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001832 log.debug("Role Change to Master: Rescheduling discovery task.");
1833 discoveryTask.reschedule(1, TimeUnit.MICROSECONDS);
1834 }
1835 break;
1836 case SLAVE:
1837 if (log.isTraceEnabled()) {
1838 log.trace("Clearing links due to " +
1839 "HA change to SLAVE");
1840 }
1841 switchLinks.clear();
1842 links.clear();
1843 portLinks.clear();
1844 portBroadcastDomainLinks.clear();
1845 discoverOnAllPorts();
1846 break;
1847 default:
1848 break;
1849 }
1850 }
1851
1852 @Override
1853 public void controllerNodeIPsChanged(
1854 Map<String, String> curControllerNodeIPs,
1855 Map<String, String> addedControllerNodeIPs,
1856 Map<String, String> removedControllerNodeIPs) {
1857 // ignore
1858 }
1859
1860 public boolean isAutoPortFastFeature() {
1861 return autoPortFastFeature;
1862 }
1863
1864 public void setAutoPortFastFeature(boolean autoPortFastFeature) {
1865 this.autoPortFastFeature = autoPortFastFeature;
1866 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001867}