2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.protocol_plugin.openflow.core.internal;
11 import java.io.IOException;
12 import java.nio.channels.SelectionKey;
13 import java.nio.channels.Selector;
14 import java.nio.channels.ServerSocketChannel;
15 import java.nio.channels.SocketChannel;
16 import java.util.Date;
17 import java.util.Iterator;
19 import java.util.Map.Entry;
21 import java.util.concurrent.BlockingQueue;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ConcurrentMap;
24 import java.util.concurrent.LinkedBlockingQueue;
25 import java.util.concurrent.atomic.AtomicInteger;
27 import org.eclipse.osgi.framework.console.CommandInterpreter;
28 import org.eclipse.osgi.framework.console.CommandProvider;
29 import org.opendaylight.controller.protocol_plugin.openflow.core.IController;
30 import org.opendaylight.controller.protocol_plugin.openflow.core.IMessageListener;
31 import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitch;
32 import org.opendaylight.controller.protocol_plugin.openflow.core.ISwitchStateListener;
33 import org.opendaylight.controller.sal.connection.ConnectionConstants;
34 import org.opendaylight.controller.sal.connection.IPluginInConnectionService;
35 import org.opendaylight.controller.sal.connection.IPluginOutConnectionService;
36 import org.opendaylight.controller.sal.core.Node;
37 import org.opendaylight.controller.sal.utils.Status;
38 import org.opendaylight.controller.sal.utils.StatusCode;
39 import org.openflow.protocol.OFMessage;
40 import org.openflow.protocol.OFType;
41 import org.openflow.util.HexString;
42 import org.osgi.framework.BundleContext;
43 import org.osgi.framework.FrameworkUtil;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 public class Controller implements IController, CommandProvider, IPluginInConnectionService {
48 private static final Logger logger = LoggerFactory
49 .getLogger(Controller.class);
50 private ControllerIO controllerIO;
51 private Thread switchEventThread;
52 private ConcurrentHashMap<Long, ISwitch> switches;
53 private BlockingQueue<SwitchEvent> switchEvents;
54 // only 1 message listener per OFType
55 private ConcurrentMap<OFType, IMessageListener> messageListeners;
56 // only 1 switch state listener
57 private ISwitchStateListener switchStateListener;
58 private AtomicInteger switchInstanceNumber;
59 private int MAXQUEUESIZE = 50000;
62 * this thread monitors the switchEvents queue for new incoming events from
65 private class EventHandler implements Runnable {
71 SwitchEvent ev = switchEvents.take();
72 SwitchEvent.SwitchEventType eType = ev.getEventType();
73 ISwitch sw = ev.getSwitch();
76 Long sid = sw.getId();
77 ISwitch existingSwitch = switches.get(sid);
78 if (existingSwitch != null) {
79 logger.info("Replacing existing {} with New {}",
81 disconnectSwitch(existingSwitch);
83 switches.put(sid, sw);
84 notifySwitchAdded(sw);
93 OFMessage msg = ev.getMsg();
95 IMessageListener listener = messageListeners
97 if (listener != null) {
98 listener.receive(sw, msg);
103 logger.error("Unknown switch event {}", eType.ordinal());
105 } catch (InterruptedException e) {
106 switchEvents.clear();
115 * Function called by the dependency manager when all the required
116 * dependencies are satisfied
120 logger.debug("Initializing!");
121 this.switches = new ConcurrentHashMap<Long, ISwitch>();
122 this.switchEvents = new LinkedBlockingQueue<SwitchEvent>(MAXQUEUESIZE);
123 this.messageListeners = new ConcurrentHashMap<OFType, IMessageListener>();
124 this.switchStateListener = null;
125 this.switchInstanceNumber = new AtomicInteger(0);
126 registerWithOSGIConsole();
130 * Function called by dependency manager after "init ()" is called and after
131 * the services provided by the class are registered in the service registry
134 public void start() {
135 logger.debug("Starting!");
137 * start a thread to handle event coming from the switch
139 switchEventThread = new Thread(new EventHandler(), "SwitchEvent Thread");
140 switchEventThread.start();
142 // spawn a thread to start to listen on the open flow port
143 controllerIO = new ControllerIO(this);
145 controllerIO.start();
146 } catch (IOException ex) {
147 logger.error("Caught exception while starting:", ex);
152 * Function called by the dependency manager before the services exported by
153 * the component are unregistered, this will be followed by a "destroy ()"
158 for (Iterator<Entry<Long, ISwitch>> it = switches.entrySet().iterator(); it
160 Entry<Long, ISwitch> entry = it.next();
161 ((SwitchHandler) entry.getValue()).stop();
164 switchEventThread.interrupt();
166 controllerIO.shutDown();
167 } catch (IOException ex) {
168 logger.error("Caught exception while stopping:", ex);
173 * Function called by the dependency manager when at least one dependency
174 * become unsatisfied or when the component is shutting down because for
175 * example bundle is being stopped.
178 public void destroy() {
182 public void addMessageListener(OFType type, IMessageListener listener) {
183 IMessageListener currentListener = this.messageListeners.get(type);
184 if (currentListener != null) {
185 logger.warn("{} is already listened by {}", type,
188 this.messageListeners.put(type, listener);
189 logger.debug("{} is now listened by {}", type, listener);
193 public void removeMessageListener(OFType type, IMessageListener listener) {
194 IMessageListener currentListener = this.messageListeners.get(type);
195 if ((currentListener != null) && (currentListener == listener)) {
196 logger.debug("{} listener {} is Removed", type, listener);
197 this.messageListeners.remove(type);
202 public void addSwitchStateListener(ISwitchStateListener listener) {
203 if (this.switchStateListener != null) {
204 logger.warn("Switch events are already listened by {}",
205 this.switchStateListener);
207 this.switchStateListener = listener;
208 logger.debug("Switch events are now listened by {}", listener);
212 public void removeSwitchStateListener(ISwitchStateListener listener) {
213 if ((this.switchStateListener != null)
214 && (this.switchStateListener == listener)) {
215 logger.debug("SwitchStateListener {} is Removed", listener);
216 this.switchStateListener = null;
220 public void handleNewConnection(Selector selector,
221 SelectionKey serverSelectionKey) {
222 ServerSocketChannel ssc = (ServerSocketChannel) serverSelectionKey
224 SocketChannel sc = null;
228 int i = this.switchInstanceNumber.addAndGet(1);
229 String instanceName = "SwitchHandler-" + i;
230 SwitchHandler switchHandler = new SwitchHandler(this, sc, instanceName);
231 switchHandler.start();
232 if (sc.isConnected()) {
233 logger.info("Switch:{} is connected to the Controller",
234 sc.socket().getRemoteSocketAddress()
235 .toString().split("/")[1]);
238 } catch (IOException e) {
243 private void disconnectSwitch(ISwitch sw) {
244 if (((SwitchHandler) sw).isOperational()) {
245 Long sid = sw.getId();
246 if (this.switches.remove(sid, sw)) {
247 logger.warn("{} is Disconnected", sw);
248 notifySwitchDeleted(sw);
251 ((SwitchHandler) sw).stop();
255 private void notifySwitchAdded(ISwitch sw) {
256 if (switchStateListener != null) {
257 switchStateListener.switchAdded(sw);
261 private void notifySwitchDeleted(ISwitch sw) {
262 if (switchStateListener != null) {
263 switchStateListener.switchDeleted(sw);
267 private synchronized void addSwitchEvent(SwitchEvent event) {
269 this.switchEvents.put(event);
270 } catch (InterruptedException e) {
271 logger.debug("SwitchEvent caught Interrupt Exception");
275 public void takeSwitchEventAdd(ISwitch sw) {
276 SwitchEvent ev = new SwitchEvent(
277 SwitchEvent.SwitchEventType.SWITCH_ADD, sw, null);
281 public void takeSwitchEventDelete(ISwitch sw) {
282 SwitchEvent ev = new SwitchEvent(
283 SwitchEvent.SwitchEventType.SWITCH_DELETE, sw, null);
287 public void takeSwitchEventError(ISwitch sw) {
288 SwitchEvent ev = new SwitchEvent(
289 SwitchEvent.SwitchEventType.SWITCH_ERROR, sw, null);
293 public void takeSwitchEventMsg(ISwitch sw, OFMessage msg) {
294 if (messageListeners.get(msg.getType()) != null) {
295 SwitchEvent ev = new SwitchEvent(
296 SwitchEvent.SwitchEventType.SWITCH_MESSAGE, sw, msg);
302 public Map<Long, ISwitch> getSwitches() {
303 return this.switches;
307 public ISwitch getSwitch(Long switchId) {
308 return this.switches.get(switchId);
311 public void _controllerShowSwitches(CommandInterpreter ci) {
312 Set<Long> sids = switches.keySet();
313 StringBuffer s = new StringBuffer();
314 int size = sids.size();
316 ci.print("switches: empty");
319 Iterator<Long> iter = sids.iterator();
320 s.append("Total: " + size + " switches\n");
321 while (iter.hasNext()) {
322 Long sid = iter.next();
323 Date date = switches.get(sid).getConnectedDate();
324 String switchInstanceName = ((SwitchHandler) switches.get(sid))
326 s.append(switchInstanceName + "/" + HexString.toHexString(sid)
327 + " connected since " + date.toString() + "\n");
329 ci.print(s.toString());
333 public void _controllerReset(CommandInterpreter ci) {
334 ci.print("...Disconnecting the communication to all switches...\n");
338 } catch (InterruptedException ie) {
340 ci.print("...start to accept connections from switches...\n");
345 public void _controllerShowConnConfig(CommandInterpreter ci) {
346 String str = System.getProperty("secureChannelEnabled");
347 if ((str != null) && (str.trim().equalsIgnoreCase("true"))) {
348 ci.print("The Controller and Switch should communicate through TLS connetion.\n");
350 String keyStoreFile = System.getProperty("controllerKeyStore");
351 String trustStoreFile = System.getProperty("controllerTrustStore");
352 if ((keyStoreFile == null) || keyStoreFile.trim().isEmpty()) {
353 ci.print("controllerKeyStore not specified in ./configuration/config.ini\n");
355 ci.print("controllerKeyStore=" + keyStoreFile + "\n");
357 if ((trustStoreFile == null) || trustStoreFile.trim().isEmpty()) {
358 ci.print("controllerTrustStore not specified in ./configuration/config.ini\n");
360 ci.print("controllerTrustStore=" + trustStoreFile + "\n");
363 ci.print("The Controller and Switch should communicate through TCP connetion.\n");
367 private void registerWithOSGIConsole() {
368 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
370 bundleContext.registerService(CommandProvider.class.getName(), this,
375 public String getHelp() {
376 StringBuffer help = new StringBuffer();
377 help.append("---Open Flow Controller---\n");
378 help.append("\t controllerShowSwitches\n");
379 help.append("\t controllerReset\n");
380 help.append("\t controllerShowConnConfig\n");
381 return help.toString();
385 public Status disconnect(Node node) {
386 ISwitch sw = getSwitch((Long) node.getID());
387 if (sw != null) disconnectSwitch(sw);
388 return new Status(StatusCode.SUCCESS);
392 public Node connect(String connectionIdentifier, Map<ConnectionConstants, String> params) {
397 * View Change notification
399 public void notifyClusterViewChanged() {
400 for (ISwitch sw : switches.values()) {
401 notifySwitchAdded(sw);
406 * Node Disconnected from the node's master controller.
409 public void notifyNodeDisconnectFromMaster(Node node) {
410 ISwitch sw = switches.get((Long)node.getID());
411 if (sw != null) notifySwitchAdded(sw);