blob: 20ad566c7a5529393d64e10a1232a3dc51c1d35a [file] [log] [blame]
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001/**
2* Copyright 2011, Big Switch Networks, Inc.
3* Originally created by David Erickson, Stanford University
4*
5* Licensed under the Apache License, Version 2.0 (the "License"); you may
6* not use this file except in compliance with the License. You may obtain
7* a copy of the License at
8*
9* http://www.apache.org/licenses/LICENSE-2.0
10*
11* Unless required by applicable law or agreed to in writing, software
12* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14* License for the specific language governing permissions and limitations
15* under the License.
16**/
17
18package net.floodlightcontroller.core.internal;
19
20import java.io.FileInputStream;
21import java.io.IOException;
22import java.net.InetAddress;
23import java.net.InetSocketAddress;
24import java.net.SocketAddress;
Jonathan Hartd10008d2013-02-23 17:04:08 -080025import java.net.UnknownHostException;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080026import java.nio.channels.ClosedChannelException;
Jonathan Hartd10008d2013-02-23 17:04:08 -080027import java.util.ArrayList;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080028import java.util.Collection;
29import java.util.Collections;
30import java.util.Date;
31import java.util.HashMap;
32import java.util.HashSet;
33import java.util.Iterator;
34import java.util.LinkedHashMap;
35import java.util.List;
36import java.util.Map;
37import java.util.Map.Entry;
38import java.util.Properties;
39import java.util.Set;
40import java.util.Stack;
41import java.util.concurrent.BlockingQueue;
42import java.util.concurrent.ConcurrentHashMap;
43import java.util.concurrent.ConcurrentMap;
44import java.util.concurrent.CopyOnWriteArraySet;
45import java.util.concurrent.Executors;
46import java.util.concurrent.Future;
47import java.util.concurrent.LinkedBlockingQueue;
48import java.util.concurrent.RejectedExecutionException;
49import java.util.concurrent.TimeUnit;
50import java.util.concurrent.TimeoutException;
51
52import net.floodlightcontroller.core.FloodlightContext;
53import net.floodlightcontroller.core.IFloodlightProviderService;
54import net.floodlightcontroller.core.IHAListener;
55import net.floodlightcontroller.core.IInfoProvider;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080056import net.floodlightcontroller.core.IListener.Command;
Jonathan Hartd10008d2013-02-23 17:04:08 -080057import net.floodlightcontroller.core.INetMapStorage.DM_OPERATION;
58import net.floodlightcontroller.core.INetMapTopologyService.ITopoRouteService;
59import net.floodlightcontroller.core.IOFMessageListener;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080060import net.floodlightcontroller.core.IOFSwitch;
61import net.floodlightcontroller.core.IOFSwitchFilter;
62import net.floodlightcontroller.core.IOFSwitchListener;
Pankaj Berde8557a462013-01-07 08:59:31 -080063import net.floodlightcontroller.core.ISwitchStorage.SwitchState;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080064import net.floodlightcontroller.core.annotations.LogMessageDoc;
65import net.floodlightcontroller.core.annotations.LogMessageDocs;
66import net.floodlightcontroller.core.internal.OFChannelState.HandshakeState;
67import net.floodlightcontroller.core.util.ListenerDispatcher;
68import net.floodlightcontroller.core.web.CoreWebRoutable;
69import net.floodlightcontroller.counter.ICounterStoreService;
Pavlin Radoslavov19b0e122013-02-21 18:47:38 -080070import net.floodlightcontroller.flowcache.IFlowService;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080071import net.floodlightcontroller.packet.Ethernet;
72import net.floodlightcontroller.perfmon.IPktInProcessingTimeService;
73import net.floodlightcontroller.restserver.IRestApiService;
74import net.floodlightcontroller.storage.IResultSet;
75import net.floodlightcontroller.storage.IStorageSourceListener;
76import net.floodlightcontroller.storage.IStorageSourceService;
77import net.floodlightcontroller.storage.OperatorPredicate;
78import net.floodlightcontroller.storage.StorageException;
79import net.floodlightcontroller.threadpool.IThreadPoolService;
Jonathan Hartd82f20d2013-02-21 18:04:24 -080080import net.onrc.onos.registry.controller.IControllerRegistryService;
Jonathan Hartcc957a02013-02-26 10:39:04 -080081import net.onrc.onos.registry.controller.IControllerRegistryService.ControlChangeCallback;
Jonathan Hartd10008d2013-02-23 17:04:08 -080082import net.onrc.onos.registry.controller.RegistryException;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -080083
84import org.jboss.netty.bootstrap.ServerBootstrap;
85import org.jboss.netty.buffer.ChannelBuffer;
86import org.jboss.netty.buffer.ChannelBuffers;
87import org.jboss.netty.channel.Channel;
88import org.jboss.netty.channel.ChannelHandlerContext;
89import org.jboss.netty.channel.ChannelPipelineFactory;
90import org.jboss.netty.channel.ChannelStateEvent;
91import org.jboss.netty.channel.ChannelUpstreamHandler;
92import org.jboss.netty.channel.Channels;
93import org.jboss.netty.channel.ExceptionEvent;
94import org.jboss.netty.channel.MessageEvent;
95import org.jboss.netty.channel.group.ChannelGroup;
96import org.jboss.netty.channel.group.DefaultChannelGroup;
97import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
98import org.jboss.netty.handler.timeout.IdleStateAwareChannelUpstreamHandler;
99import org.jboss.netty.handler.timeout.IdleStateEvent;
100import org.jboss.netty.handler.timeout.ReadTimeoutException;
101import org.openflow.protocol.OFEchoReply;
102import org.openflow.protocol.OFError;
103import org.openflow.protocol.OFError.OFBadActionCode;
104import org.openflow.protocol.OFError.OFBadRequestCode;
105import org.openflow.protocol.OFError.OFErrorType;
106import org.openflow.protocol.OFError.OFFlowModFailedCode;
107import org.openflow.protocol.OFError.OFHelloFailedCode;
108import org.openflow.protocol.OFError.OFPortModFailedCode;
109import org.openflow.protocol.OFError.OFQueueOpFailedCode;
110import org.openflow.protocol.OFFeaturesReply;
111import org.openflow.protocol.OFGetConfigReply;
112import org.openflow.protocol.OFMessage;
113import org.openflow.protocol.OFPacketIn;
114import org.openflow.protocol.OFPhysicalPort;
Pankaj Berde6a4075d2013-01-22 16:42:54 -0800115import org.openflow.protocol.OFPhysicalPort.OFPortConfig;
Pankaj Berde6debb042013-01-16 18:04:32 -0800116import org.openflow.protocol.OFPhysicalPort.OFPortState;
Jonathan Hartd10008d2013-02-23 17:04:08 -0800117import org.openflow.protocol.OFPortStatus;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800118import org.openflow.protocol.OFPortStatus.OFPortReason;
119import org.openflow.protocol.OFSetConfig;
120import org.openflow.protocol.OFStatisticsRequest;
121import org.openflow.protocol.OFSwitchConfig;
122import org.openflow.protocol.OFType;
123import org.openflow.protocol.OFVendor;
124import org.openflow.protocol.factory.BasicFactory;
125import org.openflow.protocol.factory.MessageParseException;
126import org.openflow.protocol.statistics.OFDescriptionStatistics;
127import org.openflow.protocol.statistics.OFStatistics;
128import org.openflow.protocol.statistics.OFStatisticsType;
129import org.openflow.protocol.vendor.OFBasicVendorDataType;
130import org.openflow.protocol.vendor.OFBasicVendorId;
131import org.openflow.protocol.vendor.OFVendorId;
132import org.openflow.util.HexString;
133import org.openflow.util.U16;
134import org.openflow.util.U32;
135import org.openflow.vendor.nicira.OFNiciraVendorData;
136import org.openflow.vendor.nicira.OFRoleReplyVendorData;
137import org.openflow.vendor.nicira.OFRoleRequestVendorData;
138import org.openflow.vendor.nicira.OFRoleVendorData;
139import org.slf4j.Logger;
140import org.slf4j.LoggerFactory;
141
142
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800143
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800144/**
145 * The main controller class. Handles all setup and network listeners
146 */
147public class Controller implements IFloodlightProviderService,
148 IStorageSourceListener {
Pankaj Berde29ab7fc2013-01-25 06:17:52 -0800149
150 ThreadLocal<SwitchStorageImpl> store = new ThreadLocal<SwitchStorageImpl>() {
151 @Override
152 protected SwitchStorageImpl initialValue() {
153 SwitchStorageImpl swStore = new SwitchStorageImpl();
154 //TODO: Get the file path from global properties
155 swStore.init("/tmp/cassandra.titan");
156 return swStore;
157 }
158 };
159
160 protected SwitchStorageImpl swStore = store.get();
Pankaj Berde8557a462013-01-07 08:59:31 -0800161
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800162 protected static Logger log = LoggerFactory.getLogger(Controller.class);
163
164 private static final String ERROR_DATABASE =
165 "The controller could not communicate with the system database.";
166
167 protected BasicFactory factory;
168 protected ConcurrentMap<OFType,
169 ListenerDispatcher<OFType,IOFMessageListener>>
170 messageListeners;
171 // The activeSwitches map contains only those switches that are actively
172 // being controlled by us -- it doesn't contain switches that are
173 // in the slave role
174 protected ConcurrentHashMap<Long, IOFSwitch> activeSwitches;
175 // connectedSwitches contains all connected switches, including ones where
176 // we're a slave controller. We need to keep track of them so that we can
177 // send role request messages to switches when our role changes to master
178 // We add a switch to this set after it successfully completes the
179 // handshake. Access to this Set needs to be synchronized with roleChanger
180 protected HashSet<OFSwitchImpl> connectedSwitches;
181
182 // The controllerNodeIPsCache maps Controller IDs to their IP address.
183 // It's only used by handleControllerNodeIPsChanged
184 protected HashMap<String, String> controllerNodeIPsCache;
185
186 protected Set<IOFSwitchListener> switchListeners;
187 protected Set<IHAListener> haListeners;
188 protected Map<String, List<IInfoProvider>> providerMap;
189 protected BlockingQueue<IUpdate> updates;
190
191 // Module dependencies
192 protected IRestApiService restApi;
193 protected ICounterStoreService counterStore = null;
194 protected IStorageSourceService storageSource;
195 protected IPktInProcessingTimeService pktinProcTime;
196 protected IThreadPoolService threadPool;
Pavlin Radoslavov19b0e122013-02-21 18:47:38 -0800197 protected IFlowService flowService;
Pavlin Radoslavovd7d8b792013-02-22 10:24:38 -0800198 protected ITopoRouteService topoRouteService;
Jonathan Hartd10008d2013-02-23 17:04:08 -0800199 protected IControllerRegistryService registryService;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800200
201 // Configuration options
202 protected int openFlowPort = 6633;
203 protected int workerThreads = 0;
204 // The id for this controller node. Should be unique for each controller
205 // node in a controller cluster.
206 protected String controllerId = "localhost";
207
208 // The current role of the controller.
209 // If the controller isn't configured to support roles, then this is null.
210 protected Role role;
211 // A helper that handles sending and timeout handling for role requests
212 protected RoleChanger roleChanger;
213
214 // Start time of the controller
215 protected long systemStartTime;
216
217 // Flag to always flush flow table on switch reconnect (HA or otherwise)
218 protected boolean alwaysClearFlowsOnSwAdd = false;
219
220 // Storage table names
221 protected static final String CONTROLLER_TABLE_NAME = "controller_controller";
222 protected static final String CONTROLLER_ID = "id";
223
224 protected static final String SWITCH_TABLE_NAME = "controller_switch";
225 protected static final String SWITCH_DATAPATH_ID = "dpid";
226 protected static final String SWITCH_SOCKET_ADDRESS = "socket_address";
227 protected static final String SWITCH_IP = "ip";
228 protected static final String SWITCH_CONTROLLER_ID = "controller_id";
229 protected static final String SWITCH_ACTIVE = "active";
230 protected static final String SWITCH_CONNECTED_SINCE = "connected_since";
231 protected static final String SWITCH_CAPABILITIES = "capabilities";
232 protected static final String SWITCH_BUFFERS = "buffers";
233 protected static final String SWITCH_TABLES = "tables";
234 protected static final String SWITCH_ACTIONS = "actions";
235
236 protected static final String SWITCH_CONFIG_TABLE_NAME = "controller_switchconfig";
237 protected static final String SWITCH_CONFIG_CORE_SWITCH = "core_switch";
238
239 protected static final String PORT_TABLE_NAME = "controller_port";
240 protected static final String PORT_ID = "id";
241 protected static final String PORT_SWITCH = "switch_id";
242 protected static final String PORT_NUMBER = "number";
243 protected static final String PORT_HARDWARE_ADDRESS = "hardware_address";
244 protected static final String PORT_NAME = "name";
245 protected static final String PORT_CONFIG = "config";
246 protected static final String PORT_STATE = "state";
247 protected static final String PORT_CURRENT_FEATURES = "current_features";
248 protected static final String PORT_ADVERTISED_FEATURES = "advertised_features";
249 protected static final String PORT_SUPPORTED_FEATURES = "supported_features";
250 protected static final String PORT_PEER_FEATURES = "peer_features";
251
252 protected static final String CONTROLLER_INTERFACE_TABLE_NAME = "controller_controllerinterface";
253 protected static final String CONTROLLER_INTERFACE_ID = "id";
254 protected static final String CONTROLLER_INTERFACE_CONTROLLER_ID = "controller_id";
255 protected static final String CONTROLLER_INTERFACE_TYPE = "type";
256 protected static final String CONTROLLER_INTERFACE_NUMBER = "number";
257 protected static final String CONTROLLER_INTERFACE_DISCOVERED_IP = "discovered_ip";
258
259
260
261 // Perf. related configuration
262 protected static final int SEND_BUFFER_SIZE = 4 * 1024 * 1024;
263 protected static final int BATCH_MAX_SIZE = 100;
264 protected static final boolean ALWAYS_DECODE_ETH = true;
265
266 /**
267 * Updates handled by the main loop
268 */
269 protected interface IUpdate {
270 /**
271 * Calls the appropriate listeners
272 */
273 public void dispatch();
274 }
275 public enum SwitchUpdateType {
276 ADDED,
277 REMOVED,
278 PORTCHANGED
279 }
280 /**
281 * Update message indicating a switch was added or removed
282 */
283 protected class SwitchUpdate implements IUpdate {
284 public IOFSwitch sw;
285 public SwitchUpdateType switchUpdateType;
286 public SwitchUpdate(IOFSwitch sw, SwitchUpdateType switchUpdateType) {
287 this.sw = sw;
288 this.switchUpdateType = switchUpdateType;
289 }
290 public void dispatch() {
291 if (log.isTraceEnabled()) {
292 log.trace("Dispatching switch update {} {}",
293 sw, switchUpdateType);
294 }
295 if (switchListeners != null) {
296 for (IOFSwitchListener listener : switchListeners) {
297 switch(switchUpdateType) {
298 case ADDED:
299 listener.addedSwitch(sw);
300 break;
301 case REMOVED:
302 listener.removedSwitch(sw);
303 break;
304 case PORTCHANGED:
305 listener.switchPortChanged(sw.getId());
306 break;
307 }
308 }
309 }
310 }
311 }
312
313 /**
314 * Update message indicating controller's role has changed
315 */
316 protected class HARoleUpdate implements IUpdate {
317 public Role oldRole;
318 public Role newRole;
319 public HARoleUpdate(Role newRole, Role oldRole) {
320 this.oldRole = oldRole;
321 this.newRole = newRole;
322 }
323 public void dispatch() {
324 // Make sure that old and new roles are different.
325 if (oldRole == newRole) {
326 if (log.isTraceEnabled()) {
327 log.trace("HA role update ignored as the old and " +
328 "new roles are the same. newRole = {}" +
329 "oldRole = {}", newRole, oldRole);
330 }
331 return;
332 }
333 if (log.isTraceEnabled()) {
334 log.trace("Dispatching HA Role update newRole = {}, oldRole = {}",
335 newRole, oldRole);
336 }
337 if (haListeners != null) {
338 for (IHAListener listener : haListeners) {
339 listener.roleChanged(oldRole, newRole);
340 }
341 }
342 }
343 }
344
345 /**
346 * Update message indicating
347 * IPs of controllers in controller cluster have changed.
348 */
349 protected class HAControllerNodeIPUpdate implements IUpdate {
350 public Map<String,String> curControllerNodeIPs;
351 public Map<String,String> addedControllerNodeIPs;
352 public Map<String,String> removedControllerNodeIPs;
353 public HAControllerNodeIPUpdate(
354 HashMap<String,String> curControllerNodeIPs,
355 HashMap<String,String> addedControllerNodeIPs,
356 HashMap<String,String> removedControllerNodeIPs) {
357 this.curControllerNodeIPs = curControllerNodeIPs;
358 this.addedControllerNodeIPs = addedControllerNodeIPs;
359 this.removedControllerNodeIPs = removedControllerNodeIPs;
360 }
361 public void dispatch() {
362 if (log.isTraceEnabled()) {
363 log.trace("Dispatching HA Controller Node IP update "
364 + "curIPs = {}, addedIPs = {}, removedIPs = {}",
365 new Object[] { curControllerNodeIPs, addedControllerNodeIPs,
366 removedControllerNodeIPs }
367 );
368 }
369 if (haListeners != null) {
370 for (IHAListener listener: haListeners) {
371 listener.controllerNodeIPsChanged(curControllerNodeIPs,
372 addedControllerNodeIPs, removedControllerNodeIPs);
373 }
374 }
375 }
376 }
377
378 // ***************
379 // Getters/Setters
380 // ***************
381
382 public void setStorageSourceService(IStorageSourceService storageSource) {
383 this.storageSource = storageSource;
384 }
385
386 public void setCounterStore(ICounterStoreService counterStore) {
387 this.counterStore = counterStore;
388 }
389
390 public void setPktInProcessingService(IPktInProcessingTimeService pits) {
391 this.pktinProcTime = pits;
392 }
393
394 public void setRestApiService(IRestApiService restApi) {
395 this.restApi = restApi;
396 }
397
398 public void setThreadPoolService(IThreadPoolService tp) {
399 this.threadPool = tp;
400 }
401
Pavlin Radoslavov19b0e122013-02-21 18:47:38 -0800402 public void setFlowService(IFlowService serviceImpl) {
403 this.flowService = serviceImpl;
404 }
Pavlin Radoslavovd7d8b792013-02-22 10:24:38 -0800405
406 public void setTopoRouteService(ITopoRouteService serviceImpl) {
407 this.topoRouteService = serviceImpl;
408 }
Jonathan Hartc2e95ee2013-02-22 15:25:11 -0800409
Jonathan Hartd82f20d2013-02-21 18:04:24 -0800410 public void setMastershipService(IControllerRegistryService serviceImpl) {
Jonathan Hartd10008d2013-02-23 17:04:08 -0800411 this.registryService = serviceImpl;
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800412 }
413
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800414 @Override
415 public Role getRole() {
416 synchronized(roleChanger) {
417 return role;
418 }
419 }
420
421 @Override
422 public void setRole(Role role) {
423 if (role == null) throw new NullPointerException("Role can not be null.");
424 if (role == Role.MASTER && this.role == Role.SLAVE) {
425 // Reset db state to Inactive for all switches.
426 updateAllInactiveSwitchInfo();
427 }
428
429 // Need to synchronize to ensure a reliable ordering on role request
430 // messages send and to ensure the list of connected switches is stable
431 // RoleChanger will handle the actual sending of the message and
432 // timeout handling
433 // @see RoleChanger
434 synchronized(roleChanger) {
435 if (role.equals(this.role)) {
436 log.debug("Ignoring role change: role is already {}", role);
437 return;
438 }
439
440 Role oldRole = this.role;
441 this.role = role;
442
443 log.debug("Submitting role change request to role {}", role);
444 roleChanger.submitRequest(connectedSwitches, role);
445
446 // Enqueue an update for our listeners.
447 try {
448 this.updates.put(new HARoleUpdate(role, oldRole));
449 } catch (InterruptedException e) {
450 log.error("Failure adding update to queue", e);
451 }
452 }
453 }
454
455
456
457 // **********************
458 // ChannelUpstreamHandler
459 // **********************
460
461 /**
462 * Return a new channel handler for processing a switch connections
463 * @param state The channel state object for the connection
464 * @return the new channel handler
465 */
466 protected ChannelUpstreamHandler getChannelHandler(OFChannelState state) {
467 return new OFChannelHandler(state);
468 }
469
Jonathan Hartcc957a02013-02-26 10:39:04 -0800470 protected class RoleChangeCallback implements ControlChangeCallback {
471 @Override
472 public void controlChanged(long dpid, boolean hasControl) {
473 log.info("Role change callback for switch {}, hasControl {}",
474 HexString.toHexString(dpid), hasControl);
475
476 synchronized(roleChanger){
477 OFSwitchImpl sw = null;
478 for (OFSwitchImpl connectedSw : connectedSwitches){
479 if (connectedSw.getId() == dpid){
480 sw = connectedSw;
481 break;
482 }
483 }
484 if (sw == null){
485 log.warn("Switch {} not found in connected switches",
486 HexString.toHexString(dpid));
487 return;
488 }
489
490 Role role = null;
491
492 if (sw.getRole() == null){
493 if (hasControl){
494 role = Role.MASTER;
495 }
496 else {
497 role = Role.SLAVE;
498 }
499 }
500 else if (hasControl && sw.getRole() == Role.SLAVE) {
501 // Send a MASTER role request to the switch.
502 // If this is the first role request,
503 // this is a probe that we'll use to determine if the switch
504 // actually supports the role request message. If it does we'll
505 // get back a role reply message. If it doesn't we'll get back an
506 // OFError message.
507 // If role is MASTER we will promote switch to active
508 // list when we receive the switch's role reply messages
509 role = Role.MASTER;
510 }
511 else if (!hasControl && sw.getRole() == Role.MASTER) {
512 //Send a SLAVE role request to the switch
513 role = Role.SLAVE;
514 }
515
516 if (role != null) {
517 log.debug("Sending role request {} msg to {}", role, sw);
518 Collection<OFSwitchImpl> swList = new ArrayList<OFSwitchImpl>(1);
519 swList.add(sw);
520 roleChanger.submitRequest(swList, role);
521 }
522 }
523
524 }
525 }
526
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800527 /**
528 * Channel handler deals with the switch connection and dispatches
529 * switch messages to the appropriate locations.
530 * @author readams
531 */
532 protected class OFChannelHandler
533 extends IdleStateAwareChannelUpstreamHandler {
534 protected OFSwitchImpl sw;
535 protected OFChannelState state;
536
537 public OFChannelHandler(OFChannelState state) {
538 this.state = state;
539 }
540
541 @Override
542 @LogMessageDoc(message="New switch connection from {ip address}",
543 explanation="A new switch has connected from the " +
544 "specified IP address")
545 public void channelConnected(ChannelHandlerContext ctx,
546 ChannelStateEvent e) throws Exception {
547 log.info("New switch connection from {}",
548 e.getChannel().getRemoteAddress());
549
550 sw = new OFSwitchImpl();
551 sw.setChannel(e.getChannel());
552 sw.setFloodlightProvider(Controller.this);
553 sw.setThreadPoolService(threadPool);
554
555 List<OFMessage> msglist = new ArrayList<OFMessage>(1);
556 msglist.add(factory.getMessage(OFType.HELLO));
557 e.getChannel().write(msglist);
558
559 }
560
561 @Override
562 @LogMessageDoc(message="Disconnected switch {switch information}",
563 explanation="The specified switch has disconnected.")
564 public void channelDisconnected(ChannelHandlerContext ctx,
565 ChannelStateEvent e) throws Exception {
566 if (sw != null && state.hsState == HandshakeState.READY) {
567 if (activeSwitches.containsKey(sw.getId())) {
568 // It's safe to call removeSwitch even though the map might
569 // not contain this particular switch but another with the
570 // same DPID
571 removeSwitch(sw);
572 }
573 synchronized(roleChanger) {
Jonathan Hartcc957a02013-02-26 10:39:04 -0800574 registryService.releaseControl(sw.getId());
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800575 connectedSwitches.remove(sw);
576 }
577 sw.setConnected(false);
578 }
579 log.info("Disconnected switch {}", sw);
580 }
581
582 @Override
583 @LogMessageDocs({
584 @LogMessageDoc(level="ERROR",
585 message="Disconnecting switch {switch} due to read timeout",
586 explanation="The connected switch has failed to send any " +
587 "messages or respond to echo requests",
588 recommendation=LogMessageDoc.CHECK_SWITCH),
589 @LogMessageDoc(level="ERROR",
590 message="Disconnecting switch {switch}: failed to " +
591 "complete handshake",
592 explanation="The switch did not respond correctly " +
593 "to handshake messages",
594 recommendation=LogMessageDoc.CHECK_SWITCH),
595 @LogMessageDoc(level="ERROR",
596 message="Disconnecting switch {switch} due to IO Error: {}",
597 explanation="There was an error communicating with the switch",
598 recommendation=LogMessageDoc.CHECK_SWITCH),
599 @LogMessageDoc(level="ERROR",
600 message="Disconnecting switch {switch} due to switch " +
601 "state error: {error}",
602 explanation="The switch sent an unexpected message",
603 recommendation=LogMessageDoc.CHECK_SWITCH),
604 @LogMessageDoc(level="ERROR",
605 message="Disconnecting switch {switch} due to " +
606 "message parse failure",
607 explanation="Could not parse a message from the switch",
608 recommendation=LogMessageDoc.CHECK_SWITCH),
609 @LogMessageDoc(level="ERROR",
610 message="Terminating controller due to storage exception",
611 explanation=ERROR_DATABASE,
612 recommendation=LogMessageDoc.CHECK_CONTROLLER),
613 @LogMessageDoc(level="ERROR",
614 message="Could not process message: queue full",
615 explanation="OpenFlow messages are arriving faster than " +
616 " the controller can process them.",
617 recommendation=LogMessageDoc.CHECK_CONTROLLER),
618 @LogMessageDoc(level="ERROR",
619 message="Error while processing message " +
620 "from switch {switch} {cause}",
621 explanation="An error occurred processing the switch message",
622 recommendation=LogMessageDoc.GENERIC_ACTION)
623 })
624 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
625 throws Exception {
626 if (e.getCause() instanceof ReadTimeoutException) {
627 // switch timeout
628 log.error("Disconnecting switch {} due to read timeout", sw);
629 ctx.getChannel().close();
630 } else if (e.getCause() instanceof HandshakeTimeoutException) {
631 log.error("Disconnecting switch {}: failed to complete handshake",
632 sw);
633 ctx.getChannel().close();
634 } else if (e.getCause() instanceof ClosedChannelException) {
635 //log.warn("Channel for sw {} already closed", sw);
636 } else if (e.getCause() instanceof IOException) {
637 log.error("Disconnecting switch {} due to IO Error: {}",
638 sw, e.getCause().getMessage());
639 ctx.getChannel().close();
640 } else if (e.getCause() instanceof SwitchStateException) {
641 log.error("Disconnecting switch {} due to switch state error: {}",
642 sw, e.getCause().getMessage());
643 ctx.getChannel().close();
644 } else if (e.getCause() instanceof MessageParseException) {
645 log.error("Disconnecting switch " + sw +
646 " due to message parse failure",
647 e.getCause());
648 ctx.getChannel().close();
649 } else if (e.getCause() instanceof StorageException) {
650 log.error("Terminating controller due to storage exception",
651 e.getCause());
652 terminate();
653 } else if (e.getCause() instanceof RejectedExecutionException) {
654 log.warn("Could not process message: queue full");
655 } else {
656 log.error("Error while processing message from switch " + sw,
657 e.getCause());
658 ctx.getChannel().close();
659 }
660 }
661
662 @Override
663 public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e)
664 throws Exception {
665 List<OFMessage> msglist = new ArrayList<OFMessage>(1);
666 msglist.add(factory.getMessage(OFType.ECHO_REQUEST));
667 e.getChannel().write(msglist);
668 }
669
670 @Override
671 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
672 throws Exception {
673 if (e.getMessage() instanceof List) {
674 @SuppressWarnings("unchecked")
675 List<OFMessage> msglist = (List<OFMessage>)e.getMessage();
676
677 for (OFMessage ofm : msglist) {
678 try {
679 processOFMessage(ofm);
680 }
681 catch (Exception ex) {
682 // We are the last handler in the stream, so run the
683 // exception through the channel again by passing in
684 // ctx.getChannel().
685 Channels.fireExceptionCaught(ctx.getChannel(), ex);
686 }
687 }
688
689 // Flush all flow-mods/packet-out generated from this "train"
690 OFSwitchImpl.flush_all();
691 }
692 }
693
694 /**
695 * Process the request for the switch description
696 */
697 @LogMessageDoc(level="ERROR",
698 message="Exception in reading description " +
699 " during handshake {exception}",
700 explanation="Could not process the switch description string",
701 recommendation=LogMessageDoc.CHECK_SWITCH)
702 void processSwitchDescReply() {
703 try {
704 // Read description, if it has been updated
705 @SuppressWarnings("unchecked")
706 Future<List<OFStatistics>> desc_future =
707 (Future<List<OFStatistics>>)sw.
708 getAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE);
709 List<OFStatistics> values =
710 desc_future.get(0, TimeUnit.MILLISECONDS);
711 if (values != null) {
712 OFDescriptionStatistics description =
713 new OFDescriptionStatistics();
714 ChannelBuffer data =
715 ChannelBuffers.buffer(description.getLength());
716 for (OFStatistics f : values) {
717 f.writeTo(data);
718 description.readFrom(data);
719 break; // SHOULD be a list of length 1
720 }
721 sw.setAttribute(IOFSwitch.SWITCH_DESCRIPTION_DATA,
722 description);
723 sw.setSwitchProperties(description);
724 data = null;
725
726 // At this time, also set other switch properties from storage
727 boolean is_core_switch = false;
728 IResultSet resultSet = null;
729 try {
730 String swid = sw.getStringId();
731 resultSet =
732 storageSource.getRow(SWITCH_CONFIG_TABLE_NAME, swid);
733 for (Iterator<IResultSet> it =
734 resultSet.iterator(); it.hasNext();) {
735 // In case of multiple rows, use the status
736 // in last row?
737 Map<String, Object> row = it.next().getRow();
738 if (row.containsKey(SWITCH_CONFIG_CORE_SWITCH)) {
739 if (log.isDebugEnabled()) {
740 log.debug("Reading SWITCH_IS_CORE_SWITCH " +
741 "config for switch={}, is-core={}",
742 sw, row.get(SWITCH_CONFIG_CORE_SWITCH));
743 }
744 String ics =
745 (String)row.get(SWITCH_CONFIG_CORE_SWITCH);
746 is_core_switch = ics.equals("true");
747 }
748 }
749 }
750 finally {
751 if (resultSet != null)
752 resultSet.close();
753 }
754 if (is_core_switch) {
755 sw.setAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH,
756 new Boolean(true));
757 }
758 }
759 sw.removeAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE);
760 state.hasDescription = true;
761 checkSwitchReady();
762 }
763 catch (InterruptedException ex) {
764 // Ignore
765 }
766 catch (TimeoutException ex) {
767 // Ignore
768 } catch (Exception ex) {
769 log.error("Exception in reading description " +
770 " during handshake", ex);
771 }
772 }
773
774 /**
775 * Send initial switch setup information that we need before adding
776 * the switch
777 * @throws IOException
778 */
779 void sendHelloConfiguration() throws IOException {
780 // Send initial Features Request
781 sw.write(factory.getMessage(OFType.FEATURES_REQUEST), null);
782 }
783
784 /**
785 * Send the configuration requests we can only do after we have
786 * the features reply
787 * @throws IOException
788 */
789 void sendFeatureReplyConfiguration() throws IOException {
790 // Ensure we receive the full packet via PacketIn
791 OFSetConfig config = (OFSetConfig) factory
792 .getMessage(OFType.SET_CONFIG);
793 config.setMissSendLength((short) 0xffff)
794 .setLengthU(OFSwitchConfig.MINIMUM_LENGTH);
795 sw.write(config, null);
796 sw.write(factory.getMessage(OFType.GET_CONFIG_REQUEST),
797 null);
798
799 // Get Description to set switch-specific flags
800 OFStatisticsRequest req = new OFStatisticsRequest();
801 req.setStatisticType(OFStatisticsType.DESC);
802 req.setLengthU(req.getLengthU());
803 Future<List<OFStatistics>> dfuture =
804 sw.getStatistics(req);
805 sw.setAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE,
806 dfuture);
807
808 }
809
810 protected void checkSwitchReady() {
811 if (state.hsState == HandshakeState.FEATURES_REPLY &&
812 state.hasDescription && state.hasGetConfigReply) {
813
814 state.hsState = HandshakeState.READY;
815
816 synchronized(roleChanger) {
817 // We need to keep track of all of the switches that are connected
818 // to the controller, in any role, so that we can later send the
819 // role request messages when the controller role changes.
820 // We need to be synchronized while doing this: we must not
821 // send a another role request to the connectedSwitches until
822 // we were able to add this new switch to connectedSwitches
823 // *and* send the current role to the new switch.
824 connectedSwitches.add(sw);
825
826 if (role != null) {
Jonathan Hart97801ac2013-02-26 14:29:16 -0800827 //Put the switch in SLAVE mode until we know we have control
828 log.debug("Setting new switch {} to SLAVE", sw.getStringId());
829 Collection<OFSwitchImpl> swList = new ArrayList<OFSwitchImpl>(1);
830 swList.add(sw);
831 roleChanger.submitRequest(swList, Role.SLAVE);
832
Jonathan Hartcc957a02013-02-26 10:39:04 -0800833 //Request control of the switch from the global registry
834 try {
835 registryService.requestControl(sw.getId(),
836 new RoleChangeCallback());
837 } catch (RegistryException e) {
838 log.debug("Registry error: {}", e.getMessage());
839 }
840
Jonathan Hart97801ac2013-02-26 14:29:16 -0800841
Jonathan Hartcc957a02013-02-26 10:39:04 -0800842
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800843 // Send a role request if role support is enabled for the controller
844 // This is a probe that we'll use to determine if the switch
845 // actually supports the role request message. If it does we'll
846 // get back a role reply message. If it doesn't we'll get back an
847 // OFError message.
848 // If role is MASTER we will promote switch to active
849 // list when we receive the switch's role reply messages
Jonathan Hartcc957a02013-02-26 10:39:04 -0800850 /*
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800851 log.debug("This controller's role is {}, " +
852 "sending initial role request msg to {}",
853 role, sw);
854 Collection<OFSwitchImpl> swList = new ArrayList<OFSwitchImpl>(1);
855 swList.add(sw);
856 roleChanger.submitRequest(swList, role);
Jonathan Hartcc957a02013-02-26 10:39:04 -0800857 */
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800858 }
859 else {
860 // Role supported not enabled on controller (for now)
861 // automatically promote switch to active state.
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800862 log.debug("This controller's role is {}, " +
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800863 "not sending role request msg to {}",
864 role, sw);
865 // Need to clear FlowMods before we add the switch
866 // and dispatch updates otherwise we have a race condition.
867 sw.clearAllFlowMods();
868 addSwitch(sw);
869 state.firstRoleReplyReceived = true;
870 }
871 }
872 }
873 }
874
875 /* Handle a role reply message we received from the switch. Since
876 * netty serializes message dispatch we don't need to synchronize
877 * against other receive operations from the same switch, so no need
878 * to synchronize addSwitch(), removeSwitch() operations from the same
879 * connection.
880 * FIXME: However, when a switch with the same DPID connects we do
881 * need some synchronization. However, handling switches with same
882 * DPID needs to be revisited anyways (get rid of r/w-lock and synchronous
883 * removedSwitch notification):1
884 *
885 */
886 @LogMessageDoc(level="ERROR",
887 message="Invalid role value in role reply message",
888 explanation="Was unable to set the HA role (master or slave) " +
889 "for the controller.",
890 recommendation=LogMessageDoc.CHECK_CONTROLLER)
891 protected void handleRoleReplyMessage(OFVendor vendorMessage,
892 OFRoleReplyVendorData roleReplyVendorData) {
893 // Map from the role code in the message to our role enum
894 int nxRole = roleReplyVendorData.getRole();
895 Role role = null;
896 switch (nxRole) {
897 case OFRoleVendorData.NX_ROLE_OTHER:
898 role = Role.EQUAL;
899 break;
900 case OFRoleVendorData.NX_ROLE_MASTER:
901 role = Role.MASTER;
902 break;
903 case OFRoleVendorData.NX_ROLE_SLAVE:
904 role = Role.SLAVE;
905 break;
906 default:
907 log.error("Invalid role value in role reply message");
908 sw.getChannel().close();
909 return;
910 }
911
912 log.debug("Handling role reply for role {} from {}. " +
913 "Controller's role is {} ",
914 new Object[] { role, sw, Controller.this.role}
915 );
916
917 sw.deliverRoleReply(vendorMessage.getXid(), role);
918
919 boolean isActive = activeSwitches.containsKey(sw.getId());
920 if (!isActive && sw.isActive()) {
921 // Transition from SLAVE to MASTER.
922
923 if (!state.firstRoleReplyReceived ||
924 getAlwaysClearFlowsOnSwAdd()) {
925 // This is the first role-reply message we receive from
926 // this switch or roles were disabled when the switch
927 // connected:
928 // Delete all pre-existing flows for new connections to
929 // the master
930 //
931 // FIXME: Need to think more about what the test should
932 // be for when we flush the flow-table? For example,
933 // if all the controllers are temporarily in the backup
934 // role (e.g. right after a failure of the master
935 // controller) at the point the switch connects, then
936 // all of the controllers will initially connect as
937 // backup controllers and not flush the flow-table.
938 // Then when one of them is promoted to master following
939 // the master controller election the flow-table
940 // will still not be flushed because that's treated as
941 // a failover event where we don't want to flush the
942 // flow-table. The end result would be that the flow
943 // table for a newly connected switch is never
944 // flushed. Not sure how to handle that case though...
945 sw.clearAllFlowMods();
946 log.debug("First role reply from master switch {}, " +
947 "clear FlowTable to active switch list",
948 HexString.toHexString(sw.getId()));
949 }
950
951 // Some switches don't seem to update us with port
952 // status messages while in slave role.
953 readSwitchPortStateFromStorage(sw);
954
955 // Only add the switch to the active switch list if
956 // we're not in the slave role. Note that if the role
957 // attribute is null, then that means that the switch
958 // doesn't support the role request messages, so in that
959 // case we're effectively in the EQUAL role and the
960 // switch should be included in the active switch list.
961 addSwitch(sw);
962 log.debug("Added master switch {} to active switch list",
963 HexString.toHexString(sw.getId()));
964
965 }
966 else if (isActive && !sw.isActive()) {
967 // Transition from MASTER to SLAVE: remove switch
968 // from active switch list.
969 log.debug("Removed slave switch {} from active switch" +
970 " list", HexString.toHexString(sw.getId()));
971 removeSwitch(sw);
972 }
973
974 // Indicate that we have received a role reply message.
975 state.firstRoleReplyReceived = true;
976 }
977
978 protected boolean handleVendorMessage(OFVendor vendorMessage) {
979 boolean shouldHandleMessage = false;
980 int vendor = vendorMessage.getVendor();
981 switch (vendor) {
982 case OFNiciraVendorData.NX_VENDOR_ID:
983 OFNiciraVendorData niciraVendorData =
984 (OFNiciraVendorData)vendorMessage.getVendorData();
985 int dataType = niciraVendorData.getDataType();
986 switch (dataType) {
987 case OFRoleReplyVendorData.NXT_ROLE_REPLY:
988 OFRoleReplyVendorData roleReplyVendorData =
989 (OFRoleReplyVendorData) niciraVendorData;
990 handleRoleReplyMessage(vendorMessage,
991 roleReplyVendorData);
992 break;
993 default:
994 log.warn("Unhandled Nicira VENDOR message; " +
995 "data type = {}", dataType);
996 break;
997 }
998 break;
999 default:
1000 log.warn("Unhandled VENDOR message; vendor id = {}", vendor);
1001 break;
1002 }
1003
1004 return shouldHandleMessage;
1005 }
1006
1007 /**
1008 * Dispatch an Openflow message from a switch to the appropriate
1009 * handler.
1010 * @param m The message to process
1011 * @throws IOException
1012 * @throws SwitchStateException
1013 */
1014 @LogMessageDocs({
1015 @LogMessageDoc(level="WARN",
1016 message="Config Reply from {switch} has " +
1017 "miss length set to {length}",
1018 explanation="The controller requires that the switch " +
1019 "use a miss length of 0xffff for correct " +
1020 "function",
1021 recommendation="Use a different switch to ensure " +
1022 "correct function"),
1023 @LogMessageDoc(level="WARN",
1024 message="Received ERROR from sw {switch} that "
1025 +"indicates roles are not supported "
1026 +"but we have received a valid "
1027 +"role reply earlier",
1028 explanation="The switch sent a confusing message to the" +
1029 "controller")
1030 })
1031 protected void processOFMessage(OFMessage m)
1032 throws IOException, SwitchStateException {
1033 boolean shouldHandleMessage = false;
1034
1035 switch (m.getType()) {
1036 case HELLO:
1037 if (log.isTraceEnabled())
1038 log.trace("HELLO from {}", sw);
1039
1040 if (state.hsState.equals(HandshakeState.START)) {
1041 state.hsState = HandshakeState.HELLO;
1042 sendHelloConfiguration();
1043 } else {
1044 throw new SwitchStateException("Unexpected HELLO from "
1045 + sw);
1046 }
1047 break;
1048 case ECHO_REQUEST:
1049 OFEchoReply reply =
1050 (OFEchoReply) factory.getMessage(OFType.ECHO_REPLY);
1051 reply.setXid(m.getXid());
1052 sw.write(reply, null);
1053 break;
1054 case ECHO_REPLY:
1055 break;
1056 case FEATURES_REPLY:
1057 if (log.isTraceEnabled())
1058 log.trace("Features Reply from {}", sw);
1059
1060 sw.setFeaturesReply((OFFeaturesReply) m);
1061 if (state.hsState.equals(HandshakeState.HELLO)) {
1062 sendFeatureReplyConfiguration();
1063 state.hsState = HandshakeState.FEATURES_REPLY;
1064 // uncomment to enable "dumb" switches like cbench
1065 // state.hsState = HandshakeState.READY;
1066 // addSwitch(sw);
1067 } else {
1068 // return results to rest api caller
1069 sw.deliverOFFeaturesReply(m);
1070 // update database */
1071 updateActiveSwitchInfo(sw);
1072 }
1073 break;
1074 case GET_CONFIG_REPLY:
1075 if (log.isTraceEnabled())
1076 log.trace("Get config reply from {}", sw);
1077
1078 if (!state.hsState.equals(HandshakeState.FEATURES_REPLY)) {
1079 String em = "Unexpected GET_CONFIG_REPLY from " + sw;
1080 throw new SwitchStateException(em);
1081 }
1082 OFGetConfigReply cr = (OFGetConfigReply) m;
1083 if (cr.getMissSendLength() == (short)0xffff) {
1084 log.trace("Config Reply from {} confirms " +
1085 "miss length set to 0xffff", sw);
1086 } else {
1087 log.warn("Config Reply from {} has " +
1088 "miss length set to {}",
1089 sw, cr.getMissSendLength() & 0xffff);
1090 }
1091 state.hasGetConfigReply = true;
1092 checkSwitchReady();
1093 break;
1094 case VENDOR:
1095 shouldHandleMessage = handleVendorMessage((OFVendor)m);
1096 break;
1097 case ERROR:
1098 // TODO: we need better error handling. Especially for
1099 // request/reply style message (stats, roles) we should have
1100 // a unified way to lookup the xid in the error message.
1101 // This will probable involve rewriting the way we handle
1102 // request/reply style messages.
1103 OFError error = (OFError) m;
1104 boolean shouldLogError = true;
1105 // TODO: should we check that firstRoleReplyReceived is false,
1106 // i.e., check only whether the first request fails?
1107 if (sw.checkFirstPendingRoleRequestXid(error.getXid())) {
1108 boolean isBadVendorError =
1109 (error.getErrorType() == OFError.OFErrorType.
1110 OFPET_BAD_REQUEST.getValue());
1111 // We expect to receive a bad vendor error when
1112 // we're connected to a switch that doesn't support
1113 // the Nicira vendor extensions (i.e. not OVS or
1114 // derived from OVS). By protocol, it should also be
1115 // BAD_VENDOR, but too many switch implementations
1116 // get it wrong and we can already check the xid()
1117 // so we can ignore the type with confidence that this
1118 // is not a spurious error
1119 shouldLogError = !isBadVendorError;
1120 if (isBadVendorError) {
1121 if (state.firstRoleReplyReceived && (role != null)) {
1122 log.warn("Received ERROR from sw {} that "
1123 +"indicates roles are not supported "
1124 +"but we have received a valid "
1125 +"role reply earlier", sw);
1126 }
1127 state.firstRoleReplyReceived = true;
1128 sw.deliverRoleRequestNotSupported(error.getXid());
1129 synchronized(roleChanger) {
1130 if (sw.role == null && Controller.this.role==Role.SLAVE) {
1131 // the switch doesn't understand role request
1132 // messages and the current controller role is
1133 // slave. We need to disconnect the switch.
1134 // @see RoleChanger for rationale
1135 sw.getChannel().close();
1136 }
1137 else if (sw.role == null) {
1138 // Controller's role is master: add to
1139 // active
1140 // TODO: check if clearing flow table is
1141 // right choice here.
1142 // Need to clear FlowMods before we add the switch
1143 // and dispatch updates otherwise we have a race condition.
1144 // TODO: switch update is async. Won't we still have a potential
1145 // race condition?
1146 sw.clearAllFlowMods();
1147 addSwitch(sw);
1148 }
1149 }
1150 }
1151 else {
1152 // TODO: Is this the right thing to do if we receive
1153 // some other error besides a bad vendor error?
1154 // Presumably that means the switch did actually
1155 // understand the role request message, but there
1156 // was some other error from processing the message.
1157 // OF 1.2 specifies a OFPET_ROLE_REQUEST_FAILED
1158 // error code, but it doesn't look like the Nicira
1159 // role request has that. Should check OVS source
1160 // code to see if it's possible for any other errors
1161 // to be returned.
1162 // If we received an error the switch is not
1163 // in the correct role, so we need to disconnect it.
1164 // We could also resend the request but then we need to
1165 // check if there are other pending request in which
1166 // case we shouldn't resend. If we do resend we need
1167 // to make sure that the switch eventually accepts one
1168 // of our requests or disconnect the switch. This feels
1169 // cumbersome.
1170 sw.getChannel().close();
1171 }
1172 }
1173 // Once we support OF 1.2, we'd add code to handle it here.
1174 //if (error.getXid() == state.ofRoleRequestXid) {
1175 //}
1176 if (shouldLogError)
1177 logError(sw, error);
1178 break;
1179 case STATS_REPLY:
1180 if (state.hsState.ordinal() <
1181 HandshakeState.FEATURES_REPLY.ordinal()) {
1182 String em = "Unexpected STATS_REPLY from " + sw;
1183 throw new SwitchStateException(em);
1184 }
1185 sw.deliverStatisticsReply(m);
1186 if (sw.hasAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE)) {
1187 processSwitchDescReply();
1188 }
1189 break;
1190 case PORT_STATUS:
1191 // We want to update our port state info even if we're in
1192 // the slave role, but we only want to update storage if
1193 // we're the master (or equal).
1194 boolean updateStorage = state.hsState.
1195 equals(HandshakeState.READY) &&
1196 (sw.getRole() != Role.SLAVE);
1197 handlePortStatusMessage(sw, (OFPortStatus)m, updateStorage);
1198 shouldHandleMessage = true;
1199 break;
1200
1201 default:
1202 shouldHandleMessage = true;
1203 break;
1204 }
1205
1206 if (shouldHandleMessage) {
1207 sw.getListenerReadLock().lock();
1208 try {
1209 if (sw.isConnected()) {
1210 if (!state.hsState.equals(HandshakeState.READY)) {
1211 log.debug("Ignoring message type {} received " +
1212 "from switch {} before switch is " +
1213 "fully configured.", m.getType(), sw);
1214 }
1215 // Check if the controller is in the slave role for the
1216 // switch. If it is, then don't dispatch the message to
1217 // the listeners.
1218 // TODO: Should we dispatch messages that we expect to
1219 // receive when we're in the slave role, e.g. port
1220 // status messages? Since we're "hiding" switches from
1221 // the listeners when we're in the slave role, then it
1222 // seems a little weird to dispatch port status messages
1223 // to them. On the other hand there might be special
1224 // modules that care about all of the connected switches
1225 // and would like to receive port status notifications.
1226 else if (sw.getRole() == Role.SLAVE) {
1227 // Don't log message if it's a port status message
1228 // since we expect to receive those from the switch
1229 // and don't want to emit spurious messages.
1230 if (m.getType() != OFType.PORT_STATUS) {
1231 log.debug("Ignoring message type {} received " +
1232 "from switch {} while in the slave role.",
1233 m.getType(), sw);
1234 }
1235 } else {
1236 handleMessage(sw, m, null);
1237 }
1238 }
1239 }
1240 finally {
1241 sw.getListenerReadLock().unlock();
1242 }
1243 }
1244 }
1245 }
1246
1247 // ****************
1248 // Message handlers
1249 // ****************
1250
1251 protected void handlePortStatusMessage(IOFSwitch sw,
1252 OFPortStatus m,
1253 boolean updateStorage) {
1254 short portNumber = m.getDesc().getPortNumber();
1255 OFPhysicalPort port = m.getDesc();
1256 if (m.getReason() == (byte)OFPortReason.OFPPR_MODIFY.ordinal()) {
Pankaj Berde6a4075d2013-01-22 16:42:54 -08001257 boolean portDown = ((OFPortConfig.OFPPC_PORT_DOWN.getValue() & port.getConfig()) > 0) ||
1258 ((OFPortState.OFPPS_LINK_DOWN.getValue() & port.getState()) > 0);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001259 sw.setPort(port);
Pankaj Berde6a4075d2013-01-22 16:42:54 -08001260 if (!portDown) {
Pankaj Berde6debb042013-01-16 18:04:32 -08001261 swStore.addPort(sw.getStringId(), port);
1262 } else {
1263 swStore.deletePort(sw.getStringId(), port.getPortNumber());
1264 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001265 if (updateStorage)
1266 updatePortInfo(sw, port);
1267 log.debug("Port #{} modified for {}", portNumber, sw);
1268 } else if (m.getReason() == (byte)OFPortReason.OFPPR_ADD.ordinal()) {
1269 sw.setPort(port);
Pankaj Berde8557a462013-01-07 08:59:31 -08001270 swStore.addPort(sw.getStringId(), port);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001271 if (updateStorage)
1272 updatePortInfo(sw, port);
1273 log.debug("Port #{} added for {}", portNumber, sw);
1274 } else if (m.getReason() ==
1275 (byte)OFPortReason.OFPPR_DELETE.ordinal()) {
1276 sw.deletePort(portNumber);
Pankaj Berde8557a462013-01-07 08:59:31 -08001277 swStore.deletePort(sw.getStringId(), portNumber);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001278 if (updateStorage)
1279 removePortInfo(sw, portNumber);
1280 log.debug("Port #{} deleted for {}", portNumber, sw);
1281 }
1282 SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.PORTCHANGED);
1283 try {
1284 this.updates.put(update);
1285 } catch (InterruptedException e) {
1286 log.error("Failure adding update to queue", e);
1287 }
1288 }
1289
1290 /**
1291 * flcontext_cache - Keep a thread local stack of contexts
1292 */
1293 protected static final ThreadLocal<Stack<FloodlightContext>> flcontext_cache =
1294 new ThreadLocal <Stack<FloodlightContext>> () {
1295 @Override
1296 protected Stack<FloodlightContext> initialValue() {
1297 return new Stack<FloodlightContext>();
1298 }
1299 };
1300
1301 /**
1302 * flcontext_alloc - pop a context off the stack, if required create a new one
1303 * @return FloodlightContext
1304 */
1305 protected static FloodlightContext flcontext_alloc() {
1306 FloodlightContext flcontext = null;
1307
1308 if (flcontext_cache.get().empty()) {
1309 flcontext = new FloodlightContext();
1310 }
1311 else {
1312 flcontext = flcontext_cache.get().pop();
1313 }
1314
1315 return flcontext;
1316 }
1317
1318 /**
1319 * flcontext_free - Free the context to the current thread
1320 * @param flcontext
1321 */
1322 protected void flcontext_free(FloodlightContext flcontext) {
1323 flcontext.getStorage().clear();
1324 flcontext_cache.get().push(flcontext);
1325 }
1326
1327 /**
1328 * Handle replies to certain OFMessages, and pass others off to listeners
1329 * @param sw The switch for the message
1330 * @param m The message
1331 * @param bContext The floodlight context. If null then floodlight context would
1332 * be allocated in this function
1333 * @throws IOException
1334 */
1335 @LogMessageDocs({
1336 @LogMessageDoc(level="ERROR",
1337 message="Ignoring PacketIn (Xid = {xid}) because the data" +
1338 " field is empty.",
1339 explanation="The switch sent an improperly-formatted PacketIn" +
1340 " message",
1341 recommendation=LogMessageDoc.CHECK_SWITCH),
1342 @LogMessageDoc(level="WARN",
1343 message="Unhandled OF Message: {} from {}",
1344 explanation="The switch sent a message not handled by " +
1345 "the controller")
1346 })
1347 protected void handleMessage(IOFSwitch sw, OFMessage m,
1348 FloodlightContext bContext)
1349 throws IOException {
1350 Ethernet eth = null;
1351
1352 switch (m.getType()) {
1353 case PACKET_IN:
1354 OFPacketIn pi = (OFPacketIn)m;
1355
1356 if (pi.getPacketData().length <= 0) {
1357 log.error("Ignoring PacketIn (Xid = " + pi.getXid() +
1358 ") because the data field is empty.");
1359 return;
1360 }
1361
1362 if (Controller.ALWAYS_DECODE_ETH) {
1363 eth = new Ethernet();
1364 eth.deserialize(pi.getPacketData(), 0,
1365 pi.getPacketData().length);
1366 counterStore.updatePacketInCounters(sw, m, eth);
1367 }
1368 // fall through to default case...
1369
1370 default:
1371
1372 List<IOFMessageListener> listeners = null;
1373 if (messageListeners.containsKey(m.getType())) {
1374 listeners = messageListeners.get(m.getType()).
1375 getOrderedListeners();
1376 }
1377
1378 FloodlightContext bc = null;
1379 if (listeners != null) {
1380 // Check if floodlight context is passed from the calling
1381 // function, if so use that floodlight context, otherwise
1382 // allocate one
1383 if (bContext == null) {
1384 bc = flcontext_alloc();
1385 } else {
1386 bc = bContext;
1387 }
1388 if (eth != null) {
1389 IFloodlightProviderService.bcStore.put(bc,
1390 IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
1391 eth);
1392 }
1393
1394 // Get the starting time (overall and per-component) of
1395 // the processing chain for this packet if performance
1396 // monitoring is turned on
1397 pktinProcTime.bootstrap(listeners);
1398 pktinProcTime.recordStartTimePktIn();
1399 Command cmd;
1400 for (IOFMessageListener listener : listeners) {
1401 if (listener instanceof IOFSwitchFilter) {
1402 if (!((IOFSwitchFilter)listener).isInterested(sw)) {
1403 continue;
1404 }
1405 }
1406
1407 pktinProcTime.recordStartTimeComp(listener);
1408 cmd = listener.receive(sw, m, bc);
1409 pktinProcTime.recordEndTimeComp(listener);
1410
1411 if (Command.STOP.equals(cmd)) {
1412 break;
1413 }
1414 }
1415 pktinProcTime.recordEndTimePktIn(sw, m, bc);
1416 } else {
1417 log.warn("Unhandled OF Message: {} from {}", m, sw);
1418 }
1419
1420 if ((bContext == null) && (bc != null)) flcontext_free(bc);
1421 }
1422 }
1423
1424 /**
1425 * Log an OpenFlow error message from a switch
1426 * @param sw The switch that sent the error
1427 * @param error The error message
1428 */
1429 @LogMessageDoc(level="ERROR",
1430 message="Error {error type} {error code} from {switch}",
1431 explanation="The switch responded with an unexpected error" +
1432 "to an OpenFlow message from the controller",
1433 recommendation="This could indicate improper network operation. " +
1434 "If the problem persists restarting the switch and " +
1435 "controller may help."
1436 )
1437 protected void logError(IOFSwitch sw, OFError error) {
1438 int etint = 0xffff & error.getErrorType();
1439 if (etint < 0 || etint >= OFErrorType.values().length) {
1440 log.error("Unknown error code {} from sw {}", etint, sw);
1441 }
1442 OFErrorType et = OFErrorType.values()[etint];
1443 switch (et) {
1444 case OFPET_HELLO_FAILED:
1445 OFHelloFailedCode hfc =
1446 OFHelloFailedCode.values()[0xffff & error.getErrorCode()];
1447 log.error("Error {} {} from {}", new Object[] {et, hfc, sw});
1448 break;
1449 case OFPET_BAD_REQUEST:
1450 OFBadRequestCode brc =
1451 OFBadRequestCode.values()[0xffff & error.getErrorCode()];
1452 log.error("Error {} {} from {}", new Object[] {et, brc, sw});
1453 break;
1454 case OFPET_BAD_ACTION:
1455 OFBadActionCode bac =
1456 OFBadActionCode.values()[0xffff & error.getErrorCode()];
1457 log.error("Error {} {} from {}", new Object[] {et, bac, sw});
1458 break;
1459 case OFPET_FLOW_MOD_FAILED:
1460 OFFlowModFailedCode fmfc =
1461 OFFlowModFailedCode.values()[0xffff & error.getErrorCode()];
1462 log.error("Error {} {} from {}", new Object[] {et, fmfc, sw});
1463 break;
1464 case OFPET_PORT_MOD_FAILED:
1465 OFPortModFailedCode pmfc =
1466 OFPortModFailedCode.values()[0xffff & error.getErrorCode()];
1467 log.error("Error {} {} from {}", new Object[] {et, pmfc, sw});
1468 break;
1469 case OFPET_QUEUE_OP_FAILED:
1470 OFQueueOpFailedCode qofc =
1471 OFQueueOpFailedCode.values()[0xffff & error.getErrorCode()];
1472 log.error("Error {} {} from {}", new Object[] {et, qofc, sw});
1473 break;
1474 default:
1475 break;
1476 }
1477 }
1478
1479 /**
1480 * Add a switch to the active switch list and call the switch listeners.
1481 * This happens either when a switch first connects (and the controller is
1482 * not in the slave role) or when the role of the controller changes from
1483 * slave to master.
1484 * @param sw the switch that has been added
1485 */
1486 // TODO: need to rethink locking and the synchronous switch update.
1487 // We can / should also handle duplicate DPIDs in connectedSwitches
1488 @LogMessageDoc(level="ERROR",
1489 message="New switch added {switch} for already-added switch {switch}",
1490 explanation="A switch with the same DPID as another switch " +
1491 "connected to the controller. This can be caused by " +
1492 "multiple switches configured with the same DPID, or " +
1493 "by a switch reconnected very quickly after " +
1494 "disconnecting.",
1495 recommendation="If this happens repeatedly, it is likely there " +
1496 "are switches with duplicate DPIDs on the network. " +
1497 "Reconfigure the appropriate switches. If it happens " +
1498 "very rarely, then it is likely this is a transient " +
1499 "network problem that can be ignored."
1500 )
1501 protected void addSwitch(IOFSwitch sw) {
1502 // TODO: is it safe to modify the HashMap without holding
1503 // the old switch's lock?
1504 OFSwitchImpl oldSw = (OFSwitchImpl) this.activeSwitches.put(sw.getId(), sw);
1505 if (sw == oldSw) {
1506 // Note == for object equality, not .equals for value
1507 log.info("New add switch for pre-existing switch {}", sw);
1508 return;
1509 }
1510
1511 if (oldSw != null) {
1512 oldSw.getListenerWriteLock().lock();
1513 try {
1514 log.error("New switch added {} for already-added switch {}",
1515 sw, oldSw);
1516 // Set the connected flag to false to suppress calling
1517 // the listeners for this switch in processOFMessage
1518 oldSw.setConnected(false);
1519
1520 oldSw.cancelAllStatisticsReplies();
1521
1522 updateInactiveSwitchInfo(oldSw);
1523
1524 // we need to clean out old switch state definitively
1525 // before adding the new switch
1526 // FIXME: It seems not completely kosher to call the
1527 // switch listeners here. I thought one of the points of
1528 // having the asynchronous switch update mechanism was so
1529 // the addedSwitch and removedSwitch were always called
1530 // from a single thread to simplify concurrency issues
1531 // for the listener.
1532 if (switchListeners != null) {
1533 for (IOFSwitchListener listener : switchListeners) {
1534 listener.removedSwitch(oldSw);
1535 }
1536 }
1537 // will eventually trigger a removeSwitch(), which will cause
1538 // a "Not removing Switch ... already removed debug message.
1539 // TODO: Figure out a way to handle this that avoids the
1540 // spurious debug message.
1541 oldSw.getChannel().close();
1542 }
1543 finally {
1544 oldSw.getListenerWriteLock().unlock();
1545 }
1546 }
1547
1548 updateActiveSwitchInfo(sw);
Pankaj Berde8557a462013-01-07 08:59:31 -08001549 swStore.update(sw.getStringId(), SwitchState.ACTIVE, DM_OPERATION.UPDATE);
Pankaj Berde0fc4e432013-01-12 09:47:22 -08001550 for (OFPhysicalPort port: sw.getPorts()) {
1551 swStore.addPort(sw.getStringId(), port);
1552 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001553 SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.ADDED);
1554 try {
1555 this.updates.put(update);
1556 } catch (InterruptedException e) {
1557 log.error("Failure adding update to queue", e);
1558 }
1559 }
1560
1561 /**
1562 * Remove a switch from the active switch list and call the switch listeners.
1563 * This happens either when the switch is disconnected or when the
1564 * controller's role for the switch changes from master to slave.
1565 * @param sw the switch that has been removed
1566 */
1567 protected void removeSwitch(IOFSwitch sw) {
1568 // No need to acquire the listener lock, since
1569 // this method is only called after netty has processed all
1570 // pending messages
1571 log.debug("removeSwitch: {}", sw);
Pankaj Berdeafb20532013-01-08 15:05:24 -08001572 swStore.update(sw.getStringId(), SwitchState.INACTIVE, DM_OPERATION.UPDATE);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001573 if (!this.activeSwitches.remove(sw.getId(), sw) || !sw.isConnected()) {
1574 log.debug("Not removing switch {}; already removed", sw);
1575 return;
1576 }
1577 // We cancel all outstanding statistics replies if the switch transition
1578 // from active. In the future we might allow statistics requests
1579 // from slave controllers. Then we need to move this cancelation
1580 // to switch disconnect
1581 sw.cancelAllStatisticsReplies();
Pankaj Berdeafb20532013-01-08 15:05:24 -08001582
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001583
1584 // FIXME: I think there's a race condition if we call updateInactiveSwitchInfo
1585 // here if role support is enabled. In that case if the switch is being
1586 // removed because we've been switched to being in the slave role, then I think
1587 // it's possible that the new master may have already been promoted to master
1588 // and written out the active switch state to storage. If we now execute
1589 // updateInactiveSwitchInfo we may wipe out all of the state that was
1590 // written out by the new master. Maybe need to revisit how we handle all
1591 // of the switch state that's written to storage.
1592
1593 updateInactiveSwitchInfo(sw);
Pankaj Berdeafb20532013-01-08 15:05:24 -08001594
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001595 SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.REMOVED);
1596 try {
1597 this.updates.put(update);
1598 } catch (InterruptedException e) {
1599 log.error("Failure adding update to queue", e);
1600 }
1601 }
1602
1603 // ***************
1604 // IFloodlightProvider
1605 // ***************
1606
1607 @Override
1608 public synchronized void addOFMessageListener(OFType type,
1609 IOFMessageListener listener) {
1610 ListenerDispatcher<OFType, IOFMessageListener> ldd =
1611 messageListeners.get(type);
1612 if (ldd == null) {
1613 ldd = new ListenerDispatcher<OFType, IOFMessageListener>();
1614 messageListeners.put(type, ldd);
1615 }
1616 ldd.addListener(type, listener);
1617 }
1618
1619 @Override
1620 public synchronized void removeOFMessageListener(OFType type,
1621 IOFMessageListener listener) {
1622 ListenerDispatcher<OFType, IOFMessageListener> ldd =
1623 messageListeners.get(type);
1624 if (ldd != null) {
1625 ldd.removeListener(listener);
1626 }
1627 }
1628
1629 private void logListeners() {
1630 for (Map.Entry<OFType,
1631 ListenerDispatcher<OFType,
1632 IOFMessageListener>> entry
1633 : messageListeners.entrySet()) {
1634
1635 OFType type = entry.getKey();
1636 ListenerDispatcher<OFType, IOFMessageListener> ldd =
1637 entry.getValue();
1638
1639 StringBuffer sb = new StringBuffer();
1640 sb.append("OFListeners for ");
1641 sb.append(type);
1642 sb.append(": ");
1643 for (IOFMessageListener l : ldd.getOrderedListeners()) {
1644 sb.append(l.getName());
1645 sb.append(",");
1646 }
1647 log.debug(sb.toString());
1648 }
1649 }
1650
1651 public void removeOFMessageListeners(OFType type) {
1652 messageListeners.remove(type);
1653 }
1654
1655 @Override
1656 public Map<Long, IOFSwitch> getSwitches() {
1657 return Collections.unmodifiableMap(this.activeSwitches);
1658 }
1659
1660 @Override
1661 public void addOFSwitchListener(IOFSwitchListener listener) {
1662 this.switchListeners.add(listener);
1663 }
1664
1665 @Override
1666 public void removeOFSwitchListener(IOFSwitchListener listener) {
1667 this.switchListeners.remove(listener);
1668 }
1669
1670 @Override
1671 public Map<OFType, List<IOFMessageListener>> getListeners() {
1672 Map<OFType, List<IOFMessageListener>> lers =
1673 new HashMap<OFType, List<IOFMessageListener>>();
1674 for(Entry<OFType, ListenerDispatcher<OFType, IOFMessageListener>> e :
1675 messageListeners.entrySet()) {
1676 lers.put(e.getKey(), e.getValue().getOrderedListeners());
1677 }
1678 return Collections.unmodifiableMap(lers);
1679 }
1680
1681 @Override
1682 @LogMessageDocs({
1683 @LogMessageDoc(message="Failed to inject OFMessage {message} onto " +
1684 "a null switch",
1685 explanation="Failed to process a message because the switch " +
1686 " is no longer connected."),
1687 @LogMessageDoc(level="ERROR",
1688 message="Error reinjecting OFMessage on switch {switch}",
1689 explanation="An I/O error occured while attempting to " +
1690 "process an OpenFlow message",
1691 recommendation=LogMessageDoc.CHECK_SWITCH)
1692 })
1693 public boolean injectOfMessage(IOFSwitch sw, OFMessage msg,
1694 FloodlightContext bc) {
1695 if (sw == null) {
1696 log.info("Failed to inject OFMessage {} onto a null switch", msg);
1697 return false;
1698 }
1699
1700 // FIXME: Do we need to be able to inject messages to switches
1701 // where we're the slave controller (i.e. they're connected but
1702 // not active)?
1703 // FIXME: Don't we need synchronization logic here so we're holding
1704 // the listener read lock when we call handleMessage? After some
1705 // discussions it sounds like the right thing to do here would be to
1706 // inject the message as a netty upstream channel event so it goes
1707 // through the normal netty event processing, including being
1708 // handled
1709 if (!activeSwitches.containsKey(sw.getId())) return false;
1710
1711 try {
1712 // Pass Floodlight context to the handleMessages()
1713 handleMessage(sw, msg, bc);
1714 } catch (IOException e) {
1715 log.error("Error reinjecting OFMessage on switch {}",
1716 HexString.toHexString(sw.getId()));
1717 return false;
1718 }
1719 return true;
1720 }
1721
1722 @Override
1723 @LogMessageDoc(message="Calling System.exit",
1724 explanation="The controller is terminating")
1725 public synchronized void terminate() {
1726 log.info("Calling System.exit");
1727 System.exit(1);
1728 }
1729
1730 @Override
1731 public boolean injectOfMessage(IOFSwitch sw, OFMessage msg) {
1732 // call the overloaded version with floodlight context set to null
1733 return injectOfMessage(sw, msg, null);
1734 }
1735
1736 @Override
1737 public void handleOutgoingMessage(IOFSwitch sw, OFMessage m,
1738 FloodlightContext bc) {
1739 if (log.isTraceEnabled()) {
1740 String str = OFMessage.getDataAsString(sw, m, bc);
1741 log.trace("{}", str);
1742 }
1743
1744 List<IOFMessageListener> listeners = null;
1745 if (messageListeners.containsKey(m.getType())) {
1746 listeners =
1747 messageListeners.get(m.getType()).getOrderedListeners();
1748 }
1749
1750 if (listeners != null) {
1751 for (IOFMessageListener listener : listeners) {
1752 if (listener instanceof IOFSwitchFilter) {
1753 if (!((IOFSwitchFilter)listener).isInterested(sw)) {
1754 continue;
1755 }
1756 }
1757 if (Command.STOP.equals(listener.receive(sw, m, bc))) {
1758 break;
1759 }
1760 }
1761 }
1762 }
1763
1764 @Override
1765 public BasicFactory getOFMessageFactory() {
1766 return factory;
1767 }
1768
1769 @Override
1770 public String getControllerId() {
1771 return controllerId;
1772 }
1773
1774 // **************
1775 // Initialization
1776 // **************
1777
1778 protected void updateAllInactiveSwitchInfo() {
1779 if (role == Role.SLAVE) {
1780 return;
1781 }
1782 String controllerId = getControllerId();
1783 String[] switchColumns = { SWITCH_DATAPATH_ID,
1784 SWITCH_CONTROLLER_ID,
1785 SWITCH_ACTIVE };
1786 String[] portColumns = { PORT_ID, PORT_SWITCH };
1787 IResultSet switchResultSet = null;
1788 try {
1789 OperatorPredicate op =
1790 new OperatorPredicate(SWITCH_CONTROLLER_ID,
1791 OperatorPredicate.Operator.EQ,
1792 controllerId);
1793 switchResultSet =
1794 storageSource.executeQuery(SWITCH_TABLE_NAME,
1795 switchColumns,
1796 op, null);
1797 while (switchResultSet.next()) {
1798 IResultSet portResultSet = null;
1799 try {
1800 String datapathId =
1801 switchResultSet.getString(SWITCH_DATAPATH_ID);
1802 switchResultSet.setBoolean(SWITCH_ACTIVE, Boolean.FALSE);
1803 op = new OperatorPredicate(PORT_SWITCH,
1804 OperatorPredicate.Operator.EQ,
1805 datapathId);
1806 portResultSet =
1807 storageSource.executeQuery(PORT_TABLE_NAME,
1808 portColumns,
1809 op, null);
1810 while (portResultSet.next()) {
1811 portResultSet.deleteRow();
1812 }
1813 portResultSet.save();
1814 }
1815 finally {
1816 if (portResultSet != null)
1817 portResultSet.close();
1818 }
1819 }
1820 switchResultSet.save();
1821 }
1822 finally {
1823 if (switchResultSet != null)
1824 switchResultSet.close();
1825 }
1826 }
1827
1828 protected void updateControllerInfo() {
1829 updateAllInactiveSwitchInfo();
1830
1831 // Write out the controller info to the storage source
1832 Map<String, Object> controllerInfo = new HashMap<String, Object>();
1833 String id = getControllerId();
1834 controllerInfo.put(CONTROLLER_ID, id);
1835 storageSource.updateRow(CONTROLLER_TABLE_NAME, controllerInfo);
1836 }
1837
1838 protected void updateActiveSwitchInfo(IOFSwitch sw) {
1839 if (role == Role.SLAVE) {
1840 return;
1841 }
1842 // Obtain the row info for the switch
1843 Map<String, Object> switchInfo = new HashMap<String, Object>();
1844 String datapathIdString = sw.getStringId();
1845 switchInfo.put(SWITCH_DATAPATH_ID, datapathIdString);
1846 String controllerId = getControllerId();
1847 switchInfo.put(SWITCH_CONTROLLER_ID, controllerId);
1848 Date connectedSince = sw.getConnectedSince();
1849 switchInfo.put(SWITCH_CONNECTED_SINCE, connectedSince);
1850 Channel channel = sw.getChannel();
1851 SocketAddress socketAddress = channel.getRemoteAddress();
1852 if (socketAddress != null) {
1853 String socketAddressString = socketAddress.toString();
1854 switchInfo.put(SWITCH_SOCKET_ADDRESS, socketAddressString);
1855 if (socketAddress instanceof InetSocketAddress) {
1856 InetSocketAddress inetSocketAddress =
1857 (InetSocketAddress)socketAddress;
1858 InetAddress inetAddress = inetSocketAddress.getAddress();
1859 String ip = inetAddress.getHostAddress();
1860 switchInfo.put(SWITCH_IP, ip);
1861 }
1862 }
1863
1864 // Write out the switch features info
1865 long capabilities = U32.f(sw.getCapabilities());
1866 switchInfo.put(SWITCH_CAPABILITIES, capabilities);
1867 long buffers = U32.f(sw.getBuffers());
1868 switchInfo.put(SWITCH_BUFFERS, buffers);
1869 long tables = U32.f(sw.getTables());
1870 switchInfo.put(SWITCH_TABLES, tables);
1871 long actions = U32.f(sw.getActions());
1872 switchInfo.put(SWITCH_ACTIONS, actions);
1873 switchInfo.put(SWITCH_ACTIVE, Boolean.TRUE);
1874
1875 // Update the switch
1876 storageSource.updateRowAsync(SWITCH_TABLE_NAME, switchInfo);
1877
1878 // Update the ports
1879 for (OFPhysicalPort port: sw.getPorts()) {
1880 updatePortInfo(sw, port);
1881 }
1882 }
1883
1884 protected void updateInactiveSwitchInfo(IOFSwitch sw) {
1885 if (role == Role.SLAVE) {
1886 return;
1887 }
1888 log.debug("Update DB with inactiveSW {}", sw);
1889 // Update the controller info in the storage source to be inactive
1890 Map<String, Object> switchInfo = new HashMap<String, Object>();
1891 String datapathIdString = sw.getStringId();
1892 switchInfo.put(SWITCH_DATAPATH_ID, datapathIdString);
1893 //switchInfo.put(SWITCH_CONNECTED_SINCE, null);
1894 switchInfo.put(SWITCH_ACTIVE, Boolean.FALSE);
1895 storageSource.updateRowAsync(SWITCH_TABLE_NAME, switchInfo);
1896 }
1897
1898 protected void updatePortInfo(IOFSwitch sw, OFPhysicalPort port) {
1899 if (role == Role.SLAVE) {
1900 return;
1901 }
1902 String datapathIdString = sw.getStringId();
1903 Map<String, Object> portInfo = new HashMap<String, Object>();
1904 int portNumber = U16.f(port.getPortNumber());
1905 String id = datapathIdString + "|" + portNumber;
1906 portInfo.put(PORT_ID, id);
1907 portInfo.put(PORT_SWITCH, datapathIdString);
1908 portInfo.put(PORT_NUMBER, portNumber);
1909 byte[] hardwareAddress = port.getHardwareAddress();
1910 String hardwareAddressString = HexString.toHexString(hardwareAddress);
1911 portInfo.put(PORT_HARDWARE_ADDRESS, hardwareAddressString);
1912 String name = port.getName();
1913 portInfo.put(PORT_NAME, name);
1914 long config = U32.f(port.getConfig());
1915 portInfo.put(PORT_CONFIG, config);
1916 long state = U32.f(port.getState());
1917 portInfo.put(PORT_STATE, state);
1918 long currentFeatures = U32.f(port.getCurrentFeatures());
1919 portInfo.put(PORT_CURRENT_FEATURES, currentFeatures);
1920 long advertisedFeatures = U32.f(port.getAdvertisedFeatures());
1921 portInfo.put(PORT_ADVERTISED_FEATURES, advertisedFeatures);
1922 long supportedFeatures = U32.f(port.getSupportedFeatures());
1923 portInfo.put(PORT_SUPPORTED_FEATURES, supportedFeatures);
1924 long peerFeatures = U32.f(port.getPeerFeatures());
1925 portInfo.put(PORT_PEER_FEATURES, peerFeatures);
1926 storageSource.updateRowAsync(PORT_TABLE_NAME, portInfo);
1927 }
1928
1929 /**
1930 * Read switch port data from storage and write it into a switch object
1931 * @param sw the switch to update
1932 */
1933 protected void readSwitchPortStateFromStorage(OFSwitchImpl sw) {
1934 OperatorPredicate op =
1935 new OperatorPredicate(PORT_SWITCH,
1936 OperatorPredicate.Operator.EQ,
1937 sw.getStringId());
1938 IResultSet portResultSet =
1939 storageSource.executeQuery(PORT_TABLE_NAME,
1940 null, op, null);
1941 //Map<Short, OFPhysicalPort> oldports =
1942 // new HashMap<Short, OFPhysicalPort>();
1943 //oldports.putAll(sw.getPorts());
1944
1945 while (portResultSet.next()) {
1946 try {
1947 OFPhysicalPort p = new OFPhysicalPort();
1948 p.setPortNumber((short)portResultSet.getInt(PORT_NUMBER));
1949 p.setName(portResultSet.getString(PORT_NAME));
1950 p.setConfig((int)portResultSet.getLong(PORT_CONFIG));
1951 p.setState((int)portResultSet.getLong(PORT_STATE));
1952 String portMac = portResultSet.getString(PORT_HARDWARE_ADDRESS);
1953 p.setHardwareAddress(HexString.fromHexString(portMac));
1954 p.setCurrentFeatures((int)portResultSet.
1955 getLong(PORT_CURRENT_FEATURES));
1956 p.setAdvertisedFeatures((int)portResultSet.
1957 getLong(PORT_ADVERTISED_FEATURES));
1958 p.setSupportedFeatures((int)portResultSet.
1959 getLong(PORT_SUPPORTED_FEATURES));
1960 p.setPeerFeatures((int)portResultSet.
1961 getLong(PORT_PEER_FEATURES));
1962 //oldports.remove(Short.valueOf(p.getPortNumber()));
1963 sw.setPort(p);
1964 } catch (NullPointerException e) {
1965 // ignore
1966 }
1967 }
1968 SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.PORTCHANGED);
1969 try {
1970 this.updates.put(update);
1971 } catch (InterruptedException e) {
1972 log.error("Failure adding update to queue", e);
1973 }
1974 }
1975
1976 protected void removePortInfo(IOFSwitch sw, short portNumber) {
1977 if (role == Role.SLAVE) {
1978 return;
1979 }
1980 String datapathIdString = sw.getStringId();
1981 String id = datapathIdString + "|" + portNumber;
1982 storageSource.deleteRowAsync(PORT_TABLE_NAME, id);
1983 }
1984
1985 /**
1986 * Sets the initial role based on properties in the config params.
1987 * It looks for two different properties.
1988 * If the "role" property is specified then the value should be
1989 * either "EQUAL", "MASTER", or "SLAVE" and the role of the
1990 * controller is set to the specified value. If the "role" property
1991 * is not specified then it looks next for the "role.path" property.
1992 * In this case the value should be the path to a property file in
1993 * the file system that contains a property called "floodlight.role"
1994 * which can be one of the values listed above for the "role" property.
1995 * The idea behind the "role.path" mechanism is that you have some
1996 * separate heartbeat and master controller election algorithm that
1997 * determines the role of the controller. When a role transition happens,
1998 * it updates the current role in the file specified by the "role.path"
1999 * file. Then if floodlight restarts for some reason it can get the
2000 * correct current role of the controller from the file.
2001 * @param configParams The config params for the FloodlightProvider service
2002 * @return A valid role if role information is specified in the
2003 * config params, otherwise null
2004 */
2005 @LogMessageDocs({
2006 @LogMessageDoc(message="Controller role set to {role}",
2007 explanation="Setting the initial HA role to "),
2008 @LogMessageDoc(level="ERROR",
2009 message="Invalid current role value: {role}",
2010 explanation="An invalid HA role value was read from the " +
2011 "properties file",
2012 recommendation=LogMessageDoc.CHECK_CONTROLLER)
2013 })
2014 protected Role getInitialRole(Map<String, String> configParams) {
2015 Role role = null;
2016 String roleString = configParams.get("role");
2017 if (roleString == null) {
2018 String rolePath = configParams.get("rolepath");
2019 if (rolePath != null) {
2020 Properties properties = new Properties();
2021 try {
2022 properties.load(new FileInputStream(rolePath));
2023 roleString = properties.getProperty("floodlight.role");
2024 }
2025 catch (IOException exc) {
2026 // Don't treat it as an error if the file specified by the
2027 // rolepath property doesn't exist. This lets us enable the
2028 // HA mechanism by just creating/setting the floodlight.role
2029 // property in that file without having to modify the
2030 // floodlight properties.
2031 }
2032 }
2033 }
2034
2035 if (roleString != null) {
2036 // Canonicalize the string to the form used for the enum constants
2037 roleString = roleString.trim().toUpperCase();
2038 try {
2039 role = Role.valueOf(roleString);
2040 }
2041 catch (IllegalArgumentException exc) {
2042 log.error("Invalid current role value: {}", roleString);
2043 }
2044 }
2045
2046 log.info("Controller role set to {}", role);
2047
2048 return role;
2049 }
2050
2051 /**
2052 * Tell controller that we're ready to accept switches loop
2053 * @throws IOException
2054 */
2055 @LogMessageDocs({
2056 @LogMessageDoc(message="Listening for switch connections on {address}",
2057 explanation="The controller is ready and listening for new" +
2058 " switch connections"),
2059 @LogMessageDoc(message="Storage exception in controller " +
2060 "updates loop; terminating process",
2061 explanation=ERROR_DATABASE,
2062 recommendation=LogMessageDoc.CHECK_CONTROLLER),
2063 @LogMessageDoc(level="ERROR",
2064 message="Exception in controller updates loop",
2065 explanation="Failed to dispatch controller event",
2066 recommendation=LogMessageDoc.GENERIC_ACTION)
2067 })
2068 public void run() {
2069 if (log.isDebugEnabled()) {
2070 logListeners();
2071 }
2072
2073 try {
2074 final ServerBootstrap bootstrap = createServerBootStrap();
2075
2076 bootstrap.setOption("reuseAddr", true);
2077 bootstrap.setOption("child.keepAlive", true);
2078 bootstrap.setOption("child.tcpNoDelay", true);
2079 bootstrap.setOption("child.sendBufferSize", Controller.SEND_BUFFER_SIZE);
2080
2081 ChannelPipelineFactory pfact =
2082 new OpenflowPipelineFactory(this, null);
2083 bootstrap.setPipelineFactory(pfact);
2084 InetSocketAddress sa = new InetSocketAddress(openFlowPort);
2085 final ChannelGroup cg = new DefaultChannelGroup();
2086 cg.add(bootstrap.bind(sa));
2087
2088 log.info("Listening for switch connections on {}", sa);
2089 } catch (Exception e) {
2090 throw new RuntimeException(e);
2091 }
2092
2093 // main loop
2094 while (true) {
2095 try {
2096 IUpdate update = updates.take();
2097 update.dispatch();
2098 } catch (InterruptedException e) {
2099 return;
2100 } catch (StorageException e) {
2101 log.error("Storage exception in controller " +
2102 "updates loop; terminating process", e);
2103 return;
2104 } catch (Exception e) {
2105 log.error("Exception in controller updates loop", e);
2106 }
2107 }
2108 }
2109
2110 private ServerBootstrap createServerBootStrap() {
2111 if (workerThreads == 0) {
2112 return new ServerBootstrap(
2113 new NioServerSocketChannelFactory(
2114 Executors.newCachedThreadPool(),
2115 Executors.newCachedThreadPool()));
2116 } else {
2117 return new ServerBootstrap(
2118 new NioServerSocketChannelFactory(
2119 Executors.newCachedThreadPool(),
2120 Executors.newCachedThreadPool(), workerThreads));
2121 }
2122 }
2123
2124 public void setConfigParams(Map<String, String> configParams) {
2125 String ofPort = configParams.get("openflowport");
2126 if (ofPort != null) {
2127 this.openFlowPort = Integer.parseInt(ofPort);
2128 }
2129 log.debug("OpenFlow port set to {}", this.openFlowPort);
2130 String threads = configParams.get("workerthreads");
2131 if (threads != null) {
2132 this.workerThreads = Integer.parseInt(threads);
2133 }
2134 log.debug("Number of worker threads set to {}", this.workerThreads);
2135 String controllerId = configParams.get("controllerid");
2136 if (controllerId != null) {
2137 this.controllerId = controllerId;
2138 }
Jonathan Hartd10008d2013-02-23 17:04:08 -08002139 else {
2140 //Try to get the hostname of the machine and use that for controller ID
2141 try {
2142 String hostname = java.net.InetAddress.getLocalHost().getHostName();
2143 this.controllerId = hostname;
2144 } catch (UnknownHostException e) {
2145 // Can't get hostname, we'll just use the default
2146 }
2147 }
2148
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08002149 log.debug("ControllerId set to {}", this.controllerId);
2150 }
2151
2152 private void initVendorMessages() {
2153 // Configure openflowj to be able to parse the role request/reply
2154 // vendor messages.
2155 OFBasicVendorId niciraVendorId = new OFBasicVendorId(
2156 OFNiciraVendorData.NX_VENDOR_ID, 4);
2157 OFVendorId.registerVendorId(niciraVendorId);
2158 OFBasicVendorDataType roleRequestVendorData =
2159 new OFBasicVendorDataType(
2160 OFRoleRequestVendorData.NXT_ROLE_REQUEST,
2161 OFRoleRequestVendorData.getInstantiable());
2162 niciraVendorId.registerVendorDataType(roleRequestVendorData);
2163 OFBasicVendorDataType roleReplyVendorData =
2164 new OFBasicVendorDataType(
2165 OFRoleReplyVendorData.NXT_ROLE_REPLY,
2166 OFRoleReplyVendorData.getInstantiable());
2167 niciraVendorId.registerVendorDataType(roleReplyVendorData);
2168 }
2169
2170 /**
2171 * Initialize internal data structures
2172 */
2173 public void init(Map<String, String> configParams) {
2174 // These data structures are initialized here because other
2175 // module's startUp() might be called before ours
2176 this.messageListeners =
2177 new ConcurrentHashMap<OFType,
2178 ListenerDispatcher<OFType,
2179 IOFMessageListener>>();
2180 this.switchListeners = new CopyOnWriteArraySet<IOFSwitchListener>();
2181 this.haListeners = new CopyOnWriteArraySet<IHAListener>();
2182 this.activeSwitches = new ConcurrentHashMap<Long, IOFSwitch>();
2183 this.connectedSwitches = new HashSet<OFSwitchImpl>();
2184 this.controllerNodeIPsCache = new HashMap<String, String>();
2185 this.updates = new LinkedBlockingQueue<IUpdate>();
2186 this.factory = new BasicFactory();
2187 this.providerMap = new HashMap<String, List<IInfoProvider>>();
2188 setConfigParams(configParams);
Jonathan Hartcc957a02013-02-26 10:39:04 -08002189 //this.role = getInitialRole(configParams);
2190 //Set the controller's role to MASTER so it always tries to do role requests.
2191 this.role = Role.MASTER;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08002192 this.roleChanger = new RoleChanger();
2193 initVendorMessages();
2194 this.systemStartTime = System.currentTimeMillis();
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08002195 }
2196
2197 /**
2198 * Startup all of the controller's components
2199 */
2200 @LogMessageDoc(message="Waiting for storage source",
2201 explanation="The system database is not yet ready",
2202 recommendation="If this message persists, this indicates " +
2203 "that the system database has failed to start. " +
2204 LogMessageDoc.CHECK_CONTROLLER)
2205 public void startupComponents() {
Jonathan Hartd10008d2013-02-23 17:04:08 -08002206 try {
2207 registryService.registerController(controllerId);
2208 } catch (RegistryException e2) {
2209 log.warn("Registry service error: {}", e2.getMessage());
2210 }
2211
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08002212 // Create the table names we use
2213 storageSource.createTable(CONTROLLER_TABLE_NAME, null);
2214 storageSource.createTable(SWITCH_TABLE_NAME, null);
2215 storageSource.createTable(PORT_TABLE_NAME, null);
2216 storageSource.createTable(CONTROLLER_INTERFACE_TABLE_NAME, null);
2217 storageSource.createTable(SWITCH_CONFIG_TABLE_NAME, null);
2218 storageSource.setTablePrimaryKeyName(CONTROLLER_TABLE_NAME,
2219 CONTROLLER_ID);
2220 storageSource.setTablePrimaryKeyName(SWITCH_TABLE_NAME,
2221 SWITCH_DATAPATH_ID);
2222 storageSource.setTablePrimaryKeyName(PORT_TABLE_NAME, PORT_ID);
2223 storageSource.setTablePrimaryKeyName(CONTROLLER_INTERFACE_TABLE_NAME,
2224 CONTROLLER_INTERFACE_ID);
2225 storageSource.addListener(CONTROLLER_INTERFACE_TABLE_NAME, this);
2226
2227 while (true) {
2228 try {
2229 updateControllerInfo();
2230 break;
2231 }
2232 catch (StorageException e) {
2233 log.info("Waiting for storage source");
2234 try {
2235 Thread.sleep(1000);
2236 } catch (InterruptedException e1) {
2237 }
2238 }
2239 }
2240
2241 // Add our REST API
2242 restApi.addRestletRoutable(new CoreWebRoutable());
2243 }
2244
2245 @Override
2246 public void addInfoProvider(String type, IInfoProvider provider) {
2247 if (!providerMap.containsKey(type)) {
2248 providerMap.put(type, new ArrayList<IInfoProvider>());
2249 }
2250 providerMap.get(type).add(provider);
2251 }
2252
2253 @Override
2254 public void removeInfoProvider(String type, IInfoProvider provider) {
2255 if (!providerMap.containsKey(type)) {
2256 log.debug("Provider type {} doesn't exist.", type);
2257 return;
2258 }
2259
2260 providerMap.get(type).remove(provider);
2261 }
2262
2263 public Map<String, Object> getControllerInfo(String type) {
2264 if (!providerMap.containsKey(type)) return null;
2265
2266 Map<String, Object> result = new LinkedHashMap<String, Object>();
2267 for (IInfoProvider provider : providerMap.get(type)) {
2268 result.putAll(provider.getInfo(type));
2269 }
2270
2271 return result;
2272 }
2273
2274 @Override
2275 public void addHAListener(IHAListener listener) {
2276 this.haListeners.add(listener);
2277 }
2278
2279 @Override
2280 public void removeHAListener(IHAListener listener) {
2281 this.haListeners.remove(listener);
2282 }
2283
2284
2285 /**
2286 * Handle changes to the controller nodes IPs and dispatch update.
2287 */
2288 @SuppressWarnings("unchecked")
2289 protected void handleControllerNodeIPChanges() {
2290 HashMap<String,String> curControllerNodeIPs = new HashMap<String,String>();
2291 HashMap<String,String> addedControllerNodeIPs = new HashMap<String,String>();
2292 HashMap<String,String> removedControllerNodeIPs =new HashMap<String,String>();
2293 String[] colNames = { CONTROLLER_INTERFACE_CONTROLLER_ID,
2294 CONTROLLER_INTERFACE_TYPE,
2295 CONTROLLER_INTERFACE_NUMBER,
2296 CONTROLLER_INTERFACE_DISCOVERED_IP };
2297 synchronized(controllerNodeIPsCache) {
2298 // We currently assume that interface Ethernet0 is the relevant
2299 // controller interface. Might change.
2300 // We could (should?) implement this using
2301 // predicates, but creating the individual and compound predicate
2302 // seems more overhead then just checking every row. Particularly,
2303 // since the number of rows is small and changes infrequent
2304 IResultSet res = storageSource.executeQuery(CONTROLLER_INTERFACE_TABLE_NAME,
2305 colNames,null, null);
2306 while (res.next()) {
2307 if (res.getString(CONTROLLER_INTERFACE_TYPE).equals("Ethernet") &&
2308 res.getInt(CONTROLLER_INTERFACE_NUMBER) == 0) {
2309 String controllerID = res.getString(CONTROLLER_INTERFACE_CONTROLLER_ID);
2310 String discoveredIP = res.getString(CONTROLLER_INTERFACE_DISCOVERED_IP);
2311 String curIP = controllerNodeIPsCache.get(controllerID);
2312
2313 curControllerNodeIPs.put(controllerID, discoveredIP);
2314 if (curIP == null) {
2315 // new controller node IP
2316 addedControllerNodeIPs.put(controllerID, discoveredIP);
2317 }
2318 else if (curIP != discoveredIP) {
2319 // IP changed
2320 removedControllerNodeIPs.put(controllerID, curIP);
2321 addedControllerNodeIPs.put(controllerID, discoveredIP);
2322 }
2323 }
2324 }
2325 // Now figure out if rows have been deleted. We can't use the
2326 // rowKeys from rowsDeleted directly, since the tables primary
2327 // key is a compound that we can't disassemble
2328 Set<String> curEntries = curControllerNodeIPs.keySet();
2329 Set<String> removedEntries = controllerNodeIPsCache.keySet();
2330 removedEntries.removeAll(curEntries);
2331 for (String removedControllerID : removedEntries)
2332 removedControllerNodeIPs.put(removedControllerID, controllerNodeIPsCache.get(removedControllerID));
2333 controllerNodeIPsCache = (HashMap<String, String>) curControllerNodeIPs.clone();
2334 HAControllerNodeIPUpdate update = new HAControllerNodeIPUpdate(
2335 curControllerNodeIPs, addedControllerNodeIPs,
2336 removedControllerNodeIPs);
2337 if (!removedControllerNodeIPs.isEmpty() || !addedControllerNodeIPs.isEmpty()) {
2338 try {
2339 this.updates.put(update);
2340 } catch (InterruptedException e) {
2341 log.error("Failure adding update to queue", e);
2342 }
2343 }
2344 }
2345 }
2346
2347 @Override
2348 public Map<String, String> getControllerNodeIPs() {
2349 // We return a copy of the mapping so we can guarantee that
2350 // the mapping return is the same as one that will be (or was)
2351 // dispatched to IHAListeners
2352 HashMap<String,String> retval = new HashMap<String,String>();
2353 synchronized(controllerNodeIPsCache) {
2354 retval.putAll(controllerNodeIPsCache);
2355 }
2356 return retval;
2357 }
2358
2359 @Override
2360 public void rowsModified(String tableName, Set<Object> rowKeys) {
2361 if (tableName.equals(CONTROLLER_INTERFACE_TABLE_NAME)) {
2362 handleControllerNodeIPChanges();
2363 }
2364
2365 }
2366
2367 @Override
2368 public void rowsDeleted(String tableName, Set<Object> rowKeys) {
2369 if (tableName.equals(CONTROLLER_INTERFACE_TABLE_NAME)) {
2370 handleControllerNodeIPChanges();
2371 }
2372 }
2373
2374 @Override
2375 public long getSystemStartTime() {
2376 return (this.systemStartTime);
2377 }
2378
2379 @Override
2380 public void setAlwaysClearFlowsOnSwAdd(boolean value) {
2381 this.alwaysClearFlowsOnSwAdd = value;
2382 }
2383
2384 public boolean getAlwaysClearFlowsOnSwAdd() {
2385 return this.alwaysClearFlowsOnSwAdd;
2386 }
2387}