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