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