blob: 3860e05cc381ffe732c91dde0ff76a88fa188702 [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;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080043import net.floodlightcontroller.core.IOFMessageListener;
44import net.floodlightcontroller.core.IOFSwitch;
45import net.floodlightcontroller.core.IOFSwitchListener;
46import net.floodlightcontroller.core.annotations.LogMessageCategory;
47import net.floodlightcontroller.core.annotations.LogMessageDoc;
48import net.floodlightcontroller.core.annotations.LogMessageDocs;
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -070049import net.floodlightcontroller.core.internal.OFSwitchImpl;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080050import net.floodlightcontroller.core.module.FloodlightModuleContext;
51import net.floodlightcontroller.core.module.FloodlightModuleException;
52import net.floodlightcontroller.core.module.IFloodlightModule;
53import net.floodlightcontroller.core.module.IFloodlightService;
54import net.floodlightcontroller.core.util.SingletonTask;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080055import net.floodlightcontroller.packet.BSN;
56import net.floodlightcontroller.packet.Ethernet;
57import net.floodlightcontroller.packet.IPv4;
58import net.floodlightcontroller.packet.LLDP;
59import net.floodlightcontroller.packet.LLDPTLV;
60import net.floodlightcontroller.restserver.IRestApiService;
61import net.floodlightcontroller.routing.Link;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080062import net.floodlightcontroller.threadpool.IThreadPoolService;
63import net.floodlightcontroller.topology.NodePortTuple;
64import net.floodlightcontroller.util.EventHistory;
65import net.floodlightcontroller.util.EventHistory.EvAction;
HIGUCHI Yuta7677a6f2013-06-14 14:13:35 -070066import net.onrc.onos.ofcontroller.core.IOnosRemoteSwitch;
HIGUCHI Yutaa56fbde2013-06-17 14:26:05 -070067import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery;
Jonathan Hart2fa28062013-11-25 20:16:28 -080068import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery.LDUpdate;
69import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscovery.UpdateOperation;
HIGUCHI Yutaa56fbde2013-06-17 14:26:05 -070070import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscoveryListener;
71import net.onrc.onos.ofcontroller.linkdiscovery.ILinkDiscoveryService;
72import net.onrc.onos.ofcontroller.linkdiscovery.LinkInfo;
HIGUCHI Yutaa56fbde2013-06-17 14:26:05 -070073import net.onrc.onos.ofcontroller.linkdiscovery.web.LinkDiscoveryWebRoutable;
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -070074import net.onrc.onos.registry.controller.IControllerRegistryService;
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -070075
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080076import org.openflow.protocol.OFMessage;
77import org.openflow.protocol.OFPacketIn;
78import org.openflow.protocol.OFPacketOut;
79import org.openflow.protocol.OFPhysicalPort;
80import org.openflow.protocol.OFPhysicalPort.OFPortConfig;
81import org.openflow.protocol.OFPhysicalPort.OFPortState;
82import org.openflow.protocol.OFPort;
83import org.openflow.protocol.OFPortStatus;
84import org.openflow.protocol.OFPortStatus.OFPortReason;
85import org.openflow.protocol.OFType;
86import org.openflow.protocol.action.OFAction;
87import org.openflow.protocol.action.OFActionOutput;
88import org.openflow.util.HexString;
89import org.slf4j.Logger;
90import org.slf4j.LoggerFactory;
91
92/**
93 * This class sends out LLDP messages containing the sending switch's datapath
94 * id as well as the outgoing port number. Received LLrescDP messages that
95 * match a known switch cause a new LinkTuple to be created according to the
96 * invariant rules listed below. This new LinkTuple is also passed to routing
97 * if it exists to trigger updates.
98 *
99 * This class also handles removing links that are associated to switch ports
100 * that go down, and switches that are disconnected.
101 *
102 * Invariants:
103 * -portLinks and switchLinks will not contain empty Sets outside of
104 * critical sections
105 * -portLinks contains LinkTuples where one of the src or dst
106 * SwitchPortTuple matches the map key
107 * -switchLinks contains LinkTuples where one of the src or dst
108 * SwitchPortTuple's id matches the switch id
109 * -Each LinkTuple will be indexed into switchLinks for both
110 * src.id and dst.id, and portLinks for each src and dst
111 * -The updates queue is only added to from within a held write lock
112 */
113@LogMessageCategory("Network Topology")
114public class LinkDiscoveryManager
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800115implements IOFMessageListener, IOFSwitchListener,
Jonathan Hartec4f14e2013-12-12 10:46:38 -0800116ILinkDiscoveryService, IFloodlightModule {
Pankaj Berdedc73bb12013-08-14 13:46:38 -0700117 protected IFloodlightProviderService controller;
Yuta HIGUCHI6ac8d182013-10-22 15:24:56 -0700118 protected final static Logger log = LoggerFactory.getLogger(LinkDiscoveryManager.class);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800119
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800120 protected IFloodlightProviderService floodlightProvider;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800121 protected IThreadPoolService threadPool;
122 protected IRestApiService restApi;
HIGUCHI Yuta30d03302013-06-14 13:47:36 -0700123 // Registry Service for ONOS
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -0700124 protected IControllerRegistryService registryService;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800125
HIGUCHI Yutae0515e52013-06-14 13:00:40 -0700126
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800127 // LLDP and BDDP fields
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800128 private static final byte[] LLDP_STANDARD_DST_MAC_STRING =
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800129 HexString.fromHexString("01:80:c2:00:00:0e");
130 private static final long LINK_LOCAL_MASK = 0xfffffffffff0L;
131 private static final long LINK_LOCAL_VALUE = 0x0180c2000000L;
132
133 // BigSwitch OUI is 5C:16:C7, so 5D:16:C7 is the multicast version
Masayoshi Kobayashi71137362013-07-12 15:54:52 -0700134 // private static final String LLDP_BSN_DST_MAC_STRING = "5d:16:c7:00:00:01";
135 private static final String LLDP_BSN_DST_MAC_STRING = "ff:ff:ff:ff:ff:ff";
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800136
137
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800138 // Direction TLVs are used to indicate if the LLDPs were sent
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800139 // periodically or in response to a recieved LLDP
140 private static final byte TLV_DIRECTION_TYPE = 0x73;
141 private static final short TLV_DIRECTION_LENGTH = 1; // 1 byte
142 private static final byte TLV_DIRECTION_VALUE_FORWARD[] = {0x01};
143 private static final byte TLV_DIRECTION_VALUE_REVERSE[] = {0x02};
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800144 private static final LLDPTLV forwardTLV
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800145 = new LLDPTLV().
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800146 setType(TLV_DIRECTION_TYPE).
147 setLength(TLV_DIRECTION_LENGTH).
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800148 setValue(TLV_DIRECTION_VALUE_FORWARD);
149
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800150 private static final LLDPTLV reverseTLV
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800151 = new LLDPTLV().
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800152 setType(TLV_DIRECTION_TYPE).
153 setLength(TLV_DIRECTION_LENGTH).
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800154 setValue(TLV_DIRECTION_VALUE_REVERSE);
155
156 // Link discovery task details.
157 protected SingletonTask discoveryTask;
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800158 protected final int DISCOVERY_TASK_INTERVAL = 1;
Umesh Krishnaswamy77601202013-04-03 21:46:01 -0700159 protected final int LINK_TIMEOUT = 35; // original 35 secs, aggressive 5 secs
160 protected final int LLDP_TO_ALL_INTERVAL = 15 ; //original 15 seconds, aggressive 2 secs.
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800161 protected long lldpClock = 0;
162 // This value is intentionally kept higher than LLDP_TO_ALL_INTERVAL.
163 // If we want to identify link failures faster, we could decrease this
164 // value to a small number, say 1 or 2 sec.
Umesh Krishnaswamy77601202013-04-03 21:46:01 -0700165 protected final int LLDP_TO_KNOWN_INTERVAL= 20; // LLDP frequency for known links
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800166
167 protected LLDPTLV controllerTLV;
168 protected ReentrantReadWriteLock lock;
169 int lldpTimeCount = 0;
HIGUCHI Yutae0515e52013-06-14 13:00:40 -0700170
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800171 /**
172 * Flag to indicate if automatic port fast is enabled or not.
173 * Default is set to false -- Initialized in the init method as well.
174 */
175 boolean autoPortFastFeature = false;
176
177 /**
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800178 * Map of remote switches that are not connected to this controller. This
HIGUCHI Yuta30d03302013-06-14 13:47:36 -0700179 * is used to learn remote switches in a distributed controller ONOS.
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800180 */
HIGUCHI Yuta7677a6f2013-06-14 14:13:35 -0700181 protected Map<Long, IOnosRemoteSwitch> remoteSwitches;
HIGUCHI Yuta3d96f652013-06-17 12:07:48 -0700182
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800183 /**
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800184 * Map from link to the most recent time it was verified functioning
185 */
186 protected Map<Link, LinkInfo> links;
187
188 /**
189 * Map from switch id to a set of all links with it as an endpoint
190 */
191 protected Map<Long, Set<Link>> switchLinks;
192
193 /**
194 * Map from a id:port to the set of links containing it as an endpoint
195 */
196 protected Map<NodePortTuple, Set<Link>> portLinks;
197
198 /**
199 * Set of link tuples over which multicast LLDPs are received
200 * and unicast LLDPs are not received.
201 */
202 protected Map<NodePortTuple, Set<Link>> portBroadcastDomainLinks;
203
204 protected volatile boolean shuttingDown = false;
205
206 /* topology aware components are called in the order they were added to the
207 * the array */
208 protected ArrayList<ILinkDiscoveryListener> linkDiscoveryAware;
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800209
Pankaj Berdedc73bb12013-08-14 13:46:38 -0700210 protected class LinkUpdate extends LDUpdate {
211
212 public LinkUpdate(LDUpdate old) {
213 super(old);
214 }
215 @LogMessageDoc(level="ERROR",
216 message="Error in link discovery updates loop",
217 explanation="An unknown error occured while dispatching " +
218 "link update notifications",
219 recommendation=LogMessageDoc.GENERIC_ACTION)
220 @Override
221 public void dispatch() {
Jonathan Hartb0904bf2013-11-26 14:41:11 -0800222 if (linkDiscoveryAware != null) {
223 if (log.isTraceEnabled()) {
224 log.trace("Dispatching link discovery update {} {} {} {} {} for {}",
225 new Object[]{this.getOperation(),
226 HexString.toHexString(this.getSrc()), this.getSrcPort(),
227 HexString.toHexString(this.getDst()), this.getDstPort(),
228 linkDiscoveryAware});
229 }
230 try {
231 for (ILinkDiscoveryListener lda : linkDiscoveryAware) { // order maintained
232 lda.linkDiscoveryUpdate(this);
233 }
234 }
235 catch (Exception e) {
236 log.error("Error in link discovery updates loop", e);
237 }
238 }
Pankaj Berdedc73bb12013-08-14 13:46:38 -0700239 }
Pankaj Berdedc73bb12013-08-14 13:46:38 -0700240 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800241
242 /**
243 * List of ports through which LLDP/BDDPs are not sent.
244 */
245 protected Set<NodePortTuple> suppressLinkDiscovery;
246
247 /** A list of ports that are quarantined for discovering links through
248 * them. Data traffic from these ports are not allowed until the ports
249 * are released from quarantine.
250 */
251 protected LinkedBlockingQueue<NodePortTuple> quarantineQueue;
252 protected LinkedBlockingQueue<NodePortTuple> maintenanceQueue;
253 /**
254 * Quarantine task
255 */
256 protected SingletonTask bddpTask;
257 protected final int BDDP_TASK_INTERVAL = 100; // 100 ms.
258 protected final int BDDP_TASK_SIZE = 5; // # of ports per iteration
259
260 /**
261 * Map of broadcast domain ports and the last time a BDDP was either
262 * sent or received on that port.
263 */
264 protected Map<NodePortTuple, Long> broadcastDomainPortTimeMap;
265
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800266 /**
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800267 * Get the LLDP sending period in seconds.
268 * @return LLDP sending period in seconds.
269 */
270 public int getLldpFrequency() {
271 return LLDP_TO_KNOWN_INTERVAL;
272 }
273
274 /**
275 * Get the LLDP timeout value in seconds
276 * @return LLDP timeout value in seconds
277 */
278 public int getLldpTimeout() {
279 return LINK_TIMEOUT;
280 }
281
282 public Map<NodePortTuple, Set<Link>> getPortLinks() {
283 return portLinks;
284 }
285
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800286 @Override
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800287 public Set<NodePortTuple> getSuppressLLDPsInfo() {
288 return suppressLinkDiscovery;
289 }
290
291 /**
292 * Add a switch port to the suppressed LLDP list.
293 * Remove any known links on the switch port.
294 */
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800295 @Override
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800296 public void AddToSuppressLLDPs(long sw, short port)
297 {
298 NodePortTuple npt = new NodePortTuple(sw, port);
299 this.suppressLinkDiscovery.add(npt);
300 deleteLinksOnPort(npt, "LLDP suppressed.");
301 }
302
303 /**
304 * Remove a switch port from the suppressed LLDP list.
305 * Discover links on that switchport.
306 */
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800307 @Override
308 public void RemoveFromSuppressLLDPs(long sw, short port)
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800309 {
310 NodePortTuple npt = new NodePortTuple(sw, port);
311 this.suppressLinkDiscovery.remove(npt);
312 discover(npt);
313 }
314
315 public boolean isShuttingDown() {
316 return shuttingDown;
317 }
318
319 public boolean isFastPort(long sw, short port) {
320 return false;
321 }
322
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800323 @Override
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800324 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
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800333
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
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800444 @Override
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800445 public Set<Short> getQuarantinedPorts(long sw) {
446 Set<Short> qPorts = new HashSet<Short>();
447
448 Iterator<NodePortTuple> iter = quarantineQueue.iterator();
449 while (iter.hasNext()) {
450 NodePortTuple npt = iter.next();
451 if (npt.getNodeId() == sw) {
452 qPorts.add(npt.getPortId());
453 }
454 }
455 return qPorts;
456 }
457
458 private void generateSwitchPortStatusUpdate(long sw, short port) {
459 UpdateOperation operation;
460
461 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
462 if (iofSwitch == null) return;
463
464 OFPhysicalPort ofp = iofSwitch.getPort(port);
465 if (ofp == null) return;
466
467 int srcPortState = ofp.getState();
468 boolean portUp = ((srcPortState &
469 OFPortState.OFPPS_STP_MASK.getValue()) !=
470 OFPortState.OFPPS_STP_BLOCK.getValue());
471
472 if (portUp) operation = UpdateOperation.PORT_UP;
473 else operation = UpdateOperation.PORT_DOWN;
474
Pankaj Berdedc73bb12013-08-14 13:46:38 -0700475 LinkUpdate update = new LinkUpdate(new LDUpdate(sw, port, operation));
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800476
477
Pankaj Berdedc73bb12013-08-14 13:46:38 -0700478 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800479 }
480
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800481 /**
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800482 * Send LLDP on known ports
483 */
484 protected void discoverOnKnownLinkPorts() {
485 // Copy the port set.
486 Set<NodePortTuple> nptSet = new HashSet<NodePortTuple>();
487 nptSet.addAll(portLinks.keySet());
488
489 // Send LLDP from each of them.
490 for(NodePortTuple npt: nptSet) {
491 discover(npt);
492 }
493 }
494
495 protected void discover(NodePortTuple npt) {
496 discover(npt.getNodeId(), npt.getPortId());
497 }
498
499 protected void discover(long sw, short port) {
500 sendDiscoveryMessage(sw, port, true, false);
501 }
502
503 /**
HIGUCHI Yuta30d03302013-06-14 13:47:36 -0700504 * Learn remote switches when running as a distributed controller ONOS
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800505 */
506 protected IOFSwitch addRemoteSwitch(long sw, short port) {
HIGUCHI Yuta7677a6f2013-06-14 14:13:35 -0700507 IOnosRemoteSwitch remotesw = null;
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800508
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800509 // add a switch if we have not seen it before
Umesh Krishnaswamy4c8e1082013-01-24 23:15:37 -0800510 remotesw = remoteSwitches.get(sw);
Jonathan Harte7231052013-01-25 00:01:14 -0800511
Pankaj Berdec125e622013-01-25 06:39:39 -0800512 if (remotesw == null) {
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800513 remotesw = new OFSwitchImpl();
514 remotesw.setupRemoteSwitch(sw);
515 remoteSwitches.put(remotesw.getId(), remotesw);
516 log.debug("addRemoteSwitch(): added fake remote sw {}", remotesw);
517 }
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800518
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800519 // add the port if we have not seen it before
Umesh Krishnaswamy68c118c2013-01-25 11:07:09 -0800520 if (remotesw.getPort(port) == null) {
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800521 OFPhysicalPort remoteport = new OFPhysicalPort();
522 remoteport.setPortNumber(port);
523 remoteport.setName("fake_" + port);
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800524 remoteport.setConfig(0);
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800525 remoteport.setState(0);
526 remotesw.setPort(remoteport);
Umesh Krishnaswamy82dcd982013-02-01 15:36:15 -0800527 log.debug("addRemoteSwitch(): added fake remote port {} to sw {}", remoteport, remotesw.getId());
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800528 }
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800529
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800530 return remotesw;
531 }
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800532
Umesh Krishnaswamyf962d642013-01-23 19:04:23 -0800533 /**
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800534 * Send link discovery message out of a given switch port.
535 * The discovery message may be a standard LLDP or a modified
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800536 * LLDP, where the dst mac address is set to :ff.
537 *
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800538 * TODO: The modified LLDP will updated in the future and may
539 * use a different eth-type.
540 * @param sw
541 * @param port
542 * @param isStandard indicates standard or modified LLDP
543 * @param isReverse indicates whether the LLDP was sent as a response
544 */
545 @LogMessageDoc(level="ERROR",
546 message="Failure sending LLDP out port {port} on switch {switch}",
547 explanation="An I/O error occured while sending LLDP message " +
548 "to the switch.",
549 recommendation=LogMessageDoc.CHECK_SWITCH)
550 protected void sendDiscoveryMessage(long sw, short port,
551 boolean isStandard,
552 boolean isReverse) {
553
554 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
555 if (iofSwitch == null) {
556 return;
557 }
558
559 if (port == OFPort.OFPP_LOCAL.getValue())
560 return;
561
562 OFPhysicalPort ofpPort = iofSwitch.getPort(port);
563
564 if (ofpPort == null) {
565 if (log.isTraceEnabled()) {
566 log.trace("Null physical port. sw={}, port={}", sw, port);
567 }
568 return;
569 }
570
571 if (isLinkDiscoverySuppressed(sw, port)) {
572 /* Dont send LLDPs out of this port as suppressLLDPs set
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800573 *
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800574 */
575 return;
576 }
577
578 // For fast ports, do not send forward LLDPs or BDDPs.
579 if (!isReverse && autoPortFastFeature && isFastPort(sw, port))
580 return;
581
582 if (log.isTraceEnabled()) {
583 log.trace("Sending LLDP packet out of swich: {}, port: {}",
584 sw, port);
585 }
586
587 // using "nearest customer bridge" MAC address for broadest possible propagation
588 // through provider and TPMR bridges (see IEEE 802.1AB-2009 and 802.1Q-2011),
589 // in particular the Linux bridge which behaves mostly like a provider bridge
590 byte[] chassisId = new byte[] {4, 0, 0, 0, 0, 0, 0}; // filled in later
591 byte[] portId = new byte[] {2, 0, 0}; // filled in later
592 byte[] ttlValue = new byte[] {0, 0x78};
593 // OpenFlow OUI - 00-26-E1
594 byte[] dpidTLVValue = new byte[] {0x0, 0x26, (byte) 0xe1, 0, 0, 0, 0, 0, 0, 0, 0, 0};
595 LLDPTLV dpidTLV = new LLDPTLV().setType((byte) 127).setLength((short) dpidTLVValue.length).setValue(dpidTLVValue);
596
597 byte[] dpidArray = new byte[8];
598 ByteBuffer dpidBB = ByteBuffer.wrap(dpidArray);
599 ByteBuffer portBB = ByteBuffer.wrap(portId, 1, 2);
600
601 Long dpid = sw;
602 dpidBB.putLong(dpid);
603 // set the ethernet source mac to last 6 bytes of dpid
604 System.arraycopy(dpidArray, 2, ofpPort.getHardwareAddress(), 0, 6);
605 // set the chassis id's value to last 6 bytes of dpid
606 System.arraycopy(dpidArray, 2, chassisId, 1, 6);
607 // set the optional tlv to the full dpid
608 System.arraycopy(dpidArray, 0, dpidTLVValue, 4, 8);
609
610
611 // set the portId to the outgoing port
612 portBB.putShort(port);
613 if (log.isTraceEnabled()) {
614 log.trace("Sending LLDP out of interface: {}/{}",
615 HexString.toHexString(sw), port);
616 }
617
618 LLDP lldp = new LLDP();
619 lldp.setChassisId(new LLDPTLV().setType((byte) 1).setLength((short) chassisId.length).setValue(chassisId));
620 lldp.setPortId(new LLDPTLV().setType((byte) 2).setLength((short) portId.length).setValue(portId));
621 lldp.setTtl(new LLDPTLV().setType((byte) 3).setLength((short) ttlValue.length).setValue(ttlValue));
622 lldp.getOptionalTLVList().add(dpidTLV);
623
624 // Add the controller identifier to the TLV value.
625 lldp.getOptionalTLVList().add(controllerTLV);
626 if (isReverse) {
627 lldp.getOptionalTLVList().add(reverseTLV);
628 }else {
629 lldp.getOptionalTLVList().add(forwardTLV);
630 }
631
632 Ethernet ethernet;
633 if (isStandard) {
634 ethernet = new Ethernet()
635 .setSourceMACAddress(ofpPort.getHardwareAddress())
636 .setDestinationMACAddress(LLDP_STANDARD_DST_MAC_STRING)
637 .setEtherType(Ethernet.TYPE_LLDP);
638 ethernet.setPayload(lldp);
639 } else {
640 BSN bsn = new BSN(BSN.BSN_TYPE_BDDP);
641 bsn.setPayload(lldp);
642
643 ethernet = new Ethernet()
644 .setSourceMACAddress(ofpPort.getHardwareAddress())
645 .setDestinationMACAddress(LLDP_BSN_DST_MAC_STRING)
646 .setEtherType(Ethernet.TYPE_BSN);
647 ethernet.setPayload(bsn);
648 }
649
650
651 // serialize and wrap in a packet out
652 byte[] data = ethernet.serialize();
653 OFPacketOut po = (OFPacketOut) floodlightProvider.getOFMessageFactory().getMessage(OFType.PACKET_OUT);
654 po.setBufferId(OFPacketOut.BUFFER_ID_NONE);
655 po.setInPort(OFPort.OFPP_NONE);
656
657 // set actions
658 List<OFAction> actions = new ArrayList<OFAction>();
659 actions.add(new OFActionOutput(port, (short) 0));
660 po.setActions(actions);
661 po.setActionsLength((short) OFActionOutput.MINIMUM_LENGTH);
662
663 // set data
664 po.setLengthU(OFPacketOut.MINIMUM_LENGTH + po.getActionsLength() + data.length);
665 po.setPacketData(data);
666
667 // send
668 try {
669 iofSwitch.write(po, null);
670 iofSwitch.flush();
671 } catch (IOException e) {
Yuta HIGUCHI5302ddf2014-01-06 12:53:35 -0800672 log.error("Failure sending LLDP out port "+port+" on switch "+iofSwitch.getStringId(), e);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800673 }
674
675 }
676
677 /**
678 * Send LLDPs to all switch-ports
679 */
680 protected void discoverOnAllPorts() {
681 if (log.isTraceEnabled()) {
Yuta HIGUCHI5302ddf2014-01-06 12:53:35 -0800682 log.trace("Sending LLDP packets out of all the enabled ports on switch");
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800683 }
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
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800889 // 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
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800892 // 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) {
Yuta HIGUCHIe8813402014-01-08 13:36:50 -0800935 Ethernet eth =
936 IFloodlightProviderService.bcStore.get(cntx,
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800937 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()) {
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001007 log.trace("addOrUpdateLink: {} {}",
1008 lt,
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001009 (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);
Yuta HIGUCHIe8813402014-01-08 13:36:50 -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
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001127 @Override
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001128 public Map<Long, Set<Link>> getSwitchLinks() {
1129 return this.switchLinks;
1130 }
1131
1132 /**
1133 * Removes links from memory and storage.
1134 * @param links The List of @LinkTuple to delete.
1135 */
1136 protected void deleteLinks(List<Link> links, String reason) {
1137 NodePortTuple srcNpt, dstNpt;
1138
1139 lock.writeLock().lock();
1140 try {
1141 for (Link lt : links) {
1142 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1143 dstNpt =new NodePortTuple(lt.getDst(), lt.getDstPort());
1144
1145 switchLinks.get(lt.getSrc()).remove(lt);
1146 switchLinks.get(lt.getDst()).remove(lt);
1147 if (switchLinks.containsKey(lt.getSrc()) &&
1148 switchLinks.get(lt.getSrc()).isEmpty())
1149 this.switchLinks.remove(lt.getSrc());
1150 if (this.switchLinks.containsKey(lt.getDst()) &&
1151 this.switchLinks.get(lt.getDst()).isEmpty())
1152 this.switchLinks.remove(lt.getDst());
1153
1154 if (this.portLinks.get(srcNpt) != null) {
1155 this.portLinks.get(srcNpt).remove(lt);
1156 if (this.portLinks.get(srcNpt).isEmpty())
1157 this.portLinks.remove(srcNpt);
1158 }
1159 if (this.portLinks.get(dstNpt) != null) {
1160 this.portLinks.get(dstNpt).remove(lt);
1161 if (this.portLinks.get(dstNpt).isEmpty())
1162 this.portLinks.remove(dstNpt);
1163 }
1164
1165 LinkInfo info = this.links.remove(lt);
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001166 LinkUpdate update = new LinkUpdate(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001167 lt.getDst(), lt.getDstPort(),
1168 getLinkType(lt, info),
1169 UpdateOperation.LINK_REMOVED));
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001170 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001171
1172 // Update Event History
1173 evHistTopoLink(lt.getSrc(),
1174 lt.getDst(),
1175 lt.getSrcPort(),
1176 lt.getDstPort(),
1177 0, 0, // Port states
1178 ILinkDiscovery.LinkType.INVALID_LINK,
1179 EvAction.LINK_DELETED, reason);
1180
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001181 // TODO Whenever link is removed, it has to checked if
1182 // the switchports must be added to quarantine.
1183
1184 if (log.isTraceEnabled()) {
1185 log.trace("Deleted link {}", lt);
1186 }
1187 }
1188 } finally {
1189 lock.writeLock().unlock();
1190 }
1191 }
1192
1193 /**
1194 * Handles an OFPortStatus message from a switch. We will add or
1195 * delete LinkTupes as well re-compute the topology if needed.
1196 * @param sw The IOFSwitch that sent the port status message
1197 * @param ps The OFPortStatus message
1198 * @return The Command to continue or stop after we process this message
1199 */
1200 protected Command handlePortStatus(long sw, OFPortStatus ps) {
1201
1202 IOFSwitch iofSwitch = floodlightProvider.getSwitches().get(sw);
1203 if (iofSwitch == null) return Command.CONTINUE;
HIGUCHI Yutaa89b2842013-06-17 13:54:57 -07001204
HIGUCHI Yuta30d03302013-06-14 13:47:36 -07001205 // ONOS: If we do not control this switch, then we should not process its port status messages
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -07001206 if (!registryService.hasControl(iofSwitch.getId())) return Command.CONTINUE;
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001207
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001208 if (log.isTraceEnabled()) {
1209 log.trace("handlePortStatus: Switch {} port #{} reason {}; " +
1210 "config is {} state is {}",
1211 new Object[] {iofSwitch.getStringId(),
1212 ps.getDesc().getPortNumber(),
1213 ps.getReason(),
1214 ps.getDesc().getConfig(),
1215 ps.getDesc().getState()});
1216 }
1217
1218 short port = ps.getDesc().getPortNumber();
1219 NodePortTuple npt = new NodePortTuple(sw, port);
1220 boolean linkDeleted = false;
1221 boolean linkInfoChanged = false;
1222
1223 lock.writeLock().lock();
1224 try {
1225 // if ps is a delete, or a modify where the port is down or
1226 // configured down
1227 if ((byte)OFPortReason.OFPPR_DELETE.ordinal() == ps.getReason() ||
1228 ((byte)OFPortReason.OFPPR_MODIFY.ordinal() ==
1229 ps.getReason() && !portEnabled(ps.getDesc()))) {
1230 deleteLinksOnPort(npt, "Port Status Changed");
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001231 LinkUpdate update = new LinkUpdate(new LDUpdate(sw, port, UpdateOperation.PORT_DOWN));
1232 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001233 linkDeleted = true;
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001234 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001235 else if (ps.getReason() ==
1236 (byte)OFPortReason.OFPPR_MODIFY.ordinal()) {
1237 // If ps is a port modification and the port state has changed
1238 // that affects links in the topology
1239
1240 if (this.portLinks.containsKey(npt)) {
1241 for (Link lt: this.portLinks.get(npt)) {
1242 LinkInfo linkInfo = links.get(lt);
1243 assert(linkInfo != null);
1244 Integer updatedSrcPortState = null;
1245 Integer updatedDstPortState = null;
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001246 if (lt.getSrc() == npt.getNodeId() &&
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001247 lt.getSrcPort() == npt.getPortId() &&
1248 (linkInfo.getSrcPortState() !=
1249 ps.getDesc().getState())) {
1250 updatedSrcPortState = ps.getDesc().getState();
1251 linkInfo.setSrcPortState(updatedSrcPortState);
1252 }
1253 if (lt.getDst() == npt.getNodeId() &&
1254 lt.getDstPort() == npt.getPortId() &&
1255 (linkInfo.getDstPortState() !=
1256 ps.getDesc().getState())) {
1257 updatedDstPortState = ps.getDesc().getState();
1258 linkInfo.setDstPortState(updatedDstPortState);
1259 }
1260 if ((updatedSrcPortState != null) ||
1261 (updatedDstPortState != null)) {
1262 // The link is already known to link discovery
1263 // manager and the status has changed, therefore
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001264 // send an LinkUpdate.
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001265 UpdateOperation operation =
1266 getUpdateOperation(linkInfo.getSrcPortState(),
1267 linkInfo.getDstPortState());
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001268 LinkUpdate update = new LinkUpdate(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001269 lt.getDst(), lt.getDstPort(),
1270 getLinkType(lt, linkInfo),
1271 operation));
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001272 controller.publishUpdate(update);
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001273
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001274 linkInfoChanged = true;
1275 }
1276 }
1277 }
1278
1279 UpdateOperation operation =
1280 getUpdateOperation(ps.getDesc().getState());
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001281 LinkUpdate update = new LinkUpdate(new LDUpdate(sw, port, operation));
1282 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001283 }
1284
1285 if (!linkDeleted && !linkInfoChanged){
1286 if (log.isTraceEnabled()) {
1287 log.trace("handlePortStatus: Switch {} port #{} reason {};"+
1288 " no links to update/remove",
1289 new Object[] {HexString.toHexString(sw),
1290 ps.getDesc().getPortNumber(),
1291 ps.getReason()});
1292 }
1293 }
1294 } finally {
1295 lock.writeLock().unlock();
1296 }
1297
1298 if (!linkDeleted) {
1299 // Send LLDP right away when port state is changed for faster
1300 // cluster-merge. If it is a link delete then there is not need
1301 // to send the LLDPs right away and instead we wait for the LLDPs
1302 // to be sent on the timer as it is normally done
1303 // do it outside the write-lock
1304 // sendLLDPTask.reschedule(1000, TimeUnit.MILLISECONDS);
1305 processNewPort(npt.getNodeId(), npt.getPortId());
1306 }
1307 return Command.CONTINUE;
1308 }
1309
1310 /**
1311 * Process a new port.
1312 * If link discovery is disabled on the port, then do nothing.
1313 * If autoportfast feature is enabled and the port is a fast port, then
1314 * do nothing.
1315 * Otherwise, send LLDP message. Add the port to quarantine.
1316 * @param sw
1317 * @param p
1318 */
1319 private void processNewPort(long sw, short p) {
1320 if (isLinkDiscoverySuppressed(sw, p)) {
1321 // Do nothing as link discovery is suppressed.
1322 }
1323 else if (autoPortFastFeature && isFastPort(sw, p)) {
1324 // Do nothing as the port is a fast port.
1325 }
1326 else {
1327 NodePortTuple npt = new NodePortTuple(sw, p);
1328 discover(sw, p);
1329 // if it is not a fast port, add it to quarantine.
1330 if (!isFastPort(sw, p)) {
1331 addToQuarantineQueue(npt);
1332 } else {
1333 // Add to maintenance queue to ensure that BDDP packets
1334 // are sent out.
1335 addToMaintenanceQueue(npt);
1336 }
1337 }
1338 }
1339
1340 /**
1341 * We send out LLDP messages when a switch is added to discover the topology
1342 * @param sw The IOFSwitch that connected to the controller
1343 */
1344 @Override
1345 public void addedSwitch(IOFSwitch sw) {
1346
1347 if (sw.getEnabledPorts() != null) {
1348 for (Short p : sw.getEnabledPortNumbers()) {
1349 processNewPort(sw.getId(), p);
1350 }
1351 }
1352 // Update event history
1353 evHistTopoSwitch(sw, EvAction.SWITCH_CONNECTED, "None");
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001354 LinkUpdate update = new LinkUpdate(new LDUpdate(sw.getId(), null,
1355 UpdateOperation.SWITCH_UPDATED));
1356 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001357 }
1358
1359 /**
1360 * When a switch disconnects we remove any links from our map and notify.
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001361 */
1362 @Override
1363 public void removedSwitch(IOFSwitch iofSwitch) {
1364 // Update event history
1365 long sw = iofSwitch.getId();
1366 evHistTopoSwitch(iofSwitch, EvAction.SWITCH_DISCONNECTED, "None");
1367 List<Link> eraseList = new ArrayList<Link>();
1368 lock.writeLock().lock();
1369 try {
1370 if (switchLinks.containsKey(sw)) {
1371 if (log.isTraceEnabled()) {
1372 log.trace("Handle switchRemoved. Switch {}; removing links {}",
1373 HexString.toHexString(sw), switchLinks.get(sw));
1374 }
1375 // add all tuples with an endpoint on this switch to erase list
1376 eraseList.addAll(switchLinks.get(sw));
HIGUCHI Yutaa89b2842013-06-17 13:54:57 -07001377 deleteLinks(eraseList, "Switch Removed");
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001378
1379 // Send a switch removed update
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001380 LinkUpdate update = new LinkUpdate(new LDUpdate(sw, null, UpdateOperation.SWITCH_REMOVED));
1381 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001382 }
1383 } finally {
1384 lock.writeLock().unlock();
1385 }
1386 }
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001387
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001388 /**
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001389 * We don't react the port changed notifications here. we listen for
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001390 * OFPortStatus messages directly. Might consider using this notifier
1391 * instead
1392 */
1393 @Override
1394 public void switchPortChanged(Long switchId) {
1395 // no-op
1396 }
1397
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001398 /**
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001399 * Delete links incident on a given switch port.
1400 * @param npt
1401 * @param reason
1402 */
1403 protected void deleteLinksOnPort(NodePortTuple npt, String reason) {
1404 List<Link> eraseList = new ArrayList<Link>();
1405 if (this.portLinks.containsKey(npt)) {
1406 if (log.isTraceEnabled()) {
1407 log.trace("handlePortStatus: Switch {} port #{} " +
1408 "removing links {}",
1409 new Object[] {HexString.toHexString(npt.getNodeId()),
1410 npt.getPortId(),
1411 this.portLinks.get(npt)});
1412 }
1413 eraseList.addAll(this.portLinks.get(npt));
1414 deleteLinks(eraseList, reason);
1415 }
1416 }
1417
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001418 /**
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001419 * Iterates through the list of links and deletes if the
1420 * last discovery message reception time exceeds timeout values.
1421 */
1422 protected void timeoutLinks() {
1423 List<Link> eraseList = new ArrayList<Link>();
1424 Long curTime = System.currentTimeMillis();
1425 boolean linkChanged = false;
1426
1427 // reentrant required here because deleteLink also write locks
1428 lock.writeLock().lock();
1429 try {
1430 Iterator<Entry<Link, LinkInfo>> it =
1431 this.links.entrySet().iterator();
1432 while (it.hasNext()) {
1433 Entry<Link, LinkInfo> entry = it.next();
1434 Link lt = entry.getKey();
1435 LinkInfo info = entry.getValue();
1436
1437 // Timeout the unicast and multicast LLDP valid times
1438 // independently.
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001439 if ((info.getUnicastValidTime() != null) &&
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001440 (info.getUnicastValidTime() + (this.LINK_TIMEOUT * 1000) < curTime)){
1441 info.setUnicastValidTime(null);
1442
1443 if (info.getMulticastValidTime() != null)
1444 addLinkToBroadcastDomain(lt);
1445 // Note that even if mTime becomes null later on,
1446 // the link would be deleted, which would trigger updateClusters().
1447 linkChanged = true;
1448 }
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001449 if ((info.getMulticastValidTime()!= null) &&
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001450 (info.getMulticastValidTime()+ (this.LINK_TIMEOUT * 1000) < curTime)) {
1451 info.setMulticastValidTime(null);
1452 // if uTime is not null, then link will remain as openflow
1453 // link. If uTime is null, it will be deleted. So, we
1454 // don't care about linkChanged flag here.
1455 removeLinkFromBroadcastDomain(lt);
1456 linkChanged = true;
1457 }
1458 // Add to the erase list only if the unicast
1459 // time is null.
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001460 if (info.getUnicastValidTime() == null &&
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001461 info.getMulticastValidTime() == null){
1462 eraseList.add(entry.getKey());
1463 } else if (linkChanged) {
1464 UpdateOperation operation;
1465 operation = getUpdateOperation(info.getSrcPortState(),
1466 info.getDstPortState());
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001467 LinkUpdate update = new LinkUpdate(new LDUpdate(lt.getSrc(), lt.getSrcPort(),
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001468 lt.getDst(), lt.getDstPort(),
1469 getLinkType(lt, info),
1470 operation));
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001471 controller.publishUpdate(update);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001472 }
1473 }
1474
1475 // if any link was deleted or any link was changed.
1476 if ((eraseList.size() > 0) || linkChanged) {
1477 deleteLinks(eraseList, "LLDP timeout");
1478 }
1479 } finally {
1480 lock.writeLock().unlock();
1481 }
1482 }
1483
1484 private boolean portEnabled(OFPhysicalPort port) {
1485 if (port == null)
1486 return false;
1487 if ((OFPortConfig.OFPPC_PORT_DOWN.getValue() & port.getConfig()) > 0)
1488 return false;
1489 if ((OFPortState.OFPPS_LINK_DOWN.getValue() & port.getState()) > 0)
1490 return false;
1491 // Port STP state doesn't work with multiple VLANs, so ignore it for now
1492 // if ((port.getState() & OFPortState.OFPPS_STP_MASK.getValue()) == OFPortState.OFPPS_STP_BLOCK.getValue())
1493 // return false;
1494 return true;
1495 }
1496
1497 public Map<NodePortTuple, Set<Link>> getPortBroadcastDomainLinks() {
1498 return portBroadcastDomainLinks;
1499 }
1500
1501 @Override
1502 public Map<Link, LinkInfo> getLinks() {
1503 lock.readLock().lock();
1504 Map<Link, LinkInfo> result;
1505 try {
1506 result = new HashMap<Link, LinkInfo>(links);
1507 } finally {
1508 lock.readLock().unlock();
1509 }
1510 return result;
1511 }
1512
1513 protected void addLinkToBroadcastDomain(Link lt) {
1514
1515 NodePortTuple srcNpt, dstNpt;
1516 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1517 dstNpt = new NodePortTuple(lt.getDst(), lt.getDstPort());
1518
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001519 if (!portBroadcastDomainLinks.containsKey(srcNpt))
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001520 portBroadcastDomainLinks.put(srcNpt, new HashSet<Link>());
1521 portBroadcastDomainLinks.get(srcNpt).add(lt);
1522
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001523 if (!portBroadcastDomainLinks.containsKey(dstNpt))
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001524 portBroadcastDomainLinks.put(dstNpt, new HashSet<Link>());
1525 portBroadcastDomainLinks.get(dstNpt).add(lt);
1526 }
1527
1528 protected void removeLinkFromBroadcastDomain(Link lt) {
1529
1530 NodePortTuple srcNpt, dstNpt;
1531 srcNpt = new NodePortTuple(lt.getSrc(), lt.getSrcPort());
1532 dstNpt = new NodePortTuple(lt.getDst(), lt.getDstPort());
1533
1534 if (portBroadcastDomainLinks.containsKey(srcNpt)) {
1535 portBroadcastDomainLinks.get(srcNpt).remove(lt);
1536 if (portBroadcastDomainLinks.get(srcNpt).isEmpty())
1537 portBroadcastDomainLinks.remove(srcNpt);
1538 }
1539
1540 if (portBroadcastDomainLinks.containsKey(dstNpt)) {
1541 portBroadcastDomainLinks.get(dstNpt).remove(lt);
1542 if (portBroadcastDomainLinks.get(dstNpt).isEmpty())
1543 portBroadcastDomainLinks.remove(dstNpt);
1544 }
1545 }
1546
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001547 @Override
1548 public void addListener(ILinkDiscoveryListener listener) {
1549 linkDiscoveryAware.add(listener);
1550 }
1551
1552 /**
1553 * Register a link discovery aware component
1554 * @param linkDiscoveryAwareComponent
1555 */
1556 public void addLinkDiscoveryAware(ILinkDiscoveryListener linkDiscoveryAwareComponent) {
1557 // TODO make this a copy on write set or lock it somehow
1558 this.linkDiscoveryAware.add(linkDiscoveryAwareComponent);
1559 }
1560
1561 /**
1562 * Deregister a link discovery aware component
1563 * @param linkDiscoveryAwareComponent
1564 */
1565 public void removeLinkDiscoveryAware(ILinkDiscoveryListener linkDiscoveryAwareComponent) {
1566 // TODO make this a copy on write set or lock it somehow
1567 this.linkDiscoveryAware.remove(linkDiscoveryAwareComponent);
1568 }
1569
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001570 @Override
1571 public boolean isCallbackOrderingPrereq(OFType type, String name) {
1572 return false;
1573 }
1574
1575 @Override
1576 public boolean isCallbackOrderingPostreq(OFType type, String name) {
1577 return false;
1578 }
1579
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001580 // IFloodlightModule classes
1581
1582 @Override
1583 public Collection<Class<? extends IFloodlightService>> getModuleServices() {
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001584 Collection<Class<? extends IFloodlightService>> l =
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001585 new ArrayList<Class<? extends IFloodlightService>>();
1586 l.add(ILinkDiscoveryService.class);
1587 //l.add(ITopologyService.class);
1588 return l;
1589 }
1590
1591 @Override
1592 public Map<Class<? extends IFloodlightService>, IFloodlightService>
1593 getServiceImpls() {
1594 Map<Class<? extends IFloodlightService>,
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001595 IFloodlightService> m =
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001596 new HashMap<Class<? extends IFloodlightService>,
1597 IFloodlightService>();
1598 // We are the class that implements the service
1599 m.put(ILinkDiscoveryService.class, this);
1600 return m;
1601 }
1602
1603 @Override
1604 public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001605 Collection<Class<? extends IFloodlightService>> l =
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001606 new ArrayList<Class<? extends IFloodlightService>>();
1607 l.add(IFloodlightProviderService.class);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001608 l.add(IThreadPoolService.class);
1609 l.add(IRestApiService.class);
HIGUCHI Yuta30d03302013-06-14 13:47:36 -07001610 // Added by ONOS
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -07001611 l.add(IControllerRegistryService.class);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001612 return l;
1613 }
1614
1615 @Override
1616 public void init(FloodlightModuleContext context)
1617 throws FloodlightModuleException {
1618 floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001619 threadPool = context.getServiceImpl(IThreadPoolService.class);
1620 restApi = context.getServiceImpl(IRestApiService.class);
HIGUCHI Yuta30d03302013-06-14 13:47:36 -07001621 // Added by ONOS
Umesh Krishnaswamy57a32a92013-03-21 14:21:15 -07001622 registryService = context.getServiceImpl(IControllerRegistryService.class);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001623
1624 // Set the autoportfast feature to false.
1625 this.autoPortFastFeature = false;
1626
1627 // We create this here because there is no ordering guarantee
1628 this.linkDiscoveryAware = new ArrayList<ILinkDiscoveryListener>();
1629 this.lock = new ReentrantReadWriteLock();
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001630 this.links = new HashMap<Link, LinkInfo>();
1631 this.portLinks = new HashMap<NodePortTuple, Set<Link>>();
1632 this.suppressLinkDiscovery =
1633 Collections.synchronizedSet(new HashSet<NodePortTuple>());
1634 this.portBroadcastDomainLinks = new HashMap<NodePortTuple, Set<Link>>();
1635 this.switchLinks = new HashMap<Long, Set<Link>>();
1636 this.quarantineQueue = new LinkedBlockingQueue<NodePortTuple>();
1637 this.maintenanceQueue = new LinkedBlockingQueue<NodePortTuple>();
HIGUCHI Yuta30d03302013-06-14 13:47:36 -07001638 // Added by ONOS
HIGUCHI Yuta7677a6f2013-06-14 14:13:35 -07001639 this.remoteSwitches = new HashMap<Long, IOnosRemoteSwitch>();
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001640
1641 this.evHistTopologySwitch =
1642 new EventHistory<EventHistoryTopologySwitch>("Topology: Switch");
1643 this.evHistTopologyLink =
1644 new EventHistory<EventHistoryTopologyLink>("Topology: Link");
1645 this.evHistTopologyCluster =
1646 new EventHistory<EventHistoryTopologyCluster>("Topology: Cluster");
1647 }
1648
1649 @Override
1650 @LogMessageDocs({
1651 @LogMessageDoc(level="ERROR",
1652 message="No storage source found.",
1653 explanation="Storage source was not initialized; cannot initialize " +
1654 "link discovery.",
1655 recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
1656 @LogMessageDoc(level="ERROR",
1657 message="Error in installing listener for " +
1658 "switch config table {table}",
1659 explanation="Failed to install storage notification for the " +
1660 "switch config table",
1661 recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
1662 @LogMessageDoc(level="ERROR",
1663 message="No storage source found.",
1664 explanation="Storage source was not initialized; cannot initialize " +
1665 "link discovery.",
1666 recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG),
1667 @LogMessageDoc(level="ERROR",
1668 message="Exception in LLDP send timer.",
1669 explanation="An unknown error occured while sending LLDP " +
1670 "messages to switches.",
1671 recommendation=LogMessageDoc.CHECK_SWITCH)
1672 })
1673 public void startUp(FloodlightModuleContext context) {
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001674 ScheduledExecutorService ses = threadPool.getScheduledExecutor();
Pankaj Berdedc73bb12013-08-14 13:46:38 -07001675 controller =
1676 context.getServiceImpl(IFloodlightProviderService.class);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001677
1678 // To be started by the first switch connection
1679 discoveryTask = new SingletonTask(ses, new Runnable() {
1680 @Override
1681 public void run() {
1682 try {
1683 discoverLinks();
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001684 } catch (Exception e) {
1685 log.error("Exception in LLDP send timer.", e);
1686 } finally {
1687 if (!shuttingDown) {
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001688 // Always reschedule link discovery if we're not
Jonathan Hartec4f14e2013-12-12 10:46:38 -08001689 // shutting down (no chance of SLAVE role now)
1690 log.trace("Rescheduling discovery task");
1691 discoveryTask.reschedule(DISCOVERY_TASK_INTERVAL,
1692 TimeUnit.SECONDS);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001693 }
1694 }
1695 }
1696 });
1697
Jonathan Hartec4f14e2013-12-12 10:46:38 -08001698 // Always reschedule link discovery as we are never in SLAVE role now
1699 discoveryTask.reschedule(DISCOVERY_TASK_INTERVAL, TimeUnit.SECONDS);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001700
1701 // Setup the BDDP task. It is invoked whenever switch port tuples
1702 // are added to the quarantine list.
1703 bddpTask = new SingletonTask(ses, new QuarantineWorker());
1704 bddpTask.reschedule(BDDP_TASK_INTERVAL, TimeUnit.MILLISECONDS);
1705
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001706
1707 // Register for the OpenFlow messages we want to receive
1708 floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
1709 floodlightProvider.addOFMessageListener(OFType.PORT_STATUS, this);
1710 // Register for switch updates
1711 floodlightProvider.addOFSwitchListener(this);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001712 if (restApi != null)
1713 restApi.addRestletRoutable(new LinkDiscoveryWebRoutable());
1714 setControllerTLV();
1715 }
1716
1717 // ****************************************************
1718 // Topology Manager's Event History members and methods
1719 // ****************************************************
1720
1721 // Topology Manager event history
1722 public EventHistory<EventHistoryTopologySwitch> evHistTopologySwitch;
1723 public EventHistory<EventHistoryTopologyLink> evHistTopologyLink;
1724 public EventHistory<EventHistoryTopologyCluster> evHistTopologyCluster;
1725 public EventHistoryTopologySwitch evTopoSwitch;
1726 public EventHistoryTopologyLink evTopoLink;
1727 public EventHistoryTopologyCluster evTopoCluster;
1728
1729 // Switch Added/Deleted
1730 private void evHistTopoSwitch(IOFSwitch sw, EvAction actn, String reason) {
1731 if (evTopoSwitch == null) {
1732 evTopoSwitch = new EventHistoryTopologySwitch();
1733 }
1734 evTopoSwitch.dpid = sw.getId();
1735 if ((sw.getChannel() != null) &&
1736 (SocketAddress.class.isInstance(
1737 sw.getChannel().getRemoteAddress()))) {
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001738 evTopoSwitch.ipv4Addr =
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001739 IPv4.toIPv4Address(((InetSocketAddress)(sw.getChannel().
1740 getRemoteAddress())).getAddress().getAddress());
1741 evTopoSwitch.l4Port =
1742 ((InetSocketAddress)(sw.getChannel().
1743 getRemoteAddress())).getPort();
1744 } else {
1745 evTopoSwitch.ipv4Addr = 0;
1746 evTopoSwitch.l4Port = 0;
1747 }
1748 evTopoSwitch.reason = reason;
1749 evTopoSwitch = evHistTopologySwitch.put(evTopoSwitch, actn);
1750 }
1751
1752 private void evHistTopoLink(long srcDpid, long dstDpid, short srcPort,
1753 short dstPort, int srcPortState, int dstPortState,
1754 ILinkDiscovery.LinkType linkType,
1755 EvAction actn, String reason) {
1756 if (evTopoLink == null) {
1757 evTopoLink = new EventHistoryTopologyLink();
1758 }
1759 evTopoLink.srcSwDpid = srcDpid;
1760 evTopoLink.dstSwDpid = dstDpid;
1761 evTopoLink.srcSwport = srcPort & 0xffff;
1762 evTopoLink.dstSwport = dstPort & 0xffff;
1763 evTopoLink.srcPortState = srcPortState;
1764 evTopoLink.dstPortState = dstPortState;
1765 evTopoLink.reason = reason;
1766 switch (linkType) {
1767 case DIRECT_LINK:
1768 evTopoLink.linkType = "DIRECT_LINK";
1769 break;
1770 case MULTIHOP_LINK:
1771 evTopoLink.linkType = "MULTIHOP_LINK";
1772 break;
1773 case TUNNEL:
1774 evTopoLink.linkType = "TUNNEL";
1775 break;
1776 case INVALID_LINK:
1777 default:
1778 evTopoLink.linkType = "Unknown";
1779 break;
1780 }
1781 evTopoLink = evHistTopologyLink.put(evTopoLink, actn);
1782 }
1783
1784 public void evHistTopoCluster(long dpid, long clusterIdOld,
1785 long clusterIdNew, EvAction action, String reason) {
1786 if (evTopoCluster == null) {
1787 evTopoCluster = new EventHistoryTopologyCluster();
1788 }
1789 evTopoCluster.dpid = dpid;
1790 evTopoCluster.clusterIdOld = clusterIdOld;
1791 evTopoCluster.clusterIdNew = clusterIdNew;
1792 evTopoCluster.reason = reason;
1793 evTopoCluster = evHistTopologyCluster.put(evTopoCluster, action);
1794 }
1795
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001796 @Override
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001797 public boolean isAutoPortFastFeature() {
1798 return autoPortFastFeature;
1799 }
1800
Yuta HIGUCHIe8813402014-01-08 13:36:50 -08001801 @Override
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001802 public void setAutoPortFastFeature(boolean autoPortFastFeature) {
1803 this.autoPortFastFeature = autoPortFastFeature;
1804 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001805}