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.openflow.protocol.OFMessage;
34 import org.openflow.protocol.OFType;
35 import org.openflow.util.HexString;
36 import org.osgi.framework.BundleContext;
37 import org.osgi.framework.FrameworkUtil;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 public class Controller implements IController, CommandProvider {
42 private static final Logger logger = LoggerFactory
43 .getLogger(Controller.class);
44 private ControllerIO controllerIO;
45 private Thread switchEventThread;
46 private ConcurrentHashMap<Long, ISwitch> switches;
47 private BlockingQueue<SwitchEvent> switchEvents;
48 // only 1 message listener per OFType
49 private ConcurrentMap<OFType, IMessageListener> messageListeners;
50 // only 1 switch state listener
51 private ISwitchStateListener switchStateListener;
52 private AtomicInteger switchInstanceNumber;
55 * this thread monitors the switchEvents queue for new incoming events from
58 private class EventHandler implements Runnable {
64 SwitchEvent ev = switchEvents.take();
65 SwitchEvent.SwitchEventType eType = ev.getEventType();
66 ISwitch sw = ev.getSwitch();
69 Long sid = sw.getId();
70 ISwitch existingSwitch = switches.get(sid);
71 if (existingSwitch != null) {
72 logger.info("Replacing existing {} with New {}",
73 existingSwitch.toString(), sw.toString());
74 disconnectSwitch(existingSwitch);
76 switches.put(sid, sw);
77 notifySwitchAdded(sw);
86 OFMessage msg = ev.getMsg();
88 IMessageListener listener = messageListeners
90 if (listener != null) {
91 listener.receive(sw, msg);
96 logger.error("Unknown switch event {}", eType.ordinal());
98 } catch (InterruptedException e) {
108 * Function called by the dependency manager when all the required
109 * dependencies are satisfied
113 logger.debug("Initializing!");
114 this.switches = new ConcurrentHashMap<Long, ISwitch>();
115 this.switchEvents = new LinkedBlockingQueue<SwitchEvent>();
116 this.messageListeners = new ConcurrentHashMap<OFType, IMessageListener>();
117 this.switchStateListener = null;
118 this.switchInstanceNumber = new AtomicInteger(0);
119 registerWithOSGIConsole();
123 * Function called by dependency manager after "init ()" is called and after
124 * the services provided by the class are registered in the service registry
127 public void start() {
128 logger.debug("Starting!");
130 * start a thread to handle event coming from the switch
132 switchEventThread = new Thread(new EventHandler(), "SwitchEvent Thread");
133 switchEventThread.start();
135 // spawn a thread to start to listen on the open flow port
136 controllerIO = new ControllerIO(this);
138 controllerIO.start();
139 } catch (IOException ex) {
140 logger.error("Caught exception while starting:", ex);
145 * Function called by the dependency manager before the services exported by
146 * the component are unregistered, this will be followed by a "destroy ()"
151 for (Iterator<Entry<Long, ISwitch>> it = switches.entrySet().iterator(); it
153 Entry<Long, ISwitch> entry = it.next();
154 ((SwitchHandler) entry.getValue()).stop();
157 switchEventThread.interrupt();
159 controllerIO.shutDown();
160 } catch (IOException ex) {
161 logger.error("Caught exception while stopping:", ex);
166 * Function called by the dependency manager when at least one dependency
167 * become unsatisfied or when the component is shutting down because for
168 * example bundle is being stopped.
171 public void destroy() {
175 public void addMessageListener(OFType type, IMessageListener listener) {
176 IMessageListener currentListener = this.messageListeners.get(type);
177 if (currentListener != null) {
178 logger.warn("{} is already listened by {}", type.toString(),
179 currentListener.toString());
181 this.messageListeners.put(type, listener);
182 logger.debug("{} is now listened by {}", type.toString(),
183 listener.toString());
187 public void removeMessageListener(OFType type, IMessageListener listener) {
188 IMessageListener currentListener = this.messageListeners.get(type);
189 if ((currentListener != null) && (currentListener == listener)) {
190 logger.debug("{} listener {} is Removed", type.toString(),
191 listener.toString());
192 this.messageListeners.remove(type);
197 public void addSwitchStateListener(ISwitchStateListener listener) {
198 if (this.switchStateListener != null) {
199 logger.warn("Switch events are already listened by {}",
200 this.switchStateListener.toString());
202 this.switchStateListener = listener;
203 logger.debug("Switch events are now listened by {}",
204 listener.toString());
208 public void removeSwitchStateListener(ISwitchStateListener listener) {
209 if ((this.switchStateListener != null)
210 && (this.switchStateListener == listener)) {
211 logger.debug("SwitchStateListener {} is Removed",
212 listener.toString());
213 this.switchStateListener = null;
217 public void handleNewConnection(Selector selector,
218 SelectionKey serverSelectionKey) {
219 ServerSocketChannel ssc = (ServerSocketChannel) serverSelectionKey
221 SocketChannel sc = null;
225 int i = this.switchInstanceNumber.addAndGet(1);
226 String instanceName = "SwitchHandler-" + i;
227 SwitchHandler switchHandler = new SwitchHandler(this, sc,
229 switchHandler.start();
230 if (sc.isConnected()) {
231 logger.info("Switch:{} is connected to the Controller",
232 sc.socket().getRemoteSocketAddress()
233 .toString().split("/")[1]);
236 } catch (IOException e) {
241 private void disconnectSwitch(ISwitch sw) {
242 if (((SwitchHandler) sw).isOperational()) {
243 Long sid = sw.getId();
244 if (this.switches.remove(sid, sw)) {
245 logger.warn("{} is Disconnected", sw.toString());
246 notifySwitchDeleted(sw);
249 ((SwitchHandler) sw).stop();
253 private void notifySwitchAdded(ISwitch sw) {
254 if (switchStateListener != null) {
255 switchStateListener.switchAdded(sw);
259 private void notifySwitchDeleted(ISwitch sw) {
260 if (switchStateListener != null) {
261 switchStateListener.switchDeleted(sw);
265 private synchronized void addSwitchEvent(SwitchEvent event) {
267 this.switchEvents.put(event);
268 } catch (InterruptedException e) {
269 logger.debug("SwitchEvent caught Interrupt Exception");
273 public void takeSwitchEventAdd(ISwitch sw) {
274 SwitchEvent ev = new SwitchEvent(
275 SwitchEvent.SwitchEventType.SWITCH_ADD, sw, null);
279 public void takeSwitchEventDelete(ISwitch sw) {
280 SwitchEvent ev = new SwitchEvent(
281 SwitchEvent.SwitchEventType.SWITCH_DELETE, sw, null);
285 public void takeSwitchEventError(ISwitch sw) {
286 SwitchEvent ev = new SwitchEvent(
287 SwitchEvent.SwitchEventType.SWITCH_ERROR, sw, null);
291 public void takeSwitchEventMsg(ISwitch sw, OFMessage msg) {
292 if (messageListeners.get(msg.getType()) != null) {
293 SwitchEvent ev = new SwitchEvent(
294 SwitchEvent.SwitchEventType.SWITCH_MESSAGE, sw, msg);
300 public Map<Long, ISwitch> getSwitches() {
301 return this.switches;
305 public ISwitch getSwitch(Long switchId) {
306 return this.switches.get(switchId);
309 public void _controllerShowSwitches(CommandInterpreter ci) {
310 Set<Long> sids = switches.keySet();
311 StringBuffer s = new StringBuffer();
312 int size = sids.size();
314 ci.print("switches: empty");
317 Iterator<Long> iter = sids.iterator();
318 s.append("Total: " + size + " switches\n");
319 while (iter.hasNext()) {
320 Long sid = iter.next();
321 Date date = switches.get(sid).getConnectedDate();
322 String switchInstanceName = ((SwitchHandler) switches.get(sid))
324 s.append(switchInstanceName + "/" + HexString.toHexString(sid)
325 + " connected since " + date.toString() + "\n");
327 ci.print(s.toString());
331 public void _controllerReset(CommandInterpreter ci) {
332 ci.print("...Disconnecting the communication to all switches...\n");
336 } catch (InterruptedException ie) {
338 ci.print("...start to accept connections from switches...\n");
343 public void _controllerShowConnConfig(CommandInterpreter ci) {
344 String str = System.getProperty("secureChannelEnabled");
345 if ((str != null) && (str.trim().equalsIgnoreCase("true"))) {
346 ci.print("The Controller and Switch should communicate through TLS connetion.\n");
348 String keyStoreFile = System.getProperty("controllerKeyStore");
349 String trustStoreFile = System.getProperty("controllerTrustStore");
350 if ((keyStoreFile == null) || keyStoreFile.trim().isEmpty()) {
351 ci.print("controllerKeyStore not specified in ./configuration/config.ini\n");
353 ci.print("controllerKeyStore=" + keyStoreFile + "\n");
355 if ((trustStoreFile == null) || trustStoreFile.trim().isEmpty()) {
356 ci.print("controllerTrustStore not specified in ./configuration/config.ini\n");
358 ci.print("controllerTrustStore=" + trustStoreFile + "\n");
361 ci.print("The Controller and Switch should communicate through TCP connetion.\n");
365 private void registerWithOSGIConsole() {
366 BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
368 bundleContext.registerService(CommandProvider.class.getName(), this,
373 public String getHelp() {
374 StringBuffer help = new StringBuffer();
375 help.append("---Open Flow Controller---\n");
376 help.append("\t controllerShowSwitches\n");
377 help.append("\t controllerReset\n");
378 help.append("\t controllerShowConnConfig\n");
379 return help.toString();