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