blob: 3e657d1eddb9223c8b671f282dfc50042e27aa27 [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 Berdef8ad2852013-02-27 17:06:14 -08001549 if (registryService.hasControl(sw.getId())) {
1550 swStore.update(sw.getStringId(), SwitchState.ACTIVE, DM_OPERATION.UPDATE);
1551 for (OFPhysicalPort port: sw.getPorts()) {
1552 swStore.addPort(sw.getStringId(), port);
1553 }
Pankaj Berde0fc4e432013-01-12 09:47:22 -08001554 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001555 SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.ADDED);
1556 try {
1557 this.updates.put(update);
1558 } catch (InterruptedException e) {
1559 log.error("Failure adding update to queue", e);
1560 }
1561 }
1562
1563 /**
1564 * Remove a switch from the active switch list and call the switch listeners.
1565 * This happens either when the switch is disconnected or when the
1566 * controller's role for the switch changes from master to slave.
1567 * @param sw the switch that has been removed
1568 */
1569 protected void removeSwitch(IOFSwitch sw) {
1570 // No need to acquire the listener lock, since
1571 // this method is only called after netty has processed all
1572 // pending messages
1573 log.debug("removeSwitch: {}", sw);
Pankaj Berdef8ad2852013-02-27 17:06:14 -08001574 if (registryService.hasControl(sw.getId())) {
1575 swStore.update(sw.getStringId(), SwitchState.INACTIVE, DM_OPERATION.UPDATE);
1576 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001577 if (!this.activeSwitches.remove(sw.getId(), sw) || !sw.isConnected()) {
1578 log.debug("Not removing switch {}; already removed", sw);
1579 return;
1580 }
1581 // We cancel all outstanding statistics replies if the switch transition
1582 // from active. In the future we might allow statistics requests
1583 // from slave controllers. Then we need to move this cancelation
1584 // to switch disconnect
1585 sw.cancelAllStatisticsReplies();
Pankaj Berdeafb20532013-01-08 15:05:24 -08001586
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001587
1588 // FIXME: I think there's a race condition if we call updateInactiveSwitchInfo
1589 // here if role support is enabled. In that case if the switch is being
1590 // removed because we've been switched to being in the slave role, then I think
1591 // it's possible that the new master may have already been promoted to master
1592 // and written out the active switch state to storage. If we now execute
1593 // updateInactiveSwitchInfo we may wipe out all of the state that was
1594 // written out by the new master. Maybe need to revisit how we handle all
1595 // of the switch state that's written to storage.
1596
1597 updateInactiveSwitchInfo(sw);
Pankaj Berdeafb20532013-01-08 15:05:24 -08001598
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001599 SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.REMOVED);
1600 try {
1601 this.updates.put(update);
1602 } catch (InterruptedException e) {
1603 log.error("Failure adding update to queue", e);
1604 }
1605 }
1606
1607 // ***************
1608 // IFloodlightProvider
1609 // ***************
1610
1611 @Override
1612 public synchronized void addOFMessageListener(OFType type,
1613 IOFMessageListener listener) {
1614 ListenerDispatcher<OFType, IOFMessageListener> ldd =
1615 messageListeners.get(type);
1616 if (ldd == null) {
1617 ldd = new ListenerDispatcher<OFType, IOFMessageListener>();
1618 messageListeners.put(type, ldd);
1619 }
1620 ldd.addListener(type, listener);
1621 }
1622
1623 @Override
1624 public synchronized void removeOFMessageListener(OFType type,
1625 IOFMessageListener listener) {
1626 ListenerDispatcher<OFType, IOFMessageListener> ldd =
1627 messageListeners.get(type);
1628 if (ldd != null) {
1629 ldd.removeListener(listener);
1630 }
1631 }
1632
1633 private void logListeners() {
1634 for (Map.Entry<OFType,
1635 ListenerDispatcher<OFType,
1636 IOFMessageListener>> entry
1637 : messageListeners.entrySet()) {
1638
1639 OFType type = entry.getKey();
1640 ListenerDispatcher<OFType, IOFMessageListener> ldd =
1641 entry.getValue();
1642
1643 StringBuffer sb = new StringBuffer();
1644 sb.append("OFListeners for ");
1645 sb.append(type);
1646 sb.append(": ");
1647 for (IOFMessageListener l : ldd.getOrderedListeners()) {
1648 sb.append(l.getName());
1649 sb.append(",");
1650 }
1651 log.debug(sb.toString());
1652 }
1653 }
1654
1655 public void removeOFMessageListeners(OFType type) {
1656 messageListeners.remove(type);
1657 }
1658
1659 @Override
1660 public Map<Long, IOFSwitch> getSwitches() {
1661 return Collections.unmodifiableMap(this.activeSwitches);
1662 }
1663
1664 @Override
1665 public void addOFSwitchListener(IOFSwitchListener listener) {
1666 this.switchListeners.add(listener);
1667 }
1668
1669 @Override
1670 public void removeOFSwitchListener(IOFSwitchListener listener) {
1671 this.switchListeners.remove(listener);
1672 }
1673
1674 @Override
1675 public Map<OFType, List<IOFMessageListener>> getListeners() {
1676 Map<OFType, List<IOFMessageListener>> lers =
1677 new HashMap<OFType, List<IOFMessageListener>>();
1678 for(Entry<OFType, ListenerDispatcher<OFType, IOFMessageListener>> e :
1679 messageListeners.entrySet()) {
1680 lers.put(e.getKey(), e.getValue().getOrderedListeners());
1681 }
1682 return Collections.unmodifiableMap(lers);
1683 }
1684
1685 @Override
1686 @LogMessageDocs({
1687 @LogMessageDoc(message="Failed to inject OFMessage {message} onto " +
1688 "a null switch",
1689 explanation="Failed to process a message because the switch " +
1690 " is no longer connected."),
1691 @LogMessageDoc(level="ERROR",
1692 message="Error reinjecting OFMessage on switch {switch}",
1693 explanation="An I/O error occured while attempting to " +
1694 "process an OpenFlow message",
1695 recommendation=LogMessageDoc.CHECK_SWITCH)
1696 })
1697 public boolean injectOfMessage(IOFSwitch sw, OFMessage msg,
1698 FloodlightContext bc) {
1699 if (sw == null) {
1700 log.info("Failed to inject OFMessage {} onto a null switch", msg);
1701 return false;
1702 }
1703
1704 // FIXME: Do we need to be able to inject messages to switches
1705 // where we're the slave controller (i.e. they're connected but
1706 // not active)?
1707 // FIXME: Don't we need synchronization logic here so we're holding
1708 // the listener read lock when we call handleMessage? After some
1709 // discussions it sounds like the right thing to do here would be to
1710 // inject the message as a netty upstream channel event so it goes
1711 // through the normal netty event processing, including being
1712 // handled
1713 if (!activeSwitches.containsKey(sw.getId())) return false;
1714
1715 try {
1716 // Pass Floodlight context to the handleMessages()
1717 handleMessage(sw, msg, bc);
1718 } catch (IOException e) {
1719 log.error("Error reinjecting OFMessage on switch {}",
1720 HexString.toHexString(sw.getId()));
1721 return false;
1722 }
1723 return true;
1724 }
1725
1726 @Override
1727 @LogMessageDoc(message="Calling System.exit",
1728 explanation="The controller is terminating")
1729 public synchronized void terminate() {
1730 log.info("Calling System.exit");
1731 System.exit(1);
1732 }
1733
1734 @Override
1735 public boolean injectOfMessage(IOFSwitch sw, OFMessage msg) {
1736 // call the overloaded version with floodlight context set to null
1737 return injectOfMessage(sw, msg, null);
1738 }
1739
1740 @Override
1741 public void handleOutgoingMessage(IOFSwitch sw, OFMessage m,
1742 FloodlightContext bc) {
1743 if (log.isTraceEnabled()) {
1744 String str = OFMessage.getDataAsString(sw, m, bc);
1745 log.trace("{}", str);
1746 }
1747
1748 List<IOFMessageListener> listeners = null;
1749 if (messageListeners.containsKey(m.getType())) {
1750 listeners =
1751 messageListeners.get(m.getType()).getOrderedListeners();
1752 }
1753
1754 if (listeners != null) {
1755 for (IOFMessageListener listener : listeners) {
1756 if (listener instanceof IOFSwitchFilter) {
1757 if (!((IOFSwitchFilter)listener).isInterested(sw)) {
1758 continue;
1759 }
1760 }
1761 if (Command.STOP.equals(listener.receive(sw, m, bc))) {
1762 break;
1763 }
1764 }
1765 }
1766 }
1767
1768 @Override
1769 public BasicFactory getOFMessageFactory() {
1770 return factory;
1771 }
1772
1773 @Override
1774 public String getControllerId() {
1775 return controllerId;
1776 }
1777
1778 // **************
1779 // Initialization
1780 // **************
1781
1782 protected void updateAllInactiveSwitchInfo() {
1783 if (role == Role.SLAVE) {
1784 return;
1785 }
1786 String controllerId = getControllerId();
1787 String[] switchColumns = { SWITCH_DATAPATH_ID,
1788 SWITCH_CONTROLLER_ID,
1789 SWITCH_ACTIVE };
1790 String[] portColumns = { PORT_ID, PORT_SWITCH };
1791 IResultSet switchResultSet = null;
1792 try {
1793 OperatorPredicate op =
1794 new OperatorPredicate(SWITCH_CONTROLLER_ID,
1795 OperatorPredicate.Operator.EQ,
1796 controllerId);
1797 switchResultSet =
1798 storageSource.executeQuery(SWITCH_TABLE_NAME,
1799 switchColumns,
1800 op, null);
1801 while (switchResultSet.next()) {
1802 IResultSet portResultSet = null;
1803 try {
1804 String datapathId =
1805 switchResultSet.getString(SWITCH_DATAPATH_ID);
1806 switchResultSet.setBoolean(SWITCH_ACTIVE, Boolean.FALSE);
1807 op = new OperatorPredicate(PORT_SWITCH,
1808 OperatorPredicate.Operator.EQ,
1809 datapathId);
1810 portResultSet =
1811 storageSource.executeQuery(PORT_TABLE_NAME,
1812 portColumns,
1813 op, null);
1814 while (portResultSet.next()) {
1815 portResultSet.deleteRow();
1816 }
1817 portResultSet.save();
1818 }
1819 finally {
1820 if (portResultSet != null)
1821 portResultSet.close();
1822 }
1823 }
1824 switchResultSet.save();
1825 }
1826 finally {
1827 if (switchResultSet != null)
1828 switchResultSet.close();
1829 }
1830 }
1831
1832 protected void updateControllerInfo() {
1833 updateAllInactiveSwitchInfo();
1834
1835 // Write out the controller info to the storage source
1836 Map<String, Object> controllerInfo = new HashMap<String, Object>();
1837 String id = getControllerId();
1838 controllerInfo.put(CONTROLLER_ID, id);
1839 storageSource.updateRow(CONTROLLER_TABLE_NAME, controllerInfo);
1840 }
1841
1842 protected void updateActiveSwitchInfo(IOFSwitch sw) {
1843 if (role == Role.SLAVE) {
1844 return;
1845 }
1846 // Obtain the row info for the switch
1847 Map<String, Object> switchInfo = new HashMap<String, Object>();
1848 String datapathIdString = sw.getStringId();
1849 switchInfo.put(SWITCH_DATAPATH_ID, datapathIdString);
1850 String controllerId = getControllerId();
1851 switchInfo.put(SWITCH_CONTROLLER_ID, controllerId);
1852 Date connectedSince = sw.getConnectedSince();
1853 switchInfo.put(SWITCH_CONNECTED_SINCE, connectedSince);
1854 Channel channel = sw.getChannel();
1855 SocketAddress socketAddress = channel.getRemoteAddress();
1856 if (socketAddress != null) {
1857 String socketAddressString = socketAddress.toString();
1858 switchInfo.put(SWITCH_SOCKET_ADDRESS, socketAddressString);
1859 if (socketAddress instanceof InetSocketAddress) {
1860 InetSocketAddress inetSocketAddress =
1861 (InetSocketAddress)socketAddress;
1862 InetAddress inetAddress = inetSocketAddress.getAddress();
1863 String ip = inetAddress.getHostAddress();
1864 switchInfo.put(SWITCH_IP, ip);
1865 }
1866 }
1867
1868 // Write out the switch features info
1869 long capabilities = U32.f(sw.getCapabilities());
1870 switchInfo.put(SWITCH_CAPABILITIES, capabilities);
1871 long buffers = U32.f(sw.getBuffers());
1872 switchInfo.put(SWITCH_BUFFERS, buffers);
1873 long tables = U32.f(sw.getTables());
1874 switchInfo.put(SWITCH_TABLES, tables);
1875 long actions = U32.f(sw.getActions());
1876 switchInfo.put(SWITCH_ACTIONS, actions);
1877 switchInfo.put(SWITCH_ACTIVE, Boolean.TRUE);
1878
1879 // Update the switch
1880 storageSource.updateRowAsync(SWITCH_TABLE_NAME, switchInfo);
1881
1882 // Update the ports
1883 for (OFPhysicalPort port: sw.getPorts()) {
1884 updatePortInfo(sw, port);
1885 }
1886 }
1887
1888 protected void updateInactiveSwitchInfo(IOFSwitch sw) {
1889 if (role == Role.SLAVE) {
1890 return;
1891 }
1892 log.debug("Update DB with inactiveSW {}", sw);
1893 // Update the controller info in the storage source to be inactive
1894 Map<String, Object> switchInfo = new HashMap<String, Object>();
1895 String datapathIdString = sw.getStringId();
1896 switchInfo.put(SWITCH_DATAPATH_ID, datapathIdString);
1897 //switchInfo.put(SWITCH_CONNECTED_SINCE, null);
1898 switchInfo.put(SWITCH_ACTIVE, Boolean.FALSE);
1899 storageSource.updateRowAsync(SWITCH_TABLE_NAME, switchInfo);
1900 }
1901
1902 protected void updatePortInfo(IOFSwitch sw, OFPhysicalPort port) {
1903 if (role == Role.SLAVE) {
1904 return;
1905 }
1906 String datapathIdString = sw.getStringId();
1907 Map<String, Object> portInfo = new HashMap<String, Object>();
1908 int portNumber = U16.f(port.getPortNumber());
1909 String id = datapathIdString + "|" + portNumber;
1910 portInfo.put(PORT_ID, id);
1911 portInfo.put(PORT_SWITCH, datapathIdString);
1912 portInfo.put(PORT_NUMBER, portNumber);
1913 byte[] hardwareAddress = port.getHardwareAddress();
1914 String hardwareAddressString = HexString.toHexString(hardwareAddress);
1915 portInfo.put(PORT_HARDWARE_ADDRESS, hardwareAddressString);
1916 String name = port.getName();
1917 portInfo.put(PORT_NAME, name);
1918 long config = U32.f(port.getConfig());
1919 portInfo.put(PORT_CONFIG, config);
1920 long state = U32.f(port.getState());
1921 portInfo.put(PORT_STATE, state);
1922 long currentFeatures = U32.f(port.getCurrentFeatures());
1923 portInfo.put(PORT_CURRENT_FEATURES, currentFeatures);
1924 long advertisedFeatures = U32.f(port.getAdvertisedFeatures());
1925 portInfo.put(PORT_ADVERTISED_FEATURES, advertisedFeatures);
1926 long supportedFeatures = U32.f(port.getSupportedFeatures());
1927 portInfo.put(PORT_SUPPORTED_FEATURES, supportedFeatures);
1928 long peerFeatures = U32.f(port.getPeerFeatures());
1929 portInfo.put(PORT_PEER_FEATURES, peerFeatures);
1930 storageSource.updateRowAsync(PORT_TABLE_NAME, portInfo);
1931 }
1932
1933 /**
1934 * Read switch port data from storage and write it into a switch object
1935 * @param sw the switch to update
1936 */
1937 protected void readSwitchPortStateFromStorage(OFSwitchImpl sw) {
1938 OperatorPredicate op =
1939 new OperatorPredicate(PORT_SWITCH,
1940 OperatorPredicate.Operator.EQ,
1941 sw.getStringId());
1942 IResultSet portResultSet =
1943 storageSource.executeQuery(PORT_TABLE_NAME,
1944 null, op, null);
1945 //Map<Short, OFPhysicalPort> oldports =
1946 // new HashMap<Short, OFPhysicalPort>();
1947 //oldports.putAll(sw.getPorts());
1948
1949 while (portResultSet.next()) {
1950 try {
1951 OFPhysicalPort p = new OFPhysicalPort();
1952 p.setPortNumber((short)portResultSet.getInt(PORT_NUMBER));
1953 p.setName(portResultSet.getString(PORT_NAME));
1954 p.setConfig((int)portResultSet.getLong(PORT_CONFIG));
1955 p.setState((int)portResultSet.getLong(PORT_STATE));
1956 String portMac = portResultSet.getString(PORT_HARDWARE_ADDRESS);
1957 p.setHardwareAddress(HexString.fromHexString(portMac));
1958 p.setCurrentFeatures((int)portResultSet.
1959 getLong(PORT_CURRENT_FEATURES));
1960 p.setAdvertisedFeatures((int)portResultSet.
1961 getLong(PORT_ADVERTISED_FEATURES));
1962 p.setSupportedFeatures((int)portResultSet.
1963 getLong(PORT_SUPPORTED_FEATURES));
1964 p.setPeerFeatures((int)portResultSet.
1965 getLong(PORT_PEER_FEATURES));
1966 //oldports.remove(Short.valueOf(p.getPortNumber()));
1967 sw.setPort(p);
1968 } catch (NullPointerException e) {
1969 // ignore
1970 }
1971 }
1972 SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.PORTCHANGED);
1973 try {
1974 this.updates.put(update);
1975 } catch (InterruptedException e) {
1976 log.error("Failure adding update to queue", e);
1977 }
1978 }
1979
1980 protected void removePortInfo(IOFSwitch sw, short portNumber) {
1981 if (role == Role.SLAVE) {
1982 return;
1983 }
1984 String datapathIdString = sw.getStringId();
1985 String id = datapathIdString + "|" + portNumber;
1986 storageSource.deleteRowAsync(PORT_TABLE_NAME, id);
1987 }
1988
1989 /**
1990 * Sets the initial role based on properties in the config params.
1991 * It looks for two different properties.
1992 * If the "role" property is specified then the value should be
1993 * either "EQUAL", "MASTER", or "SLAVE" and the role of the
1994 * controller is set to the specified value. If the "role" property
1995 * is not specified then it looks next for the "role.path" property.
1996 * In this case the value should be the path to a property file in
1997 * the file system that contains a property called "floodlight.role"
1998 * which can be one of the values listed above for the "role" property.
1999 * The idea behind the "role.path" mechanism is that you have some
2000 * separate heartbeat and master controller election algorithm that
2001 * determines the role of the controller. When a role transition happens,
2002 * it updates the current role in the file specified by the "role.path"
2003 * file. Then if floodlight restarts for some reason it can get the
2004 * correct current role of the controller from the file.
2005 * @param configParams The config params for the FloodlightProvider service
2006 * @return A valid role if role information is specified in the
2007 * config params, otherwise null
2008 */
2009 @LogMessageDocs({
2010 @LogMessageDoc(message="Controller role set to {role}",
2011 explanation="Setting the initial HA role to "),
2012 @LogMessageDoc(level="ERROR",
2013 message="Invalid current role value: {role}",
2014 explanation="An invalid HA role value was read from the " +
2015 "properties file",
2016 recommendation=LogMessageDoc.CHECK_CONTROLLER)
2017 })
2018 protected Role getInitialRole(Map<String, String> configParams) {
2019 Role role = null;
2020 String roleString = configParams.get("role");
2021 if (roleString == null) {
2022 String rolePath = configParams.get("rolepath");
2023 if (rolePath != null) {
2024 Properties properties = new Properties();
2025 try {
2026 properties.load(new FileInputStream(rolePath));
2027 roleString = properties.getProperty("floodlight.role");
2028 }
2029 catch (IOException exc) {
2030 // Don't treat it as an error if the file specified by the
2031 // rolepath property doesn't exist. This lets us enable the
2032 // HA mechanism by just creating/setting the floodlight.role
2033 // property in that file without having to modify the
2034 // floodlight properties.
2035 }
2036 }
2037 }
2038
2039 if (roleString != null) {
2040 // Canonicalize the string to the form used for the enum constants
2041 roleString = roleString.trim().toUpperCase();
2042 try {
2043 role = Role.valueOf(roleString);
2044 }
2045 catch (IllegalArgumentException exc) {
2046 log.error("Invalid current role value: {}", roleString);
2047 }
2048 }
2049
2050 log.info("Controller role set to {}", role);
2051
2052 return role;
2053 }
2054
2055 /**
2056 * Tell controller that we're ready to accept switches loop
2057 * @throws IOException
2058 */
2059 @LogMessageDocs({
2060 @LogMessageDoc(message="Listening for switch connections on {address}",
2061 explanation="The controller is ready and listening for new" +
2062 " switch connections"),
2063 @LogMessageDoc(message="Storage exception in controller " +
2064 "updates loop; terminating process",
2065 explanation=ERROR_DATABASE,
2066 recommendation=LogMessageDoc.CHECK_CONTROLLER),
2067 @LogMessageDoc(level="ERROR",
2068 message="Exception in controller updates loop",
2069 explanation="Failed to dispatch controller event",
2070 recommendation=LogMessageDoc.GENERIC_ACTION)
2071 })
2072 public void run() {
2073 if (log.isDebugEnabled()) {
2074 logListeners();
2075 }
2076
2077 try {
2078 final ServerBootstrap bootstrap = createServerBootStrap();
2079
2080 bootstrap.setOption("reuseAddr", true);
2081 bootstrap.setOption("child.keepAlive", true);
2082 bootstrap.setOption("child.tcpNoDelay", true);
2083 bootstrap.setOption("child.sendBufferSize", Controller.SEND_BUFFER_SIZE);
2084
2085 ChannelPipelineFactory pfact =
2086 new OpenflowPipelineFactory(this, null);
2087 bootstrap.setPipelineFactory(pfact);
2088 InetSocketAddress sa = new InetSocketAddress(openFlowPort);
2089 final ChannelGroup cg = new DefaultChannelGroup();
2090 cg.add(bootstrap.bind(sa));
2091
2092 log.info("Listening for switch connections on {}", sa);
2093 } catch (Exception e) {
2094 throw new RuntimeException(e);
2095 }
2096
2097 // main loop
2098 while (true) {
2099 try {
2100 IUpdate update = updates.take();
2101 update.dispatch();
2102 } catch (InterruptedException e) {
2103 return;
2104 } catch (StorageException e) {
2105 log.error("Storage exception in controller " +
2106 "updates loop; terminating process", e);
2107 return;
2108 } catch (Exception e) {
2109 log.error("Exception in controller updates loop", e);
2110 }
2111 }
2112 }
2113
2114 private ServerBootstrap createServerBootStrap() {
2115 if (workerThreads == 0) {
2116 return new ServerBootstrap(
2117 new NioServerSocketChannelFactory(
2118 Executors.newCachedThreadPool(),
2119 Executors.newCachedThreadPool()));
2120 } else {
2121 return new ServerBootstrap(
2122 new NioServerSocketChannelFactory(
2123 Executors.newCachedThreadPool(),
2124 Executors.newCachedThreadPool(), workerThreads));
2125 }
2126 }
2127
2128 public void setConfigParams(Map<String, String> configParams) {
2129 String ofPort = configParams.get("openflowport");
2130 if (ofPort != null) {
2131 this.openFlowPort = Integer.parseInt(ofPort);
2132 }
2133 log.debug("OpenFlow port set to {}", this.openFlowPort);
2134 String threads = configParams.get("workerthreads");
2135 if (threads != null) {
2136 this.workerThreads = Integer.parseInt(threads);
2137 }
2138 log.debug("Number of worker threads set to {}", this.workerThreads);
2139 String controllerId = configParams.get("controllerid");
2140 if (controllerId != null) {
2141 this.controllerId = controllerId;
2142 }
Jonathan Hartd10008d2013-02-23 17:04:08 -08002143 else {
2144 //Try to get the hostname of the machine and use that for controller ID
2145 try {
2146 String hostname = java.net.InetAddress.getLocalHost().getHostName();
2147 this.controllerId = hostname;
2148 } catch (UnknownHostException e) {
2149 // Can't get hostname, we'll just use the default
2150 }
2151 }
2152
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08002153 log.debug("ControllerId set to {}", this.controllerId);
2154 }
2155
2156 private void initVendorMessages() {
2157 // Configure openflowj to be able to parse the role request/reply
2158 // vendor messages.
2159 OFBasicVendorId niciraVendorId = new OFBasicVendorId(
2160 OFNiciraVendorData.NX_VENDOR_ID, 4);
2161 OFVendorId.registerVendorId(niciraVendorId);
2162 OFBasicVendorDataType roleRequestVendorData =
2163 new OFBasicVendorDataType(
2164 OFRoleRequestVendorData.NXT_ROLE_REQUEST,
2165 OFRoleRequestVendorData.getInstantiable());
2166 niciraVendorId.registerVendorDataType(roleRequestVendorData);
2167 OFBasicVendorDataType roleReplyVendorData =
2168 new OFBasicVendorDataType(
2169 OFRoleReplyVendorData.NXT_ROLE_REPLY,
2170 OFRoleReplyVendorData.getInstantiable());
2171 niciraVendorId.registerVendorDataType(roleReplyVendorData);
2172 }
2173
2174 /**
2175 * Initialize internal data structures
2176 */
2177 public void init(Map<String, String> configParams) {
2178 // These data structures are initialized here because other
2179 // module's startUp() might be called before ours
2180 this.messageListeners =
2181 new ConcurrentHashMap<OFType,
2182 ListenerDispatcher<OFType,
2183 IOFMessageListener>>();
2184 this.switchListeners = new CopyOnWriteArraySet<IOFSwitchListener>();
2185 this.haListeners = new CopyOnWriteArraySet<IHAListener>();
2186 this.activeSwitches = new ConcurrentHashMap<Long, IOFSwitch>();
2187 this.connectedSwitches = new HashSet<OFSwitchImpl>();
2188 this.controllerNodeIPsCache = new HashMap<String, String>();
2189 this.updates = new LinkedBlockingQueue<IUpdate>();
2190 this.factory = new BasicFactory();
2191 this.providerMap = new HashMap<String, List<IInfoProvider>>();
2192 setConfigParams(configParams);
Jonathan Hartcc957a02013-02-26 10:39:04 -08002193 //this.role = getInitialRole(configParams);
2194 //Set the controller's role to MASTER so it always tries to do role requests.
2195 this.role = Role.MASTER;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08002196 this.roleChanger = new RoleChanger();
2197 initVendorMessages();
2198 this.systemStartTime = System.currentTimeMillis();
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08002199 }
2200
2201 /**
2202 * Startup all of the controller's components
2203 */
2204 @LogMessageDoc(message="Waiting for storage source",
2205 explanation="The system database is not yet ready",
2206 recommendation="If this message persists, this indicates " +
2207 "that the system database has failed to start. " +
2208 LogMessageDoc.CHECK_CONTROLLER)
2209 public void startupComponents() {
Jonathan Hartd10008d2013-02-23 17:04:08 -08002210 try {
2211 registryService.registerController(controllerId);
2212 } catch (RegistryException e2) {
2213 log.warn("Registry service error: {}", e2.getMessage());
2214 }
2215
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08002216 // Create the table names we use
2217 storageSource.createTable(CONTROLLER_TABLE_NAME, null);
2218 storageSource.createTable(SWITCH_TABLE_NAME, null);
2219 storageSource.createTable(PORT_TABLE_NAME, null);
2220 storageSource.createTable(CONTROLLER_INTERFACE_TABLE_NAME, null);
2221 storageSource.createTable(SWITCH_CONFIG_TABLE_NAME, null);
2222 storageSource.setTablePrimaryKeyName(CONTROLLER_TABLE_NAME,
2223 CONTROLLER_ID);
2224 storageSource.setTablePrimaryKeyName(SWITCH_TABLE_NAME,
2225 SWITCH_DATAPATH_ID);
2226 storageSource.setTablePrimaryKeyName(PORT_TABLE_NAME, PORT_ID);
2227 storageSource.setTablePrimaryKeyName(CONTROLLER_INTERFACE_TABLE_NAME,
2228 CONTROLLER_INTERFACE_ID);
2229 storageSource.addListener(CONTROLLER_INTERFACE_TABLE_NAME, this);
2230
2231 while (true) {
2232 try {
2233 updateControllerInfo();
2234 break;
2235 }
2236 catch (StorageException e) {
2237 log.info("Waiting for storage source");
2238 try {
2239 Thread.sleep(1000);
2240 } catch (InterruptedException e1) {
2241 }
2242 }
2243 }
2244
2245 // Add our REST API
2246 restApi.addRestletRoutable(new CoreWebRoutable());
2247 }
2248
2249 @Override
2250 public void addInfoProvider(String type, IInfoProvider provider) {
2251 if (!providerMap.containsKey(type)) {
2252 providerMap.put(type, new ArrayList<IInfoProvider>());
2253 }
2254 providerMap.get(type).add(provider);
2255 }
2256
2257 @Override
2258 public void removeInfoProvider(String type, IInfoProvider provider) {
2259 if (!providerMap.containsKey(type)) {
2260 log.debug("Provider type {} doesn't exist.", type);
2261 return;
2262 }
2263
2264 providerMap.get(type).remove(provider);
2265 }
2266
2267 public Map<String, Object> getControllerInfo(String type) {
2268 if (!providerMap.containsKey(type)) return null;
2269
2270 Map<String, Object> result = new LinkedHashMap<String, Object>();
2271 for (IInfoProvider provider : providerMap.get(type)) {
2272 result.putAll(provider.getInfo(type));
2273 }
2274
2275 return result;
2276 }
2277
2278 @Override
2279 public void addHAListener(IHAListener listener) {
2280 this.haListeners.add(listener);
2281 }
2282
2283 @Override
2284 public void removeHAListener(IHAListener listener) {
2285 this.haListeners.remove(listener);
2286 }
2287
2288
2289 /**
2290 * Handle changes to the controller nodes IPs and dispatch update.
2291 */
2292 @SuppressWarnings("unchecked")
2293 protected void handleControllerNodeIPChanges() {
2294 HashMap<String,String> curControllerNodeIPs = new HashMap<String,String>();
2295 HashMap<String,String> addedControllerNodeIPs = new HashMap<String,String>();
2296 HashMap<String,String> removedControllerNodeIPs =new HashMap<String,String>();
2297 String[] colNames = { CONTROLLER_INTERFACE_CONTROLLER_ID,
2298 CONTROLLER_INTERFACE_TYPE,
2299 CONTROLLER_INTERFACE_NUMBER,
2300 CONTROLLER_INTERFACE_DISCOVERED_IP };
2301 synchronized(controllerNodeIPsCache) {
2302 // We currently assume that interface Ethernet0 is the relevant
2303 // controller interface. Might change.
2304 // We could (should?) implement this using
2305 // predicates, but creating the individual and compound predicate
2306 // seems more overhead then just checking every row. Particularly,
2307 // since the number of rows is small and changes infrequent
2308 IResultSet res = storageSource.executeQuery(CONTROLLER_INTERFACE_TABLE_NAME,
2309 colNames,null, null);
2310 while (res.next()) {
2311 if (res.getString(CONTROLLER_INTERFACE_TYPE).equals("Ethernet") &&
2312 res.getInt(CONTROLLER_INTERFACE_NUMBER) == 0) {
2313 String controllerID = res.getString(CONTROLLER_INTERFACE_CONTROLLER_ID);
2314 String discoveredIP = res.getString(CONTROLLER_INTERFACE_DISCOVERED_IP);
2315 String curIP = controllerNodeIPsCache.get(controllerID);
2316
2317 curControllerNodeIPs.put(controllerID, discoveredIP);
2318 if (curIP == null) {
2319 // new controller node IP
2320 addedControllerNodeIPs.put(controllerID, discoveredIP);
2321 }
2322 else if (curIP != discoveredIP) {
2323 // IP changed
2324 removedControllerNodeIPs.put(controllerID, curIP);
2325 addedControllerNodeIPs.put(controllerID, discoveredIP);
2326 }
2327 }
2328 }
2329 // Now figure out if rows have been deleted. We can't use the
2330 // rowKeys from rowsDeleted directly, since the tables primary
2331 // key is a compound that we can't disassemble
2332 Set<String> curEntries = curControllerNodeIPs.keySet();
2333 Set<String> removedEntries = controllerNodeIPsCache.keySet();
2334 removedEntries.removeAll(curEntries);
2335 for (String removedControllerID : removedEntries)
2336 removedControllerNodeIPs.put(removedControllerID, controllerNodeIPsCache.get(removedControllerID));
2337 controllerNodeIPsCache = (HashMap<String, String>) curControllerNodeIPs.clone();
2338 HAControllerNodeIPUpdate update = new HAControllerNodeIPUpdate(
2339 curControllerNodeIPs, addedControllerNodeIPs,
2340 removedControllerNodeIPs);
2341 if (!removedControllerNodeIPs.isEmpty() || !addedControllerNodeIPs.isEmpty()) {
2342 try {
2343 this.updates.put(update);
2344 } catch (InterruptedException e) {
2345 log.error("Failure adding update to queue", e);
2346 }
2347 }
2348 }
2349 }
2350
2351 @Override
2352 public Map<String, String> getControllerNodeIPs() {
2353 // We return a copy of the mapping so we can guarantee that
2354 // the mapping return is the same as one that will be (or was)
2355 // dispatched to IHAListeners
2356 HashMap<String,String> retval = new HashMap<String,String>();
2357 synchronized(controllerNodeIPsCache) {
2358 retval.putAll(controllerNodeIPsCache);
2359 }
2360 return retval;
2361 }
2362
2363 @Override
2364 public void rowsModified(String tableName, Set<Object> rowKeys) {
2365 if (tableName.equals(CONTROLLER_INTERFACE_TABLE_NAME)) {
2366 handleControllerNodeIPChanges();
2367 }
2368
2369 }
2370
2371 @Override
2372 public void rowsDeleted(String tableName, Set<Object> rowKeys) {
2373 if (tableName.equals(CONTROLLER_INTERFACE_TABLE_NAME)) {
2374 handleControllerNodeIPChanges();
2375 }
2376 }
2377
2378 @Override
2379 public long getSystemStartTime() {
2380 return (this.systemStartTime);
2381 }
2382
2383 @Override
2384 public void setAlwaysClearFlowsOnSwAdd(boolean value) {
2385 this.alwaysClearFlowsOnSwAdd = value;
2386 }
2387
2388 public boolean getAlwaysClearFlowsOnSwAdd() {
2389 return this.alwaysClearFlowsOnSwAdd;
2390 }
2391}