blob: d4a44fcbb45b5a7b57ed9dd8757b3df6563cc6b3 [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
Pankaj Berde01939e92013-03-08 14:38:27 -0800492 /*
493 * issue #229
494 * Cannot rely on sw.getRole() as it can be behind due to pending
495 * role changes in the queue. Just submit it and late the RoleChanger
496 * handle duplicates.
497 */
498
499 if (hasControl){
Jonathan Hartcc957a02013-02-26 10:39:04 -0800500 role = Role.MASTER;
501 }
Pankaj Berde01939e92013-03-08 14:38:27 -0800502 else {
Jonathan Hartcc957a02013-02-26 10:39:04 -0800503 role = Role.SLAVE;
504 }
Pankaj Berde01939e92013-03-08 14:38:27 -0800505
506 log.debug("Sending role request {} msg to {}", role, sw);
507 Collection<OFSwitchImpl> swList = new ArrayList<OFSwitchImpl>(1);
508 swList.add(sw);
509 roleChanger.submitRequest(swList, role);
510
Jonathan Hartcc957a02013-02-26 10:39:04 -0800511 }
512
513 }
514 }
515
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800516 /**
517 * Channel handler deals with the switch connection and dispatches
518 * switch messages to the appropriate locations.
519 * @author readams
520 */
521 protected class OFChannelHandler
522 extends IdleStateAwareChannelUpstreamHandler {
523 protected OFSwitchImpl sw;
524 protected OFChannelState state;
525
526 public OFChannelHandler(OFChannelState state) {
527 this.state = state;
528 }
529
530 @Override
531 @LogMessageDoc(message="New switch connection from {ip address}",
532 explanation="A new switch has connected from the " +
533 "specified IP address")
534 public void channelConnected(ChannelHandlerContext ctx,
535 ChannelStateEvent e) throws Exception {
536 log.info("New switch connection from {}",
537 e.getChannel().getRemoteAddress());
538
539 sw = new OFSwitchImpl();
540 sw.setChannel(e.getChannel());
541 sw.setFloodlightProvider(Controller.this);
542 sw.setThreadPoolService(threadPool);
543
544 List<OFMessage> msglist = new ArrayList<OFMessage>(1);
545 msglist.add(factory.getMessage(OFType.HELLO));
546 e.getChannel().write(msglist);
547
548 }
549
550 @Override
551 @LogMessageDoc(message="Disconnected switch {switch information}",
552 explanation="The specified switch has disconnected.")
553 public void channelDisconnected(ChannelHandlerContext ctx,
554 ChannelStateEvent e) throws Exception {
555 if (sw != null && state.hsState == HandshakeState.READY) {
556 if (activeSwitches.containsKey(sw.getId())) {
557 // It's safe to call removeSwitch even though the map might
558 // not contain this particular switch but another with the
559 // same DPID
560 removeSwitch(sw);
561 }
562 synchronized(roleChanger) {
Jonathan Hartcc957a02013-02-26 10:39:04 -0800563 registryService.releaseControl(sw.getId());
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800564 connectedSwitches.remove(sw);
565 }
566 sw.setConnected(false);
567 }
568 log.info("Disconnected switch {}", sw);
569 }
570
571 @Override
572 @LogMessageDocs({
573 @LogMessageDoc(level="ERROR",
574 message="Disconnecting switch {switch} due to read timeout",
575 explanation="The connected switch has failed to send any " +
576 "messages or respond to echo requests",
577 recommendation=LogMessageDoc.CHECK_SWITCH),
578 @LogMessageDoc(level="ERROR",
579 message="Disconnecting switch {switch}: failed to " +
580 "complete handshake",
581 explanation="The switch did not respond correctly " +
582 "to handshake messages",
583 recommendation=LogMessageDoc.CHECK_SWITCH),
584 @LogMessageDoc(level="ERROR",
585 message="Disconnecting switch {switch} due to IO Error: {}",
586 explanation="There was an error communicating with the switch",
587 recommendation=LogMessageDoc.CHECK_SWITCH),
588 @LogMessageDoc(level="ERROR",
589 message="Disconnecting switch {switch} due to switch " +
590 "state error: {error}",
591 explanation="The switch sent an unexpected message",
592 recommendation=LogMessageDoc.CHECK_SWITCH),
593 @LogMessageDoc(level="ERROR",
594 message="Disconnecting switch {switch} due to " +
595 "message parse failure",
596 explanation="Could not parse a message from the switch",
597 recommendation=LogMessageDoc.CHECK_SWITCH),
598 @LogMessageDoc(level="ERROR",
599 message="Terminating controller due to storage exception",
600 explanation=ERROR_DATABASE,
601 recommendation=LogMessageDoc.CHECK_CONTROLLER),
602 @LogMessageDoc(level="ERROR",
603 message="Could not process message: queue full",
604 explanation="OpenFlow messages are arriving faster than " +
605 " the controller can process them.",
606 recommendation=LogMessageDoc.CHECK_CONTROLLER),
607 @LogMessageDoc(level="ERROR",
608 message="Error while processing message " +
609 "from switch {switch} {cause}",
610 explanation="An error occurred processing the switch message",
611 recommendation=LogMessageDoc.GENERIC_ACTION)
612 })
613 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
614 throws Exception {
615 if (e.getCause() instanceof ReadTimeoutException) {
616 // switch timeout
617 log.error("Disconnecting switch {} due to read timeout", sw);
618 ctx.getChannel().close();
619 } else if (e.getCause() instanceof HandshakeTimeoutException) {
620 log.error("Disconnecting switch {}: failed to complete handshake",
621 sw);
622 ctx.getChannel().close();
623 } else if (e.getCause() instanceof ClosedChannelException) {
624 //log.warn("Channel for sw {} already closed", sw);
625 } else if (e.getCause() instanceof IOException) {
626 log.error("Disconnecting switch {} due to IO Error: {}",
627 sw, e.getCause().getMessage());
628 ctx.getChannel().close();
629 } else if (e.getCause() instanceof SwitchStateException) {
630 log.error("Disconnecting switch {} due to switch state error: {}",
631 sw, e.getCause().getMessage());
632 ctx.getChannel().close();
633 } else if (e.getCause() instanceof MessageParseException) {
634 log.error("Disconnecting switch " + sw +
635 " due to message parse failure",
636 e.getCause());
637 ctx.getChannel().close();
638 } else if (e.getCause() instanceof StorageException) {
639 log.error("Terminating controller due to storage exception",
640 e.getCause());
641 terminate();
642 } else if (e.getCause() instanceof RejectedExecutionException) {
643 log.warn("Could not process message: queue full");
644 } else {
645 log.error("Error while processing message from switch " + sw,
646 e.getCause());
647 ctx.getChannel().close();
648 }
649 }
650
651 @Override
652 public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e)
653 throws Exception {
654 List<OFMessage> msglist = new ArrayList<OFMessage>(1);
655 msglist.add(factory.getMessage(OFType.ECHO_REQUEST));
656 e.getChannel().write(msglist);
657 }
658
659 @Override
660 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
661 throws Exception {
662 if (e.getMessage() instanceof List) {
663 @SuppressWarnings("unchecked")
664 List<OFMessage> msglist = (List<OFMessage>)e.getMessage();
665
666 for (OFMessage ofm : msglist) {
667 try {
668 processOFMessage(ofm);
669 }
670 catch (Exception ex) {
671 // We are the last handler in the stream, so run the
672 // exception through the channel again by passing in
673 // ctx.getChannel().
674 Channels.fireExceptionCaught(ctx.getChannel(), ex);
675 }
676 }
677
678 // Flush all flow-mods/packet-out generated from this "train"
679 OFSwitchImpl.flush_all();
680 }
681 }
682
683 /**
684 * Process the request for the switch description
685 */
686 @LogMessageDoc(level="ERROR",
687 message="Exception in reading description " +
688 " during handshake {exception}",
689 explanation="Could not process the switch description string",
690 recommendation=LogMessageDoc.CHECK_SWITCH)
691 void processSwitchDescReply() {
692 try {
693 // Read description, if it has been updated
694 @SuppressWarnings("unchecked")
695 Future<List<OFStatistics>> desc_future =
696 (Future<List<OFStatistics>>)sw.
697 getAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE);
698 List<OFStatistics> values =
699 desc_future.get(0, TimeUnit.MILLISECONDS);
700 if (values != null) {
701 OFDescriptionStatistics description =
702 new OFDescriptionStatistics();
703 ChannelBuffer data =
704 ChannelBuffers.buffer(description.getLength());
705 for (OFStatistics f : values) {
706 f.writeTo(data);
707 description.readFrom(data);
708 break; // SHOULD be a list of length 1
709 }
710 sw.setAttribute(IOFSwitch.SWITCH_DESCRIPTION_DATA,
711 description);
712 sw.setSwitchProperties(description);
713 data = null;
714
715 // At this time, also set other switch properties from storage
716 boolean is_core_switch = false;
717 IResultSet resultSet = null;
718 try {
719 String swid = sw.getStringId();
720 resultSet =
721 storageSource.getRow(SWITCH_CONFIG_TABLE_NAME, swid);
722 for (Iterator<IResultSet> it =
723 resultSet.iterator(); it.hasNext();) {
724 // In case of multiple rows, use the status
725 // in last row?
726 Map<String, Object> row = it.next().getRow();
727 if (row.containsKey(SWITCH_CONFIG_CORE_SWITCH)) {
728 if (log.isDebugEnabled()) {
729 log.debug("Reading SWITCH_IS_CORE_SWITCH " +
730 "config for switch={}, is-core={}",
731 sw, row.get(SWITCH_CONFIG_CORE_SWITCH));
732 }
733 String ics =
734 (String)row.get(SWITCH_CONFIG_CORE_SWITCH);
735 is_core_switch = ics.equals("true");
736 }
737 }
738 }
739 finally {
740 if (resultSet != null)
741 resultSet.close();
742 }
743 if (is_core_switch) {
744 sw.setAttribute(IOFSwitch.SWITCH_IS_CORE_SWITCH,
745 new Boolean(true));
746 }
747 }
748 sw.removeAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE);
749 state.hasDescription = true;
750 checkSwitchReady();
751 }
752 catch (InterruptedException ex) {
753 // Ignore
754 }
755 catch (TimeoutException ex) {
756 // Ignore
757 } catch (Exception ex) {
758 log.error("Exception in reading description " +
759 " during handshake", ex);
760 }
761 }
762
763 /**
764 * Send initial switch setup information that we need before adding
765 * the switch
766 * @throws IOException
767 */
768 void sendHelloConfiguration() throws IOException {
769 // Send initial Features Request
770 sw.write(factory.getMessage(OFType.FEATURES_REQUEST), null);
771 }
772
773 /**
774 * Send the configuration requests we can only do after we have
775 * the features reply
776 * @throws IOException
777 */
778 void sendFeatureReplyConfiguration() throws IOException {
779 // Ensure we receive the full packet via PacketIn
780 OFSetConfig config = (OFSetConfig) factory
781 .getMessage(OFType.SET_CONFIG);
782 config.setMissSendLength((short) 0xffff)
783 .setLengthU(OFSwitchConfig.MINIMUM_LENGTH);
784 sw.write(config, null);
785 sw.write(factory.getMessage(OFType.GET_CONFIG_REQUEST),
786 null);
787
788 // Get Description to set switch-specific flags
789 OFStatisticsRequest req = new OFStatisticsRequest();
790 req.setStatisticType(OFStatisticsType.DESC);
791 req.setLengthU(req.getLengthU());
792 Future<List<OFStatistics>> dfuture =
793 sw.getStatistics(req);
794 sw.setAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE,
795 dfuture);
796
797 }
798
799 protected void checkSwitchReady() {
800 if (state.hsState == HandshakeState.FEATURES_REPLY &&
801 state.hasDescription && state.hasGetConfigReply) {
802
803 state.hsState = HandshakeState.READY;
804
805 synchronized(roleChanger) {
806 // We need to keep track of all of the switches that are connected
807 // to the controller, in any role, so that we can later send the
808 // role request messages when the controller role changes.
809 // We need to be synchronized while doing this: we must not
810 // send a another role request to the connectedSwitches until
811 // we were able to add this new switch to connectedSwitches
812 // *and* send the current role to the new switch.
813 connectedSwitches.add(sw);
814
815 if (role != null) {
Jonathan Hart97801ac2013-02-26 14:29:16 -0800816 //Put the switch in SLAVE mode until we know we have control
817 log.debug("Setting new switch {} to SLAVE", sw.getStringId());
818 Collection<OFSwitchImpl> swList = new ArrayList<OFSwitchImpl>(1);
819 swList.add(sw);
820 roleChanger.submitRequest(swList, Role.SLAVE);
821
Jonathan Hartcc957a02013-02-26 10:39:04 -0800822 //Request control of the switch from the global registry
823 try {
824 registryService.requestControl(sw.getId(),
825 new RoleChangeCallback());
826 } catch (RegistryException e) {
827 log.debug("Registry error: {}", e.getMessage());
828 }
829
Jonathan Hart97801ac2013-02-26 14:29:16 -0800830
Jonathan Hartcc957a02013-02-26 10:39:04 -0800831
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800832 // Send a role request if role support is enabled for the controller
833 // This is a probe that we'll use to determine if the switch
834 // actually supports the role request message. If it does we'll
835 // get back a role reply message. If it doesn't we'll get back an
836 // OFError message.
837 // If role is MASTER we will promote switch to active
838 // list when we receive the switch's role reply messages
Jonathan Hartcc957a02013-02-26 10:39:04 -0800839 /*
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800840 log.debug("This controller's role is {}, " +
841 "sending initial role request msg to {}",
842 role, sw);
843 Collection<OFSwitchImpl> swList = new ArrayList<OFSwitchImpl>(1);
844 swList.add(sw);
845 roleChanger.submitRequest(swList, role);
Jonathan Hartcc957a02013-02-26 10:39:04 -0800846 */
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800847 }
848 else {
849 // Role supported not enabled on controller (for now)
850 // automatically promote switch to active state.
Umesh Krishnaswamyb56bb292013-02-12 20:28:27 -0800851 log.debug("This controller's role is {}, " +
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -0800852 "not sending role request msg to {}",
853 role, sw);
854 // Need to clear FlowMods before we add the switch
855 // and dispatch updates otherwise we have a race condition.
856 sw.clearAllFlowMods();
857 addSwitch(sw);
858 state.firstRoleReplyReceived = true;
859 }
860 }
861 }
862 }
863
864 /* Handle a role reply message we received from the switch. Since
865 * netty serializes message dispatch we don't need to synchronize
866 * against other receive operations from the same switch, so no need
867 * to synchronize addSwitch(), removeSwitch() operations from the same
868 * connection.
869 * FIXME: However, when a switch with the same DPID connects we do
870 * need some synchronization. However, handling switches with same
871 * DPID needs to be revisited anyways (get rid of r/w-lock and synchronous
872 * removedSwitch notification):1
873 *
874 */
875 @LogMessageDoc(level="ERROR",
876 message="Invalid role value in role reply message",
877 explanation="Was unable to set the HA role (master or slave) " +
878 "for the controller.",
879 recommendation=LogMessageDoc.CHECK_CONTROLLER)
880 protected void handleRoleReplyMessage(OFVendor vendorMessage,
881 OFRoleReplyVendorData roleReplyVendorData) {
882 // Map from the role code in the message to our role enum
883 int nxRole = roleReplyVendorData.getRole();
884 Role role = null;
885 switch (nxRole) {
886 case OFRoleVendorData.NX_ROLE_OTHER:
887 role = Role.EQUAL;
888 break;
889 case OFRoleVendorData.NX_ROLE_MASTER:
890 role = Role.MASTER;
891 break;
892 case OFRoleVendorData.NX_ROLE_SLAVE:
893 role = Role.SLAVE;
894 break;
895 default:
896 log.error("Invalid role value in role reply message");
897 sw.getChannel().close();
898 return;
899 }
900
901 log.debug("Handling role reply for role {} from {}. " +
902 "Controller's role is {} ",
903 new Object[] { role, sw, Controller.this.role}
904 );
905
906 sw.deliverRoleReply(vendorMessage.getXid(), role);
907
908 boolean isActive = activeSwitches.containsKey(sw.getId());
909 if (!isActive && sw.isActive()) {
910 // Transition from SLAVE to MASTER.
911
912 if (!state.firstRoleReplyReceived ||
913 getAlwaysClearFlowsOnSwAdd()) {
914 // This is the first role-reply message we receive from
915 // this switch or roles were disabled when the switch
916 // connected:
917 // Delete all pre-existing flows for new connections to
918 // the master
919 //
920 // FIXME: Need to think more about what the test should
921 // be for when we flush the flow-table? For example,
922 // if all the controllers are temporarily in the backup
923 // role (e.g. right after a failure of the master
924 // controller) at the point the switch connects, then
925 // all of the controllers will initially connect as
926 // backup controllers and not flush the flow-table.
927 // Then when one of them is promoted to master following
928 // the master controller election the flow-table
929 // will still not be flushed because that's treated as
930 // a failover event where we don't want to flush the
931 // flow-table. The end result would be that the flow
932 // table for a newly connected switch is never
933 // flushed. Not sure how to handle that case though...
934 sw.clearAllFlowMods();
935 log.debug("First role reply from master switch {}, " +
936 "clear FlowTable to active switch list",
937 HexString.toHexString(sw.getId()));
938 }
939
940 // Some switches don't seem to update us with port
941 // status messages while in slave role.
942 readSwitchPortStateFromStorage(sw);
943
944 // Only add the switch to the active switch list if
945 // we're not in the slave role. Note that if the role
946 // attribute is null, then that means that the switch
947 // doesn't support the role request messages, so in that
948 // case we're effectively in the EQUAL role and the
949 // switch should be included in the active switch list.
950 addSwitch(sw);
951 log.debug("Added master switch {} to active switch list",
952 HexString.toHexString(sw.getId()));
953
954 }
955 else if (isActive && !sw.isActive()) {
956 // Transition from MASTER to SLAVE: remove switch
957 // from active switch list.
958 log.debug("Removed slave switch {} from active switch" +
959 " list", HexString.toHexString(sw.getId()));
960 removeSwitch(sw);
961 }
962
963 // Indicate that we have received a role reply message.
964 state.firstRoleReplyReceived = true;
965 }
966
967 protected boolean handleVendorMessage(OFVendor vendorMessage) {
968 boolean shouldHandleMessage = false;
969 int vendor = vendorMessage.getVendor();
970 switch (vendor) {
971 case OFNiciraVendorData.NX_VENDOR_ID:
972 OFNiciraVendorData niciraVendorData =
973 (OFNiciraVendorData)vendorMessage.getVendorData();
974 int dataType = niciraVendorData.getDataType();
975 switch (dataType) {
976 case OFRoleReplyVendorData.NXT_ROLE_REPLY:
977 OFRoleReplyVendorData roleReplyVendorData =
978 (OFRoleReplyVendorData) niciraVendorData;
979 handleRoleReplyMessage(vendorMessage,
980 roleReplyVendorData);
981 break;
982 default:
983 log.warn("Unhandled Nicira VENDOR message; " +
984 "data type = {}", dataType);
985 break;
986 }
987 break;
988 default:
989 log.warn("Unhandled VENDOR message; vendor id = {}", vendor);
990 break;
991 }
992
993 return shouldHandleMessage;
994 }
995
996 /**
997 * Dispatch an Openflow message from a switch to the appropriate
998 * handler.
999 * @param m The message to process
1000 * @throws IOException
1001 * @throws SwitchStateException
1002 */
1003 @LogMessageDocs({
1004 @LogMessageDoc(level="WARN",
1005 message="Config Reply from {switch} has " +
1006 "miss length set to {length}",
1007 explanation="The controller requires that the switch " +
1008 "use a miss length of 0xffff for correct " +
1009 "function",
1010 recommendation="Use a different switch to ensure " +
1011 "correct function"),
1012 @LogMessageDoc(level="WARN",
1013 message="Received ERROR from sw {switch} that "
1014 +"indicates roles are not supported "
1015 +"but we have received a valid "
1016 +"role reply earlier",
1017 explanation="The switch sent a confusing message to the" +
1018 "controller")
1019 })
1020 protected void processOFMessage(OFMessage m)
1021 throws IOException, SwitchStateException {
1022 boolean shouldHandleMessage = false;
1023
1024 switch (m.getType()) {
1025 case HELLO:
1026 if (log.isTraceEnabled())
1027 log.trace("HELLO from {}", sw);
1028
1029 if (state.hsState.equals(HandshakeState.START)) {
1030 state.hsState = HandshakeState.HELLO;
1031 sendHelloConfiguration();
1032 } else {
1033 throw new SwitchStateException("Unexpected HELLO from "
1034 + sw);
1035 }
1036 break;
1037 case ECHO_REQUEST:
1038 OFEchoReply reply =
1039 (OFEchoReply) factory.getMessage(OFType.ECHO_REPLY);
1040 reply.setXid(m.getXid());
1041 sw.write(reply, null);
1042 break;
1043 case ECHO_REPLY:
1044 break;
1045 case FEATURES_REPLY:
1046 if (log.isTraceEnabled())
1047 log.trace("Features Reply from {}", sw);
1048
1049 sw.setFeaturesReply((OFFeaturesReply) m);
1050 if (state.hsState.equals(HandshakeState.HELLO)) {
1051 sendFeatureReplyConfiguration();
1052 state.hsState = HandshakeState.FEATURES_REPLY;
1053 // uncomment to enable "dumb" switches like cbench
1054 // state.hsState = HandshakeState.READY;
1055 // addSwitch(sw);
1056 } else {
1057 // return results to rest api caller
1058 sw.deliverOFFeaturesReply(m);
1059 // update database */
1060 updateActiveSwitchInfo(sw);
1061 }
1062 break;
1063 case GET_CONFIG_REPLY:
1064 if (log.isTraceEnabled())
1065 log.trace("Get config reply from {}", sw);
1066
1067 if (!state.hsState.equals(HandshakeState.FEATURES_REPLY)) {
1068 String em = "Unexpected GET_CONFIG_REPLY from " + sw;
1069 throw new SwitchStateException(em);
1070 }
1071 OFGetConfigReply cr = (OFGetConfigReply) m;
1072 if (cr.getMissSendLength() == (short)0xffff) {
1073 log.trace("Config Reply from {} confirms " +
1074 "miss length set to 0xffff", sw);
1075 } else {
1076 log.warn("Config Reply from {} has " +
1077 "miss length set to {}",
1078 sw, cr.getMissSendLength() & 0xffff);
1079 }
1080 state.hasGetConfigReply = true;
1081 checkSwitchReady();
1082 break;
1083 case VENDOR:
1084 shouldHandleMessage = handleVendorMessage((OFVendor)m);
1085 break;
1086 case ERROR:
1087 // TODO: we need better error handling. Especially for
1088 // request/reply style message (stats, roles) we should have
1089 // a unified way to lookup the xid in the error message.
1090 // This will probable involve rewriting the way we handle
1091 // request/reply style messages.
1092 OFError error = (OFError) m;
1093 boolean shouldLogError = true;
1094 // TODO: should we check that firstRoleReplyReceived is false,
1095 // i.e., check only whether the first request fails?
1096 if (sw.checkFirstPendingRoleRequestXid(error.getXid())) {
1097 boolean isBadVendorError =
1098 (error.getErrorType() == OFError.OFErrorType.
1099 OFPET_BAD_REQUEST.getValue());
1100 // We expect to receive a bad vendor error when
1101 // we're connected to a switch that doesn't support
1102 // the Nicira vendor extensions (i.e. not OVS or
1103 // derived from OVS). By protocol, it should also be
1104 // BAD_VENDOR, but too many switch implementations
1105 // get it wrong and we can already check the xid()
1106 // so we can ignore the type with confidence that this
1107 // is not a spurious error
1108 shouldLogError = !isBadVendorError;
1109 if (isBadVendorError) {
1110 if (state.firstRoleReplyReceived && (role != null)) {
1111 log.warn("Received ERROR from sw {} that "
1112 +"indicates roles are not supported "
1113 +"but we have received a valid "
1114 +"role reply earlier", sw);
1115 }
1116 state.firstRoleReplyReceived = true;
1117 sw.deliverRoleRequestNotSupported(error.getXid());
1118 synchronized(roleChanger) {
1119 if (sw.role == null && Controller.this.role==Role.SLAVE) {
1120 // the switch doesn't understand role request
1121 // messages and the current controller role is
1122 // slave. We need to disconnect the switch.
1123 // @see RoleChanger for rationale
1124 sw.getChannel().close();
1125 }
1126 else if (sw.role == null) {
1127 // Controller's role is master: add to
1128 // active
1129 // TODO: check if clearing flow table is
1130 // right choice here.
1131 // Need to clear FlowMods before we add the switch
1132 // and dispatch updates otherwise we have a race condition.
1133 // TODO: switch update is async. Won't we still have a potential
1134 // race condition?
1135 sw.clearAllFlowMods();
1136 addSwitch(sw);
1137 }
1138 }
1139 }
1140 else {
1141 // TODO: Is this the right thing to do if we receive
1142 // some other error besides a bad vendor error?
1143 // Presumably that means the switch did actually
1144 // understand the role request message, but there
1145 // was some other error from processing the message.
1146 // OF 1.2 specifies a OFPET_ROLE_REQUEST_FAILED
1147 // error code, but it doesn't look like the Nicira
1148 // role request has that. Should check OVS source
1149 // code to see if it's possible for any other errors
1150 // to be returned.
1151 // If we received an error the switch is not
1152 // in the correct role, so we need to disconnect it.
1153 // We could also resend the request but then we need to
1154 // check if there are other pending request in which
1155 // case we shouldn't resend. If we do resend we need
1156 // to make sure that the switch eventually accepts one
1157 // of our requests or disconnect the switch. This feels
1158 // cumbersome.
1159 sw.getChannel().close();
1160 }
1161 }
1162 // Once we support OF 1.2, we'd add code to handle it here.
1163 //if (error.getXid() == state.ofRoleRequestXid) {
1164 //}
1165 if (shouldLogError)
1166 logError(sw, error);
1167 break;
1168 case STATS_REPLY:
1169 if (state.hsState.ordinal() <
1170 HandshakeState.FEATURES_REPLY.ordinal()) {
1171 String em = "Unexpected STATS_REPLY from " + sw;
1172 throw new SwitchStateException(em);
1173 }
1174 sw.deliverStatisticsReply(m);
1175 if (sw.hasAttribute(IOFSwitch.SWITCH_DESCRIPTION_FUTURE)) {
1176 processSwitchDescReply();
1177 }
1178 break;
1179 case PORT_STATUS:
1180 // We want to update our port state info even if we're in
1181 // the slave role, but we only want to update storage if
1182 // we're the master (or equal).
1183 boolean updateStorage = state.hsState.
1184 equals(HandshakeState.READY) &&
1185 (sw.getRole() != Role.SLAVE);
1186 handlePortStatusMessage(sw, (OFPortStatus)m, updateStorage);
1187 shouldHandleMessage = true;
1188 break;
1189
1190 default:
1191 shouldHandleMessage = true;
1192 break;
1193 }
1194
1195 if (shouldHandleMessage) {
1196 sw.getListenerReadLock().lock();
1197 try {
1198 if (sw.isConnected()) {
1199 if (!state.hsState.equals(HandshakeState.READY)) {
1200 log.debug("Ignoring message type {} received " +
1201 "from switch {} before switch is " +
1202 "fully configured.", m.getType(), sw);
1203 }
1204 // Check if the controller is in the slave role for the
1205 // switch. If it is, then don't dispatch the message to
1206 // the listeners.
1207 // TODO: Should we dispatch messages that we expect to
1208 // receive when we're in the slave role, e.g. port
1209 // status messages? Since we're "hiding" switches from
1210 // the listeners when we're in the slave role, then it
1211 // seems a little weird to dispatch port status messages
1212 // to them. On the other hand there might be special
1213 // modules that care about all of the connected switches
1214 // and would like to receive port status notifications.
1215 else if (sw.getRole() == Role.SLAVE) {
1216 // Don't log message if it's a port status message
1217 // since we expect to receive those from the switch
1218 // and don't want to emit spurious messages.
1219 if (m.getType() != OFType.PORT_STATUS) {
1220 log.debug("Ignoring message type {} received " +
1221 "from switch {} while in the slave role.",
1222 m.getType(), sw);
1223 }
1224 } else {
1225 handleMessage(sw, m, null);
1226 }
1227 }
1228 }
1229 finally {
1230 sw.getListenerReadLock().unlock();
1231 }
1232 }
1233 }
1234 }
1235
1236 // ****************
1237 // Message handlers
1238 // ****************
1239
1240 protected void handlePortStatusMessage(IOFSwitch sw,
1241 OFPortStatus m,
1242 boolean updateStorage) {
1243 short portNumber = m.getDesc().getPortNumber();
1244 OFPhysicalPort port = m.getDesc();
1245 if (m.getReason() == (byte)OFPortReason.OFPPR_MODIFY.ordinal()) {
Pankaj Berde6a4075d2013-01-22 16:42:54 -08001246 boolean portDown = ((OFPortConfig.OFPPC_PORT_DOWN.getValue() & port.getConfig()) > 0) ||
1247 ((OFPortState.OFPPS_LINK_DOWN.getValue() & port.getState()) > 0);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001248 sw.setPort(port);
Pankaj Berde6a4075d2013-01-22 16:42:54 -08001249 if (!portDown) {
Pankaj Berde6debb042013-01-16 18:04:32 -08001250 swStore.addPort(sw.getStringId(), port);
1251 } else {
1252 swStore.deletePort(sw.getStringId(), port.getPortNumber());
1253 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001254 if (updateStorage)
1255 updatePortInfo(sw, port);
1256 log.debug("Port #{} modified for {}", portNumber, sw);
1257 } else if (m.getReason() == (byte)OFPortReason.OFPPR_ADD.ordinal()) {
1258 sw.setPort(port);
Pankaj Berde8557a462013-01-07 08:59:31 -08001259 swStore.addPort(sw.getStringId(), port);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001260 if (updateStorage)
1261 updatePortInfo(sw, port);
1262 log.debug("Port #{} added for {}", portNumber, sw);
1263 } else if (m.getReason() ==
1264 (byte)OFPortReason.OFPPR_DELETE.ordinal()) {
1265 sw.deletePort(portNumber);
Pankaj Berde8557a462013-01-07 08:59:31 -08001266 swStore.deletePort(sw.getStringId(), portNumber);
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001267 if (updateStorage)
1268 removePortInfo(sw, portNumber);
1269 log.debug("Port #{} deleted for {}", portNumber, sw);
1270 }
1271 SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.PORTCHANGED);
1272 try {
1273 this.updates.put(update);
1274 } catch (InterruptedException e) {
1275 log.error("Failure adding update to queue", e);
1276 }
1277 }
1278
1279 /**
1280 * flcontext_cache - Keep a thread local stack of contexts
1281 */
1282 protected static final ThreadLocal<Stack<FloodlightContext>> flcontext_cache =
1283 new ThreadLocal <Stack<FloodlightContext>> () {
1284 @Override
1285 protected Stack<FloodlightContext> initialValue() {
1286 return new Stack<FloodlightContext>();
1287 }
1288 };
1289
1290 /**
1291 * flcontext_alloc - pop a context off the stack, if required create a new one
1292 * @return FloodlightContext
1293 */
1294 protected static FloodlightContext flcontext_alloc() {
1295 FloodlightContext flcontext = null;
1296
1297 if (flcontext_cache.get().empty()) {
1298 flcontext = new FloodlightContext();
1299 }
1300 else {
1301 flcontext = flcontext_cache.get().pop();
1302 }
1303
1304 return flcontext;
1305 }
1306
1307 /**
1308 * flcontext_free - Free the context to the current thread
1309 * @param flcontext
1310 */
1311 protected void flcontext_free(FloodlightContext flcontext) {
1312 flcontext.getStorage().clear();
1313 flcontext_cache.get().push(flcontext);
1314 }
1315
1316 /**
1317 * Handle replies to certain OFMessages, and pass others off to listeners
1318 * @param sw The switch for the message
1319 * @param m The message
1320 * @param bContext The floodlight context. If null then floodlight context would
1321 * be allocated in this function
1322 * @throws IOException
1323 */
1324 @LogMessageDocs({
1325 @LogMessageDoc(level="ERROR",
1326 message="Ignoring PacketIn (Xid = {xid}) because the data" +
1327 " field is empty.",
1328 explanation="The switch sent an improperly-formatted PacketIn" +
1329 " message",
1330 recommendation=LogMessageDoc.CHECK_SWITCH),
1331 @LogMessageDoc(level="WARN",
1332 message="Unhandled OF Message: {} from {}",
1333 explanation="The switch sent a message not handled by " +
1334 "the controller")
1335 })
1336 protected void handleMessage(IOFSwitch sw, OFMessage m,
1337 FloodlightContext bContext)
1338 throws IOException {
1339 Ethernet eth = null;
1340
1341 switch (m.getType()) {
1342 case PACKET_IN:
1343 OFPacketIn pi = (OFPacketIn)m;
1344
1345 if (pi.getPacketData().length <= 0) {
1346 log.error("Ignoring PacketIn (Xid = " + pi.getXid() +
1347 ") because the data field is empty.");
1348 return;
1349 }
1350
1351 if (Controller.ALWAYS_DECODE_ETH) {
1352 eth = new Ethernet();
1353 eth.deserialize(pi.getPacketData(), 0,
1354 pi.getPacketData().length);
1355 counterStore.updatePacketInCounters(sw, m, eth);
1356 }
1357 // fall through to default case...
1358
1359 default:
1360
1361 List<IOFMessageListener> listeners = null;
1362 if (messageListeners.containsKey(m.getType())) {
1363 listeners = messageListeners.get(m.getType()).
1364 getOrderedListeners();
1365 }
1366
1367 FloodlightContext bc = null;
1368 if (listeners != null) {
1369 // Check if floodlight context is passed from the calling
1370 // function, if so use that floodlight context, otherwise
1371 // allocate one
1372 if (bContext == null) {
1373 bc = flcontext_alloc();
1374 } else {
1375 bc = bContext;
1376 }
1377 if (eth != null) {
1378 IFloodlightProviderService.bcStore.put(bc,
1379 IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
1380 eth);
1381 }
1382
1383 // Get the starting time (overall and per-component) of
1384 // the processing chain for this packet if performance
1385 // monitoring is turned on
1386 pktinProcTime.bootstrap(listeners);
1387 pktinProcTime.recordStartTimePktIn();
1388 Command cmd;
1389 for (IOFMessageListener listener : listeners) {
1390 if (listener instanceof IOFSwitchFilter) {
1391 if (!((IOFSwitchFilter)listener).isInterested(sw)) {
1392 continue;
1393 }
1394 }
1395
1396 pktinProcTime.recordStartTimeComp(listener);
1397 cmd = listener.receive(sw, m, bc);
1398 pktinProcTime.recordEndTimeComp(listener);
1399
1400 if (Command.STOP.equals(cmd)) {
1401 break;
1402 }
1403 }
1404 pktinProcTime.recordEndTimePktIn(sw, m, bc);
1405 } else {
1406 log.warn("Unhandled OF Message: {} from {}", m, sw);
1407 }
1408
1409 if ((bContext == null) && (bc != null)) flcontext_free(bc);
1410 }
1411 }
1412
1413 /**
1414 * Log an OpenFlow error message from a switch
1415 * @param sw The switch that sent the error
1416 * @param error The error message
1417 */
1418 @LogMessageDoc(level="ERROR",
1419 message="Error {error type} {error code} from {switch}",
1420 explanation="The switch responded with an unexpected error" +
1421 "to an OpenFlow message from the controller",
1422 recommendation="This could indicate improper network operation. " +
1423 "If the problem persists restarting the switch and " +
1424 "controller may help."
1425 )
1426 protected void logError(IOFSwitch sw, OFError error) {
1427 int etint = 0xffff & error.getErrorType();
1428 if (etint < 0 || etint >= OFErrorType.values().length) {
1429 log.error("Unknown error code {} from sw {}", etint, sw);
1430 }
1431 OFErrorType et = OFErrorType.values()[etint];
1432 switch (et) {
1433 case OFPET_HELLO_FAILED:
1434 OFHelloFailedCode hfc =
1435 OFHelloFailedCode.values()[0xffff & error.getErrorCode()];
1436 log.error("Error {} {} from {}", new Object[] {et, hfc, sw});
1437 break;
1438 case OFPET_BAD_REQUEST:
1439 OFBadRequestCode brc =
1440 OFBadRequestCode.values()[0xffff & error.getErrorCode()];
1441 log.error("Error {} {} from {}", new Object[] {et, brc, sw});
1442 break;
1443 case OFPET_BAD_ACTION:
1444 OFBadActionCode bac =
1445 OFBadActionCode.values()[0xffff & error.getErrorCode()];
1446 log.error("Error {} {} from {}", new Object[] {et, bac, sw});
1447 break;
1448 case OFPET_FLOW_MOD_FAILED:
1449 OFFlowModFailedCode fmfc =
1450 OFFlowModFailedCode.values()[0xffff & error.getErrorCode()];
1451 log.error("Error {} {} from {}", new Object[] {et, fmfc, sw});
1452 break;
1453 case OFPET_PORT_MOD_FAILED:
1454 OFPortModFailedCode pmfc =
1455 OFPortModFailedCode.values()[0xffff & error.getErrorCode()];
1456 log.error("Error {} {} from {}", new Object[] {et, pmfc, sw});
1457 break;
1458 case OFPET_QUEUE_OP_FAILED:
1459 OFQueueOpFailedCode qofc =
1460 OFQueueOpFailedCode.values()[0xffff & error.getErrorCode()];
1461 log.error("Error {} {} from {}", new Object[] {et, qofc, sw});
1462 break;
1463 default:
1464 break;
1465 }
1466 }
1467
1468 /**
1469 * Add a switch to the active switch list and call the switch listeners.
1470 * This happens either when a switch first connects (and the controller is
1471 * not in the slave role) or when the role of the controller changes from
1472 * slave to master.
1473 * @param sw the switch that has been added
1474 */
1475 // TODO: need to rethink locking and the synchronous switch update.
1476 // We can / should also handle duplicate DPIDs in connectedSwitches
1477 @LogMessageDoc(level="ERROR",
1478 message="New switch added {switch} for already-added switch {switch}",
1479 explanation="A switch with the same DPID as another switch " +
1480 "connected to the controller. This can be caused by " +
1481 "multiple switches configured with the same DPID, or " +
1482 "by a switch reconnected very quickly after " +
1483 "disconnecting.",
1484 recommendation="If this happens repeatedly, it is likely there " +
1485 "are switches with duplicate DPIDs on the network. " +
1486 "Reconfigure the appropriate switches. If it happens " +
1487 "very rarely, then it is likely this is a transient " +
1488 "network problem that can be ignored."
1489 )
1490 protected void addSwitch(IOFSwitch sw) {
1491 // TODO: is it safe to modify the HashMap without holding
1492 // the old switch's lock?
1493 OFSwitchImpl oldSw = (OFSwitchImpl) this.activeSwitches.put(sw.getId(), sw);
1494 if (sw == oldSw) {
1495 // Note == for object equality, not .equals for value
1496 log.info("New add switch for pre-existing switch {}", sw);
1497 return;
1498 }
1499
1500 if (oldSw != null) {
1501 oldSw.getListenerWriteLock().lock();
1502 try {
1503 log.error("New switch added {} for already-added switch {}",
1504 sw, oldSw);
1505 // Set the connected flag to false to suppress calling
1506 // the listeners for this switch in processOFMessage
1507 oldSw.setConnected(false);
1508
1509 oldSw.cancelAllStatisticsReplies();
1510
1511 updateInactiveSwitchInfo(oldSw);
1512
1513 // we need to clean out old switch state definitively
1514 // before adding the new switch
1515 // FIXME: It seems not completely kosher to call the
1516 // switch listeners here. I thought one of the points of
1517 // having the asynchronous switch update mechanism was so
1518 // the addedSwitch and removedSwitch were always called
1519 // from a single thread to simplify concurrency issues
1520 // for the listener.
1521 if (switchListeners != null) {
1522 for (IOFSwitchListener listener : switchListeners) {
1523 listener.removedSwitch(oldSw);
1524 }
1525 }
1526 // will eventually trigger a removeSwitch(), which will cause
1527 // a "Not removing Switch ... already removed debug message.
1528 // TODO: Figure out a way to handle this that avoids the
1529 // spurious debug message.
1530 oldSw.getChannel().close();
1531 }
1532 finally {
1533 oldSw.getListenerWriteLock().unlock();
1534 }
1535 }
1536
1537 updateActiveSwitchInfo(sw);
Pankaj Berdef8ad2852013-02-27 17:06:14 -08001538 if (registryService.hasControl(sw.getId())) {
1539 swStore.update(sw.getStringId(), SwitchState.ACTIVE, DM_OPERATION.UPDATE);
1540 for (OFPhysicalPort port: sw.getPorts()) {
1541 swStore.addPort(sw.getStringId(), port);
1542 }
Pankaj Berde0fc4e432013-01-12 09:47:22 -08001543 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001544 SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.ADDED);
1545 try {
1546 this.updates.put(update);
1547 } catch (InterruptedException e) {
1548 log.error("Failure adding update to queue", e);
1549 }
1550 }
1551
1552 /**
1553 * Remove a switch from the active switch list and call the switch listeners.
1554 * This happens either when the switch is disconnected or when the
1555 * controller's role for the switch changes from master to slave.
1556 * @param sw the switch that has been removed
1557 */
1558 protected void removeSwitch(IOFSwitch sw) {
1559 // No need to acquire the listener lock, since
1560 // this method is only called after netty has processed all
1561 // pending messages
1562 log.debug("removeSwitch: {}", sw);
Pankaj Berdef8ad2852013-02-27 17:06:14 -08001563 if (registryService.hasControl(sw.getId())) {
1564 swStore.update(sw.getStringId(), SwitchState.INACTIVE, DM_OPERATION.UPDATE);
1565 }
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001566 if (!this.activeSwitches.remove(sw.getId(), sw) || !sw.isConnected()) {
1567 log.debug("Not removing switch {}; already removed", sw);
1568 return;
1569 }
1570 // We cancel all outstanding statistics replies if the switch transition
1571 // from active. In the future we might allow statistics requests
1572 // from slave controllers. Then we need to move this cancelation
1573 // to switch disconnect
1574 sw.cancelAllStatisticsReplies();
Pankaj Berdeafb20532013-01-08 15:05:24 -08001575
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001576
1577 // FIXME: I think there's a race condition if we call updateInactiveSwitchInfo
1578 // here if role support is enabled. In that case if the switch is being
1579 // removed because we've been switched to being in the slave role, then I think
1580 // it's possible that the new master may have already been promoted to master
1581 // and written out the active switch state to storage. If we now execute
1582 // updateInactiveSwitchInfo we may wipe out all of the state that was
1583 // written out by the new master. Maybe need to revisit how we handle all
1584 // of the switch state that's written to storage.
1585
1586 updateInactiveSwitchInfo(sw);
Pankaj Berdeafb20532013-01-08 15:05:24 -08001587
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08001588 SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.REMOVED);
1589 try {
1590 this.updates.put(update);
1591 } catch (InterruptedException e) {
1592 log.error("Failure adding update to queue", e);
1593 }
1594 }
1595
1596 // ***************
1597 // IFloodlightProvider
1598 // ***************
1599
1600 @Override
1601 public synchronized void addOFMessageListener(OFType type,
1602 IOFMessageListener listener) {
1603 ListenerDispatcher<OFType, IOFMessageListener> ldd =
1604 messageListeners.get(type);
1605 if (ldd == null) {
1606 ldd = new ListenerDispatcher<OFType, IOFMessageListener>();
1607 messageListeners.put(type, ldd);
1608 }
1609 ldd.addListener(type, listener);
1610 }
1611
1612 @Override
1613 public synchronized void removeOFMessageListener(OFType type,
1614 IOFMessageListener listener) {
1615 ListenerDispatcher<OFType, IOFMessageListener> ldd =
1616 messageListeners.get(type);
1617 if (ldd != null) {
1618 ldd.removeListener(listener);
1619 }
1620 }
1621
1622 private void logListeners() {
1623 for (Map.Entry<OFType,
1624 ListenerDispatcher<OFType,
1625 IOFMessageListener>> entry
1626 : messageListeners.entrySet()) {
1627
1628 OFType type = entry.getKey();
1629 ListenerDispatcher<OFType, IOFMessageListener> ldd =
1630 entry.getValue();
1631
1632 StringBuffer sb = new StringBuffer();
1633 sb.append("OFListeners for ");
1634 sb.append(type);
1635 sb.append(": ");
1636 for (IOFMessageListener l : ldd.getOrderedListeners()) {
1637 sb.append(l.getName());
1638 sb.append(",");
1639 }
1640 log.debug(sb.toString());
1641 }
1642 }
1643
1644 public void removeOFMessageListeners(OFType type) {
1645 messageListeners.remove(type);
1646 }
1647
1648 @Override
1649 public Map<Long, IOFSwitch> getSwitches() {
1650 return Collections.unmodifiableMap(this.activeSwitches);
1651 }
1652
1653 @Override
1654 public void addOFSwitchListener(IOFSwitchListener listener) {
1655 this.switchListeners.add(listener);
1656 }
1657
1658 @Override
1659 public void removeOFSwitchListener(IOFSwitchListener listener) {
1660 this.switchListeners.remove(listener);
1661 }
1662
1663 @Override
1664 public Map<OFType, List<IOFMessageListener>> getListeners() {
1665 Map<OFType, List<IOFMessageListener>> lers =
1666 new HashMap<OFType, List<IOFMessageListener>>();
1667 for(Entry<OFType, ListenerDispatcher<OFType, IOFMessageListener>> e :
1668 messageListeners.entrySet()) {
1669 lers.put(e.getKey(), e.getValue().getOrderedListeners());
1670 }
1671 return Collections.unmodifiableMap(lers);
1672 }
1673
1674 @Override
1675 @LogMessageDocs({
1676 @LogMessageDoc(message="Failed to inject OFMessage {message} onto " +
1677 "a null switch",
1678 explanation="Failed to process a message because the switch " +
1679 " is no longer connected."),
1680 @LogMessageDoc(level="ERROR",
1681 message="Error reinjecting OFMessage on switch {switch}",
1682 explanation="An I/O error occured while attempting to " +
1683 "process an OpenFlow message",
1684 recommendation=LogMessageDoc.CHECK_SWITCH)
1685 })
1686 public boolean injectOfMessage(IOFSwitch sw, OFMessage msg,
1687 FloodlightContext bc) {
1688 if (sw == null) {
1689 log.info("Failed to inject OFMessage {} onto a null switch", msg);
1690 return false;
1691 }
1692
1693 // FIXME: Do we need to be able to inject messages to switches
1694 // where we're the slave controller (i.e. they're connected but
1695 // not active)?
1696 // FIXME: Don't we need synchronization logic here so we're holding
1697 // the listener read lock when we call handleMessage? After some
1698 // discussions it sounds like the right thing to do here would be to
1699 // inject the message as a netty upstream channel event so it goes
1700 // through the normal netty event processing, including being
1701 // handled
1702 if (!activeSwitches.containsKey(sw.getId())) return false;
1703
1704 try {
1705 // Pass Floodlight context to the handleMessages()
1706 handleMessage(sw, msg, bc);
1707 } catch (IOException e) {
1708 log.error("Error reinjecting OFMessage on switch {}",
1709 HexString.toHexString(sw.getId()));
1710 return false;
1711 }
1712 return true;
1713 }
1714
1715 @Override
1716 @LogMessageDoc(message="Calling System.exit",
1717 explanation="The controller is terminating")
1718 public synchronized void terminate() {
1719 log.info("Calling System.exit");
1720 System.exit(1);
1721 }
1722
1723 @Override
1724 public boolean injectOfMessage(IOFSwitch sw, OFMessage msg) {
1725 // call the overloaded version with floodlight context set to null
1726 return injectOfMessage(sw, msg, null);
1727 }
1728
1729 @Override
1730 public void handleOutgoingMessage(IOFSwitch sw, OFMessage m,
1731 FloodlightContext bc) {
1732 if (log.isTraceEnabled()) {
1733 String str = OFMessage.getDataAsString(sw, m, bc);
1734 log.trace("{}", str);
1735 }
1736
1737 List<IOFMessageListener> listeners = null;
1738 if (messageListeners.containsKey(m.getType())) {
1739 listeners =
1740 messageListeners.get(m.getType()).getOrderedListeners();
1741 }
1742
1743 if (listeners != null) {
1744 for (IOFMessageListener listener : listeners) {
1745 if (listener instanceof IOFSwitchFilter) {
1746 if (!((IOFSwitchFilter)listener).isInterested(sw)) {
1747 continue;
1748 }
1749 }
1750 if (Command.STOP.equals(listener.receive(sw, m, bc))) {
1751 break;
1752 }
1753 }
1754 }
1755 }
1756
1757 @Override
1758 public BasicFactory getOFMessageFactory() {
1759 return factory;
1760 }
1761
1762 @Override
1763 public String getControllerId() {
1764 return controllerId;
1765 }
1766
1767 // **************
1768 // Initialization
1769 // **************
1770
1771 protected void updateAllInactiveSwitchInfo() {
1772 if (role == Role.SLAVE) {
1773 return;
1774 }
1775 String controllerId = getControllerId();
1776 String[] switchColumns = { SWITCH_DATAPATH_ID,
1777 SWITCH_CONTROLLER_ID,
1778 SWITCH_ACTIVE };
1779 String[] portColumns = { PORT_ID, PORT_SWITCH };
1780 IResultSet switchResultSet = null;
1781 try {
1782 OperatorPredicate op =
1783 new OperatorPredicate(SWITCH_CONTROLLER_ID,
1784 OperatorPredicate.Operator.EQ,
1785 controllerId);
1786 switchResultSet =
1787 storageSource.executeQuery(SWITCH_TABLE_NAME,
1788 switchColumns,
1789 op, null);
1790 while (switchResultSet.next()) {
1791 IResultSet portResultSet = null;
1792 try {
1793 String datapathId =
1794 switchResultSet.getString(SWITCH_DATAPATH_ID);
1795 switchResultSet.setBoolean(SWITCH_ACTIVE, Boolean.FALSE);
1796 op = new OperatorPredicate(PORT_SWITCH,
1797 OperatorPredicate.Operator.EQ,
1798 datapathId);
1799 portResultSet =
1800 storageSource.executeQuery(PORT_TABLE_NAME,
1801 portColumns,
1802 op, null);
1803 while (portResultSet.next()) {
1804 portResultSet.deleteRow();
1805 }
1806 portResultSet.save();
1807 }
1808 finally {
1809 if (portResultSet != null)
1810 portResultSet.close();
1811 }
1812 }
1813 switchResultSet.save();
1814 }
1815 finally {
1816 if (switchResultSet != null)
1817 switchResultSet.close();
1818 }
1819 }
1820
1821 protected void updateControllerInfo() {
1822 updateAllInactiveSwitchInfo();
1823
1824 // Write out the controller info to the storage source
1825 Map<String, Object> controllerInfo = new HashMap<String, Object>();
1826 String id = getControllerId();
1827 controllerInfo.put(CONTROLLER_ID, id);
1828 storageSource.updateRow(CONTROLLER_TABLE_NAME, controllerInfo);
1829 }
1830
1831 protected void updateActiveSwitchInfo(IOFSwitch sw) {
1832 if (role == Role.SLAVE) {
1833 return;
1834 }
1835 // Obtain the row info for the switch
1836 Map<String, Object> switchInfo = new HashMap<String, Object>();
1837 String datapathIdString = sw.getStringId();
1838 switchInfo.put(SWITCH_DATAPATH_ID, datapathIdString);
1839 String controllerId = getControllerId();
1840 switchInfo.put(SWITCH_CONTROLLER_ID, controllerId);
1841 Date connectedSince = sw.getConnectedSince();
1842 switchInfo.put(SWITCH_CONNECTED_SINCE, connectedSince);
1843 Channel channel = sw.getChannel();
1844 SocketAddress socketAddress = channel.getRemoteAddress();
1845 if (socketAddress != null) {
1846 String socketAddressString = socketAddress.toString();
1847 switchInfo.put(SWITCH_SOCKET_ADDRESS, socketAddressString);
1848 if (socketAddress instanceof InetSocketAddress) {
1849 InetSocketAddress inetSocketAddress =
1850 (InetSocketAddress)socketAddress;
1851 InetAddress inetAddress = inetSocketAddress.getAddress();
1852 String ip = inetAddress.getHostAddress();
1853 switchInfo.put(SWITCH_IP, ip);
1854 }
1855 }
1856
1857 // Write out the switch features info
1858 long capabilities = U32.f(sw.getCapabilities());
1859 switchInfo.put(SWITCH_CAPABILITIES, capabilities);
1860 long buffers = U32.f(sw.getBuffers());
1861 switchInfo.put(SWITCH_BUFFERS, buffers);
1862 long tables = U32.f(sw.getTables());
1863 switchInfo.put(SWITCH_TABLES, tables);
1864 long actions = U32.f(sw.getActions());
1865 switchInfo.put(SWITCH_ACTIONS, actions);
1866 switchInfo.put(SWITCH_ACTIVE, Boolean.TRUE);
1867
1868 // Update the switch
1869 storageSource.updateRowAsync(SWITCH_TABLE_NAME, switchInfo);
1870
1871 // Update the ports
1872 for (OFPhysicalPort port: sw.getPorts()) {
1873 updatePortInfo(sw, port);
1874 }
1875 }
1876
1877 protected void updateInactiveSwitchInfo(IOFSwitch sw) {
1878 if (role == Role.SLAVE) {
1879 return;
1880 }
1881 log.debug("Update DB with inactiveSW {}", sw);
1882 // Update the controller info in the storage source to be inactive
1883 Map<String, Object> switchInfo = new HashMap<String, Object>();
1884 String datapathIdString = sw.getStringId();
1885 switchInfo.put(SWITCH_DATAPATH_ID, datapathIdString);
1886 //switchInfo.put(SWITCH_CONNECTED_SINCE, null);
1887 switchInfo.put(SWITCH_ACTIVE, Boolean.FALSE);
1888 storageSource.updateRowAsync(SWITCH_TABLE_NAME, switchInfo);
1889 }
1890
1891 protected void updatePortInfo(IOFSwitch sw, OFPhysicalPort port) {
1892 if (role == Role.SLAVE) {
1893 return;
1894 }
1895 String datapathIdString = sw.getStringId();
1896 Map<String, Object> portInfo = new HashMap<String, Object>();
1897 int portNumber = U16.f(port.getPortNumber());
1898 String id = datapathIdString + "|" + portNumber;
1899 portInfo.put(PORT_ID, id);
1900 portInfo.put(PORT_SWITCH, datapathIdString);
1901 portInfo.put(PORT_NUMBER, portNumber);
1902 byte[] hardwareAddress = port.getHardwareAddress();
1903 String hardwareAddressString = HexString.toHexString(hardwareAddress);
1904 portInfo.put(PORT_HARDWARE_ADDRESS, hardwareAddressString);
1905 String name = port.getName();
1906 portInfo.put(PORT_NAME, name);
1907 long config = U32.f(port.getConfig());
1908 portInfo.put(PORT_CONFIG, config);
1909 long state = U32.f(port.getState());
1910 portInfo.put(PORT_STATE, state);
1911 long currentFeatures = U32.f(port.getCurrentFeatures());
1912 portInfo.put(PORT_CURRENT_FEATURES, currentFeatures);
1913 long advertisedFeatures = U32.f(port.getAdvertisedFeatures());
1914 portInfo.put(PORT_ADVERTISED_FEATURES, advertisedFeatures);
1915 long supportedFeatures = U32.f(port.getSupportedFeatures());
1916 portInfo.put(PORT_SUPPORTED_FEATURES, supportedFeatures);
1917 long peerFeatures = U32.f(port.getPeerFeatures());
1918 portInfo.put(PORT_PEER_FEATURES, peerFeatures);
1919 storageSource.updateRowAsync(PORT_TABLE_NAME, portInfo);
1920 }
1921
1922 /**
1923 * Read switch port data from storage and write it into a switch object
1924 * @param sw the switch to update
1925 */
1926 protected void readSwitchPortStateFromStorage(OFSwitchImpl sw) {
1927 OperatorPredicate op =
1928 new OperatorPredicate(PORT_SWITCH,
1929 OperatorPredicate.Operator.EQ,
1930 sw.getStringId());
1931 IResultSet portResultSet =
1932 storageSource.executeQuery(PORT_TABLE_NAME,
1933 null, op, null);
1934 //Map<Short, OFPhysicalPort> oldports =
1935 // new HashMap<Short, OFPhysicalPort>();
1936 //oldports.putAll(sw.getPorts());
1937
1938 while (portResultSet.next()) {
1939 try {
1940 OFPhysicalPort p = new OFPhysicalPort();
1941 p.setPortNumber((short)portResultSet.getInt(PORT_NUMBER));
1942 p.setName(portResultSet.getString(PORT_NAME));
1943 p.setConfig((int)portResultSet.getLong(PORT_CONFIG));
1944 p.setState((int)portResultSet.getLong(PORT_STATE));
1945 String portMac = portResultSet.getString(PORT_HARDWARE_ADDRESS);
1946 p.setHardwareAddress(HexString.fromHexString(portMac));
1947 p.setCurrentFeatures((int)portResultSet.
1948 getLong(PORT_CURRENT_FEATURES));
1949 p.setAdvertisedFeatures((int)portResultSet.
1950 getLong(PORT_ADVERTISED_FEATURES));
1951 p.setSupportedFeatures((int)portResultSet.
1952 getLong(PORT_SUPPORTED_FEATURES));
1953 p.setPeerFeatures((int)portResultSet.
1954 getLong(PORT_PEER_FEATURES));
1955 //oldports.remove(Short.valueOf(p.getPortNumber()));
1956 sw.setPort(p);
1957 } catch (NullPointerException e) {
1958 // ignore
1959 }
1960 }
1961 SwitchUpdate update = new SwitchUpdate(sw, SwitchUpdateType.PORTCHANGED);
1962 try {
1963 this.updates.put(update);
1964 } catch (InterruptedException e) {
1965 log.error("Failure adding update to queue", e);
1966 }
1967 }
1968
1969 protected void removePortInfo(IOFSwitch sw, short portNumber) {
1970 if (role == Role.SLAVE) {
1971 return;
1972 }
1973 String datapathIdString = sw.getStringId();
1974 String id = datapathIdString + "|" + portNumber;
1975 storageSource.deleteRowAsync(PORT_TABLE_NAME, id);
1976 }
1977
1978 /**
1979 * Sets the initial role based on properties in the config params.
1980 * It looks for two different properties.
1981 * If the "role" property is specified then the value should be
1982 * either "EQUAL", "MASTER", or "SLAVE" and the role of the
1983 * controller is set to the specified value. If the "role" property
1984 * is not specified then it looks next for the "role.path" property.
1985 * In this case the value should be the path to a property file in
1986 * the file system that contains a property called "floodlight.role"
1987 * which can be one of the values listed above for the "role" property.
1988 * The idea behind the "role.path" mechanism is that you have some
1989 * separate heartbeat and master controller election algorithm that
1990 * determines the role of the controller. When a role transition happens,
1991 * it updates the current role in the file specified by the "role.path"
1992 * file. Then if floodlight restarts for some reason it can get the
1993 * correct current role of the controller from the file.
1994 * @param configParams The config params for the FloodlightProvider service
1995 * @return A valid role if role information is specified in the
1996 * config params, otherwise null
1997 */
1998 @LogMessageDocs({
1999 @LogMessageDoc(message="Controller role set to {role}",
2000 explanation="Setting the initial HA role to "),
2001 @LogMessageDoc(level="ERROR",
2002 message="Invalid current role value: {role}",
2003 explanation="An invalid HA role value was read from the " +
2004 "properties file",
2005 recommendation=LogMessageDoc.CHECK_CONTROLLER)
2006 })
2007 protected Role getInitialRole(Map<String, String> configParams) {
2008 Role role = null;
2009 String roleString = configParams.get("role");
2010 if (roleString == null) {
2011 String rolePath = configParams.get("rolepath");
2012 if (rolePath != null) {
2013 Properties properties = new Properties();
2014 try {
2015 properties.load(new FileInputStream(rolePath));
2016 roleString = properties.getProperty("floodlight.role");
2017 }
2018 catch (IOException exc) {
2019 // Don't treat it as an error if the file specified by the
2020 // rolepath property doesn't exist. This lets us enable the
2021 // HA mechanism by just creating/setting the floodlight.role
2022 // property in that file without having to modify the
2023 // floodlight properties.
2024 }
2025 }
2026 }
2027
2028 if (roleString != null) {
2029 // Canonicalize the string to the form used for the enum constants
2030 roleString = roleString.trim().toUpperCase();
2031 try {
2032 role = Role.valueOf(roleString);
2033 }
2034 catch (IllegalArgumentException exc) {
2035 log.error("Invalid current role value: {}", roleString);
2036 }
2037 }
2038
2039 log.info("Controller role set to {}", role);
2040
2041 return role;
2042 }
2043
2044 /**
2045 * Tell controller that we're ready to accept switches loop
2046 * @throws IOException
2047 */
2048 @LogMessageDocs({
2049 @LogMessageDoc(message="Listening for switch connections on {address}",
2050 explanation="The controller is ready and listening for new" +
2051 " switch connections"),
2052 @LogMessageDoc(message="Storage exception in controller " +
2053 "updates loop; terminating process",
2054 explanation=ERROR_DATABASE,
2055 recommendation=LogMessageDoc.CHECK_CONTROLLER),
2056 @LogMessageDoc(level="ERROR",
2057 message="Exception in controller updates loop",
2058 explanation="Failed to dispatch controller event",
2059 recommendation=LogMessageDoc.GENERIC_ACTION)
2060 })
2061 public void run() {
2062 if (log.isDebugEnabled()) {
2063 logListeners();
2064 }
2065
2066 try {
2067 final ServerBootstrap bootstrap = createServerBootStrap();
2068
2069 bootstrap.setOption("reuseAddr", true);
2070 bootstrap.setOption("child.keepAlive", true);
2071 bootstrap.setOption("child.tcpNoDelay", true);
2072 bootstrap.setOption("child.sendBufferSize", Controller.SEND_BUFFER_SIZE);
2073
2074 ChannelPipelineFactory pfact =
2075 new OpenflowPipelineFactory(this, null);
2076 bootstrap.setPipelineFactory(pfact);
2077 InetSocketAddress sa = new InetSocketAddress(openFlowPort);
2078 final ChannelGroup cg = new DefaultChannelGroup();
2079 cg.add(bootstrap.bind(sa));
2080
2081 log.info("Listening for switch connections on {}", sa);
2082 } catch (Exception e) {
2083 throw new RuntimeException(e);
2084 }
2085
2086 // main loop
2087 while (true) {
2088 try {
2089 IUpdate update = updates.take();
2090 update.dispatch();
2091 } catch (InterruptedException e) {
2092 return;
2093 } catch (StorageException e) {
2094 log.error("Storage exception in controller " +
2095 "updates loop; terminating process", e);
2096 return;
2097 } catch (Exception e) {
2098 log.error("Exception in controller updates loop", e);
2099 }
2100 }
2101 }
2102
2103 private ServerBootstrap createServerBootStrap() {
2104 if (workerThreads == 0) {
2105 return new ServerBootstrap(
2106 new NioServerSocketChannelFactory(
2107 Executors.newCachedThreadPool(),
2108 Executors.newCachedThreadPool()));
2109 } else {
2110 return new ServerBootstrap(
2111 new NioServerSocketChannelFactory(
2112 Executors.newCachedThreadPool(),
2113 Executors.newCachedThreadPool(), workerThreads));
2114 }
2115 }
2116
2117 public void setConfigParams(Map<String, String> configParams) {
2118 String ofPort = configParams.get("openflowport");
2119 if (ofPort != null) {
2120 this.openFlowPort = Integer.parseInt(ofPort);
2121 }
2122 log.debug("OpenFlow port set to {}", this.openFlowPort);
2123 String threads = configParams.get("workerthreads");
2124 if (threads != null) {
2125 this.workerThreads = Integer.parseInt(threads);
2126 }
2127 log.debug("Number of worker threads set to {}", this.workerThreads);
2128 String controllerId = configParams.get("controllerid");
2129 if (controllerId != null) {
2130 this.controllerId = controllerId;
2131 }
Jonathan Hartd10008d2013-02-23 17:04:08 -08002132 else {
2133 //Try to get the hostname of the machine and use that for controller ID
2134 try {
2135 String hostname = java.net.InetAddress.getLocalHost().getHostName();
2136 this.controllerId = hostname;
2137 } catch (UnknownHostException e) {
2138 // Can't get hostname, we'll just use the default
2139 }
2140 }
2141
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08002142 log.debug("ControllerId set to {}", this.controllerId);
2143 }
2144
2145 private void initVendorMessages() {
2146 // Configure openflowj to be able to parse the role request/reply
2147 // vendor messages.
2148 OFBasicVendorId niciraVendorId = new OFBasicVendorId(
2149 OFNiciraVendorData.NX_VENDOR_ID, 4);
2150 OFVendorId.registerVendorId(niciraVendorId);
2151 OFBasicVendorDataType roleRequestVendorData =
2152 new OFBasicVendorDataType(
2153 OFRoleRequestVendorData.NXT_ROLE_REQUEST,
2154 OFRoleRequestVendorData.getInstantiable());
2155 niciraVendorId.registerVendorDataType(roleRequestVendorData);
2156 OFBasicVendorDataType roleReplyVendorData =
2157 new OFBasicVendorDataType(
2158 OFRoleReplyVendorData.NXT_ROLE_REPLY,
2159 OFRoleReplyVendorData.getInstantiable());
2160 niciraVendorId.registerVendorDataType(roleReplyVendorData);
2161 }
2162
2163 /**
2164 * Initialize internal data structures
2165 */
2166 public void init(Map<String, String> configParams) {
2167 // These data structures are initialized here because other
2168 // module's startUp() might be called before ours
2169 this.messageListeners =
2170 new ConcurrentHashMap<OFType,
2171 ListenerDispatcher<OFType,
2172 IOFMessageListener>>();
2173 this.switchListeners = new CopyOnWriteArraySet<IOFSwitchListener>();
2174 this.haListeners = new CopyOnWriteArraySet<IHAListener>();
2175 this.activeSwitches = new ConcurrentHashMap<Long, IOFSwitch>();
2176 this.connectedSwitches = new HashSet<OFSwitchImpl>();
2177 this.controllerNodeIPsCache = new HashMap<String, String>();
2178 this.updates = new LinkedBlockingQueue<IUpdate>();
2179 this.factory = new BasicFactory();
2180 this.providerMap = new HashMap<String, List<IInfoProvider>>();
2181 setConfigParams(configParams);
Jonathan Hartcc957a02013-02-26 10:39:04 -08002182 //this.role = getInitialRole(configParams);
2183 //Set the controller's role to MASTER so it always tries to do role requests.
2184 this.role = Role.MASTER;
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08002185 this.roleChanger = new RoleChanger();
2186 initVendorMessages();
2187 this.systemStartTime = System.currentTimeMillis();
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08002188 }
2189
2190 /**
2191 * Startup all of the controller's components
2192 */
2193 @LogMessageDoc(message="Waiting for storage source",
2194 explanation="The system database is not yet ready",
2195 recommendation="If this message persists, this indicates " +
2196 "that the system database has failed to start. " +
2197 LogMessageDoc.CHECK_CONTROLLER)
2198 public void startupComponents() {
Jonathan Hartd10008d2013-02-23 17:04:08 -08002199 try {
2200 registryService.registerController(controllerId);
2201 } catch (RegistryException e2) {
2202 log.warn("Registry service error: {}", e2.getMessage());
2203 }
2204
Umesh Krishnaswamy345ee992012-12-13 20:29:48 -08002205 // Create the table names we use
2206 storageSource.createTable(CONTROLLER_TABLE_NAME, null);
2207 storageSource.createTable(SWITCH_TABLE_NAME, null);
2208 storageSource.createTable(PORT_TABLE_NAME, null);
2209 storageSource.createTable(CONTROLLER_INTERFACE_TABLE_NAME, null);
2210 storageSource.createTable(SWITCH_CONFIG_TABLE_NAME, null);
2211 storageSource.setTablePrimaryKeyName(CONTROLLER_TABLE_NAME,
2212 CONTROLLER_ID);
2213 storageSource.setTablePrimaryKeyName(SWITCH_TABLE_NAME,
2214 SWITCH_DATAPATH_ID);
2215 storageSource.setTablePrimaryKeyName(PORT_TABLE_NAME, PORT_ID);
2216 storageSource.setTablePrimaryKeyName(CONTROLLER_INTERFACE_TABLE_NAME,
2217 CONTROLLER_INTERFACE_ID);
2218 storageSource.addListener(CONTROLLER_INTERFACE_TABLE_NAME, this);
2219
2220 while (true) {
2221 try {
2222 updateControllerInfo();
2223 break;
2224 }
2225 catch (StorageException e) {
2226 log.info("Waiting for storage source");
2227 try {
2228 Thread.sleep(1000);
2229 } catch (InterruptedException e1) {
2230 }
2231 }
2232 }
2233
2234 // Add our REST API
2235 restApi.addRestletRoutable(new CoreWebRoutable());
2236 }
2237
2238 @Override
2239 public void addInfoProvider(String type, IInfoProvider provider) {
2240 if (!providerMap.containsKey(type)) {
2241 providerMap.put(type, new ArrayList<IInfoProvider>());
2242 }
2243 providerMap.get(type).add(provider);
2244 }
2245
2246 @Override
2247 public void removeInfoProvider(String type, IInfoProvider provider) {
2248 if (!providerMap.containsKey(type)) {
2249 log.debug("Provider type {} doesn't exist.", type);
2250 return;
2251 }
2252
2253 providerMap.get(type).remove(provider);
2254 }
2255
2256 public Map<String, Object> getControllerInfo(String type) {
2257 if (!providerMap.containsKey(type)) return null;
2258
2259 Map<String, Object> result = new LinkedHashMap<String, Object>();
2260 for (IInfoProvider provider : providerMap.get(type)) {
2261 result.putAll(provider.getInfo(type));
2262 }
2263
2264 return result;
2265 }
2266
2267 @Override
2268 public void addHAListener(IHAListener listener) {
2269 this.haListeners.add(listener);
2270 }
2271
2272 @Override
2273 public void removeHAListener(IHAListener listener) {
2274 this.haListeners.remove(listener);
2275 }
2276
2277
2278 /**
2279 * Handle changes to the controller nodes IPs and dispatch update.
2280 */
2281 @SuppressWarnings("unchecked")
2282 protected void handleControllerNodeIPChanges() {
2283 HashMap<String,String> curControllerNodeIPs = new HashMap<String,String>();
2284 HashMap<String,String> addedControllerNodeIPs = new HashMap<String,String>();
2285 HashMap<String,String> removedControllerNodeIPs =new HashMap<String,String>();
2286 String[] colNames = { CONTROLLER_INTERFACE_CONTROLLER_ID,
2287 CONTROLLER_INTERFACE_TYPE,
2288 CONTROLLER_INTERFACE_NUMBER,
2289 CONTROLLER_INTERFACE_DISCOVERED_IP };
2290 synchronized(controllerNodeIPsCache) {
2291 // We currently assume that interface Ethernet0 is the relevant
2292 // controller interface. Might change.
2293 // We could (should?) implement this using
2294 // predicates, but creating the individual and compound predicate
2295 // seems more overhead then just checking every row. Particularly,
2296 // since the number of rows is small and changes infrequent
2297 IResultSet res = storageSource.executeQuery(CONTROLLER_INTERFACE_TABLE_NAME,
2298 colNames,null, null);
2299 while (res.next()) {
2300 if (res.getString(CONTROLLER_INTERFACE_TYPE).equals("Ethernet") &&
2301 res.getInt(CONTROLLER_INTERFACE_NUMBER) == 0) {
2302 String controllerID = res.getString(CONTROLLER_INTERFACE_CONTROLLER_ID);
2303 String discoveredIP = res.getString(CONTROLLER_INTERFACE_DISCOVERED_IP);
2304 String curIP = controllerNodeIPsCache.get(controllerID);
2305
2306 curControllerNodeIPs.put(controllerID, discoveredIP);
2307 if (curIP == null) {
2308 // new controller node IP
2309 addedControllerNodeIPs.put(controllerID, discoveredIP);
2310 }
2311 else if (curIP != discoveredIP) {
2312 // IP changed
2313 removedControllerNodeIPs.put(controllerID, curIP);
2314 addedControllerNodeIPs.put(controllerID, discoveredIP);
2315 }
2316 }
2317 }
2318 // Now figure out if rows have been deleted. We can't use the
2319 // rowKeys from rowsDeleted directly, since the tables primary
2320 // key is a compound that we can't disassemble
2321 Set<String> curEntries = curControllerNodeIPs.keySet();
2322 Set<String> removedEntries = controllerNodeIPsCache.keySet();
2323 removedEntries.removeAll(curEntries);
2324 for (String removedControllerID : removedEntries)
2325 removedControllerNodeIPs.put(removedControllerID, controllerNodeIPsCache.get(removedControllerID));
2326 controllerNodeIPsCache = (HashMap<String, String>) curControllerNodeIPs.clone();
2327 HAControllerNodeIPUpdate update = new HAControllerNodeIPUpdate(
2328 curControllerNodeIPs, addedControllerNodeIPs,
2329 removedControllerNodeIPs);
2330 if (!removedControllerNodeIPs.isEmpty() || !addedControllerNodeIPs.isEmpty()) {
2331 try {
2332 this.updates.put(update);
2333 } catch (InterruptedException e) {
2334 log.error("Failure adding update to queue", e);
2335 }
2336 }
2337 }
2338 }
2339
2340 @Override
2341 public Map<String, String> getControllerNodeIPs() {
2342 // We return a copy of the mapping so we can guarantee that
2343 // the mapping return is the same as one that will be (or was)
2344 // dispatched to IHAListeners
2345 HashMap<String,String> retval = new HashMap<String,String>();
2346 synchronized(controllerNodeIPsCache) {
2347 retval.putAll(controllerNodeIPsCache);
2348 }
2349 return retval;
2350 }
2351
2352 @Override
2353 public void rowsModified(String tableName, Set<Object> rowKeys) {
2354 if (tableName.equals(CONTROLLER_INTERFACE_TABLE_NAME)) {
2355 handleControllerNodeIPChanges();
2356 }
2357
2358 }
2359
2360 @Override
2361 public void rowsDeleted(String tableName, Set<Object> rowKeys) {
2362 if (tableName.equals(CONTROLLER_INTERFACE_TABLE_NAME)) {
2363 handleControllerNodeIPChanges();
2364 }
2365 }
2366
2367 @Override
2368 public long getSystemStartTime() {
2369 return (this.systemStartTime);
2370 }
2371
2372 @Override
2373 public void setAlwaysClearFlowsOnSwAdd(boolean value) {
2374 this.alwaysClearFlowsOnSwAdd = value;
2375 }
2376
2377 public boolean getAlwaysClearFlowsOnSwAdd() {
2378 return this.alwaysClearFlowsOnSwAdd;
2379 }
2380}