ed0394d2096aed52f93232def9137c9f4d3daf5f
[controller.git] / opendaylight / sal / implementation / src / main / java / org / opendaylight / controller / sal / implementation / internal / ReadService.java
1
2 /*
3  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9
10 package org.opendaylight.controller.sal.implementation.internal;
11
12 import java.net.InetAddress;
13 import java.net.UnknownHostException;
14 import java.util.ArrayList;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Set;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.CopyOnWriteArraySet;
20
21 import org.eclipse.osgi.framework.console.CommandInterpreter;
22 import org.eclipse.osgi.framework.console.CommandProvider;
23 import org.opendaylight.controller.sal.action.Action;
24 import org.opendaylight.controller.sal.action.Controller;
25 import org.opendaylight.controller.sal.action.Flood;
26 import org.opendaylight.controller.sal.action.Output;
27 import org.opendaylight.controller.sal.action.PopVlan;
28 import org.opendaylight.controller.sal.core.ConstructionException;
29 import org.opendaylight.controller.sal.core.Node;
30 import org.opendaylight.controller.sal.core.Node.NodeIDType;
31 import org.opendaylight.controller.sal.core.NodeConnector;
32 import org.opendaylight.controller.sal.core.NodeTable;
33 import org.opendaylight.controller.sal.flowprogrammer.Flow;
34 import org.opendaylight.controller.sal.match.Match;
35 import org.opendaylight.controller.sal.match.MatchType;
36 import org.opendaylight.controller.sal.reader.FlowOnNode;
37 import org.opendaylight.controller.sal.reader.IPluginInReadService;
38 import org.opendaylight.controller.sal.reader.IPluginOutReadService;
39 import org.opendaylight.controller.sal.reader.IReadService;
40 import org.opendaylight.controller.sal.reader.IReadServiceListener;
41 import org.opendaylight.controller.sal.reader.NodeConnectorStatistics;
42 import org.opendaylight.controller.sal.reader.NodeDescription;
43 import org.opendaylight.controller.sal.reader.NodeTableStatistics;
44 import org.opendaylight.controller.sal.utils.EtherTypes;
45 import org.opendaylight.controller.sal.utils.GlobalConstants;
46 import org.opendaylight.controller.sal.utils.IPProtocols;
47 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
48 import org.opendaylight.controller.sal.utils.NodeCreator;
49 import org.opendaylight.controller.sal.utils.NodeTableCreator;
50 import org.osgi.framework.BundleContext;
51 import org.osgi.framework.FrameworkUtil;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * The SAL Read Service. Dispatches read requests to the proper SDN protocol
57  * plugin, and notifies any listeners on updates from any plugin readers
58  */
59 public class ReadService implements IReadService, CommandProvider, IPluginOutReadService {
60
61     protected static final Logger logger = LoggerFactory.getLogger(ReadService.class);
62     private ConcurrentHashMap<String, IPluginInReadService> pluginReader;
63     private Set<IReadServiceListener> readerListeners;
64
65     /**
66      * Function called by the dependency manager when all the required
67      * dependencies are satisfied
68      *
69      */
70     void init() {
71         pluginReader = new ConcurrentHashMap<String, IPluginInReadService>();
72         readerListeners = new CopyOnWriteArraySet<IReadServiceListener>();
73     }
74
75     /**
76      * Function called by the dependency manager when at least one
77      * dependency become unsatisfied or when the component is shutting
78      * down because for example bundle is being stopped.
79      *
80      */
81     void destroy() {
82         // In case of plugin disactivating make sure we clear the
83         // dependencies
84         this.pluginReader.clear();
85     }
86
87     /**
88      * Function called by dependency manager after "init ()" is called
89      * and after the services provided by the class are registered in
90      * the service registry
91      *
92      */
93     void start() {
94         registerWithOSGIConsole();
95     }
96
97     /**
98      * Function called by the dependency manager before the services
99      * exported by the component are unregistered, this will be
100      * followed by a "destroy ()" calls
101      *
102      */
103     void stop() {
104     }
105
106     // Set the reference to the plugin flow Reader service
107     public void setService(Map<?, ?> props, IPluginInReadService s) {
108         if (this.pluginReader == null) {
109             logger.error("pluginReader store null");
110             return;
111         }
112
113         logger.trace("Got a service set request {}", s);
114         String type = null;
115         for (Object e : props.entrySet()) {
116             Map.Entry<?, ?> entry = (Map.Entry<?, ?>) e;
117             logger.trace("Prop key:({}) value:({})", entry.getKey(),
118                     entry.getValue());
119         }
120
121         Object value = props.get(GlobalConstants.PROTOCOLPLUGINTYPE.toString());
122         if (value instanceof String) {
123             type = (String) value;
124         }
125         if (type == null) {
126             logger.error("Received a pluginReader without any "
127                     + "protocolPluginType provided");
128         } else {
129             this.pluginReader.put(type, s);
130             logger.debug("Stored the pluginReader for type: {}", type);
131         }
132     }
133
134     public void unsetService(Map<?, ?> props, IPluginInReadService s) {
135         if (this.pluginReader == null) {
136             logger.error("pluginReader store null");
137             return;
138         }
139
140         String type = null;
141         logger.debug("Received unsetpluginReader request");
142         for (Object e : props.entrySet()) {
143             Map.Entry<?, ?> entry = (Map.Entry<?, ?>) e;
144             logger.trace("Prop key:({}) value:({})", entry.getKey(),
145                     entry.getValue());
146         }
147
148         Object value = props.get(GlobalConstants.PROTOCOLPLUGINTYPE.toString());
149         if (value instanceof String) {
150             type = (String) value;
151         }
152         if (type == null) {
153             logger.error("Received a pluginReader without any "
154                     + "protocolPluginType provided");
155         } else if (this.pluginReader.get(type).equals(s)) {
156             this.pluginReader.remove(type);
157             logger.debug("Removed the pluginReader for type: {}", type);
158         }
159     }
160     public void setReaderListener(IReadServiceListener service) {
161         logger.trace("Got a listener set request {}", service);
162         this.readerListeners.add(service);
163     }
164
165     public void unsetReaderListener(IReadServiceListener service) {
166         logger.trace("Got a listener Unset request");
167         this.readerListeners.remove(service);
168     }
169
170     @Override
171     public FlowOnNode readFlow(Node node, Flow flow) {
172         if (pluginReader != null) {
173             if (this.pluginReader.get(node.getType()) != null) {
174                 return this.pluginReader.get(node.getType())
175                         .readFlow(node, flow, true);
176             }
177         }
178         logger.warn("Plugin {} unavailable", node.getType());
179         return null;
180     }
181
182     @Override
183     public FlowOnNode nonCachedReadFlow(Node node, Flow flow) {
184         if (pluginReader != null) {
185             if (this.pluginReader.get(node.getType()) != null) {
186                 return this.pluginReader.get(node.getType())
187                         .readFlow(node, flow, false);
188             }
189         }
190         logger.warn("Plugin {} unavailable", node.getType());
191         return null;
192     }
193
194     @Override
195     public List<FlowOnNode> readAllFlows(Node node) {
196         if (pluginReader != null) {
197             if (this.pluginReader.get(node.getType()) != null) {
198                 return this.pluginReader.get(node.getType())
199                         .readAllFlow(node, true);
200             }
201         }
202         logger.warn("Plugin {} unavailable", node.getType());
203         return null;
204     }
205
206     @Override
207     public List<FlowOnNode> nonCachedReadAllFlows(Node node) {
208         if (pluginReader != null) {
209             if (this.pluginReader.get(node.getType()) != null) {
210                 return this.pluginReader.get(node.getType())
211                         .readAllFlow(node, false);
212             }
213         }
214         logger.warn("Plugin {} unavailable", node.getType());
215         return null;
216     }
217
218     @Override
219     public NodeDescription readDescription(Node node) {
220         if (pluginReader != null) {
221             if (this.pluginReader.get(node.getType()) != null) {
222                 return this.pluginReader.get(node.getType())
223                         .readDescription(node, true);
224             }
225         }
226         logger.warn("Plugin {} unavailable", node.getType());
227         return null;
228     }
229
230     @Override
231     public NodeDescription nonCachedReadDescription(Node node) {
232         if (pluginReader != null) {
233             if (this.pluginReader.get(node.getType()) != null) {
234                 return this.pluginReader.get(node.getType())
235                         .readDescription(node, false);
236             }
237         }
238         logger.warn("Plugin {} unavailable", node.getType());
239         return null;
240     }
241
242     @Override
243     public NodeConnectorStatistics readNodeConnector(NodeConnector connector) {
244         Node node = connector.getNode();
245         if (pluginReader != null && node != null) {
246             if (this.pluginReader.get(node.getType()) != null) {
247                 return this.pluginReader.get(node.getType())
248                         .readNodeConnector(connector, true);
249             }
250         }
251         logger.warn("Plugin {} unavailable", node.getType());
252         return null;
253     }
254
255     @Override
256     public NodeConnectorStatistics nonCachedReadNodeConnector(
257             NodeConnector connector) {
258         Node node = connector.getNode();
259         if (pluginReader != null && node != null) {
260             if (this.pluginReader.get(node.getType()) != null) {
261                 return this.pluginReader.get(node.getType())
262                         .readNodeConnector(connector, false);
263             }
264         }
265         logger.warn("Plugin {} unavailable", node.getType());
266         return null;
267     }
268
269     @Override
270     public List<NodeConnectorStatistics> readNodeConnectors(Node node) {
271         if (pluginReader != null) {
272             if (this.pluginReader.get(node.getType()) != null) {
273                 return this.pluginReader.get(node.getType())
274                         .readAllNodeConnector(node, true);
275             }
276         }
277         logger.warn("Plugin {} unavailable", node.getType());
278         return null;
279     }
280
281     @Override
282     public List<NodeTableStatistics> readNodeTable(Node node) {
283         if (pluginReader != null) {
284             if (this.pluginReader.get(node.getType()) != null) {
285                 return this.pluginReader.get(node.getType())
286                         .readAllNodeTable(node, true);
287             }
288         }
289         logger.warn("Plugin {} unavailable", node.getType());
290         return null;
291     }
292
293
294     @Override
295     public NodeTableStatistics nonCachedReadNodeTable(NodeTable table) {
296         Node node = table.getNode();
297         if (pluginReader != null && node != null) {
298             if (this.pluginReader.get(node.getType()) != null) {
299                 return this.pluginReader.get(node.getType())
300                         .readNodeTable(table, false);
301             }
302         }
303         logger.warn("Plugin {} unavailable", node.getType());
304         return null;
305     }
306
307     @Override
308     public NodeTableStatistics readNodeTable(NodeTable table) {
309         Node node = table.getNode();
310         if (pluginReader != null && node != null) {
311             if (this.pluginReader.get(node.getType()) != null) {
312                 return this.pluginReader.get(node.getType())
313                         .readNodeTable(table, true);
314             }
315         }
316         logger.warn("Plugin {} unavailable", node.getType());
317         return null;
318     }
319
320     @Override
321     public List<NodeConnectorStatistics> nonCachedReadNodeConnectors(Node node) {
322         if (pluginReader != null) {
323             if (this.pluginReader.get(node.getType()) != null) {
324                 return this.pluginReader.get(node.getType())
325                         .readAllNodeConnector(node, false);
326             }
327         }
328         logger.warn("Plugin {} unavailable", node.getType());
329         return null;
330     }
331
332     @Override
333     public long getTransmitRate(NodeConnector connector) {
334         Node node = connector.getNode();
335         if (pluginReader != null && node != null) {
336             if (this.pluginReader.get(node.getType()) != null) {
337                 return this.pluginReader.get(node.getType())
338                         .getTransmitRate(connector);
339             }
340         }
341         logger.warn("Plugin {} unavailable", node.getType());
342         return 0;
343     }
344
345     @Override
346     public void nodeFlowStatisticsUpdated(Node node, List<FlowOnNode> flowStatsList) {
347         for (IReadServiceListener l : readerListeners){
348             l.nodeFlowStatisticsUpdated(node, flowStatsList);
349         }
350     }
351
352     @Override
353     public void nodeConnectorStatisticsUpdated(Node node, List<NodeConnectorStatistics> ncStatsList) {
354         for (IReadServiceListener l : readerListeners){
355             l.nodeConnectorStatisticsUpdated(node, ncStatsList);
356         }
357     }
358
359     @Override
360     public void nodeTableStatisticsUpdated(Node node, List<NodeTableStatistics> tableStatsList) {
361         for (IReadServiceListener l : readerListeners){
362             l.nodeTableStatisticsUpdated(node, tableStatsList);
363         }
364     }
365
366     @Override
367     public void descriptionStatisticsUpdated(Node node, NodeDescription nodeDescription) {
368         for (IReadServiceListener l : readerListeners){
369             l.descriptionStatisticsUpdated(node, nodeDescription);
370         }
371     }
372
373     // ---------------- OSGI TEST CODE ------------------------------//
374
375     private void registerWithOSGIConsole() {
376         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
377                 .getBundleContext();
378         bundleContext.registerService(CommandProvider.class.getName(), this,
379                 null);
380     }
381
382     @Override
383     public String getHelp() {
384         StringBuffer help = new StringBuffer();
385         help.append("---SAL Reader testing commands---\n");
386         help
387         .append("\t readflows <sid> <cached>  - Read all the (cached) flows from the openflow switch <sid>\n");
388         help
389         .append("\t readflow  <sid> <cached>  - Read the (cached) sample flow from the openflow switch <sid>\n");
390         help
391         .append("\t readdesc  <sid> <cached>  - Read the (cached) description from openflow switch <sid>\n");
392         help
393         .append("\t           cached=true/false. If false or not specified, the protocol plugin cached info\n");
394         help
395         .append("\t           is returned. If true, the info is directly retrieved from the switch\n");
396         return help.toString();
397     }
398
399     public void _readflows(CommandInterpreter ci) {
400         String nodeId = ci.nextArgument();
401         String cacheReq = ci.nextArgument();
402         boolean cached;
403         if (nodeId == null) {
404             ci.print("Node id not specified");
405             return;
406         }
407         cached = (cacheReq == null) ? true : cacheReq.equals("true");
408         Node node = null;
409         try {
410             node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId));
411         } catch (NumberFormatException e) {
412             logger.error("",e);
413         } catch (ConstructionException e) {
414             logger.error("",e);
415         }
416         List<FlowOnNode> list = (cached) ? this.readAllFlows(node) : this
417                 .nonCachedReadAllFlows(node);
418         if (list != null) {
419             ci.println(list.toString());
420         } else {
421             ci.println("null");
422         }
423     }
424
425     // Requests the hw view for the specific sample flow
426     public void _readflow(CommandInterpreter ci) throws UnknownHostException {
427         String nodeId = ci.nextArgument();
428         String cacheReq = ci.nextArgument();
429         boolean cached;
430         if (nodeId == null) {
431             ci.print("Node id not specified");
432             return;
433         }
434         cached = (cacheReq == null) ? true : cacheReq.equals("true");
435         Node node = null;
436         try {
437             node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId));
438         } catch (NumberFormatException e) {
439             logger.error("",e);
440         } catch (ConstructionException e) {
441             logger.error("",e);
442         }
443         Flow flow = getSampleFlow(node);
444         FlowOnNode flowOnNode = (cached) ? this.readFlow(node, flow) : this
445                 .nonCachedReadFlow(node, flow);
446         if (flowOnNode != null) {
447             ci.println(flowOnNode.toString());
448         } else {
449             ci.println("null");
450         }
451     }
452
453     public void _readports(CommandInterpreter ci) {
454         String nodeId = ci.nextArgument();
455         String cacheReq = ci.nextArgument();
456         boolean cached;
457         if (nodeId == null) {
458             ci.print("Node id not specified");
459             return;
460         }
461         cached = (cacheReq == null) ? true : cacheReq.equals("true");
462         Node node = null;
463         try {
464             node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId));
465         } catch (NumberFormatException e) {
466             logger.error("",e);
467         } catch (ConstructionException e) {
468             logger.error("",e);
469         }
470         List<NodeConnectorStatistics> list = (cached) ? this
471                 .readNodeConnectors(node) : this
472                 .nonCachedReadNodeConnectors(node);
473                 if (list != null) {
474                     ci.println(list.toString());
475                 } else {
476                     ci.println("null");
477                 }
478     }
479
480     public void _readport(CommandInterpreter ci) {
481         String nodeId = ci.nextArgument();
482         String portId = ci.nextArgument();
483         String cacheReq = ci.nextArgument();
484         boolean cached;
485         if (nodeId == null) {
486             ci.print("Node id not specified");
487             return;
488         }
489         if (portId == null) {
490             ci.print("Port id not specified");
491             return;
492         }
493         cached = (cacheReq == null) ? true : cacheReq.equals("true");
494         NodeConnector nodeConnector = null;
495         Node node = NodeCreator.createOFNode(Long.parseLong(nodeId));
496         nodeConnector = NodeConnectorCreator.createNodeConnector(Short
497                 .valueOf(portId), node);
498         NodeConnectorStatistics stats = (cached) ? this
499                 .readNodeConnector(nodeConnector) : this
500                 .nonCachedReadNodeConnector(nodeConnector);
501                 if (stats != null) {
502                     ci.println(stats.toString());
503                 } else {
504                     ci.println("null");
505                 }
506     }
507
508     public void _readtable(CommandInterpreter ci) {
509         String nodeId = ci.nextArgument();
510         String tableId = ci.nextArgument();
511         String cacheReq = ci.nextArgument();
512         boolean cached;
513         if (nodeId == null) {
514             ci.print("Node id not specified");
515             return;
516         }
517         if (tableId == null) {
518             ci.print("Table id not specified");
519             return;
520         }
521         cached = (cacheReq == null) ? true : cacheReq.equals("true");
522         NodeTable nodeTable = null;
523         Node node = NodeCreator.createOFNode(Long.parseLong(nodeId));
524         nodeTable = NodeTableCreator.createNodeTable(Byte
525                 .valueOf(tableId), node);
526         NodeTableStatistics stats = (cached) ? this
527                 .readNodeTable(nodeTable) : this
528                 .nonCachedReadNodeTable(nodeTable);
529                 if (stats != null) {
530                     ci.println(stats.toString());
531                 } else {
532                     ci.println("null");
533                 }
534     }
535
536     public void _readdescr(CommandInterpreter ci) {
537         String nodeId = ci.nextArgument();
538         String cacheReq = ci.nextArgument();
539         boolean cached;
540         if (nodeId == null) {
541             ci.print("Node id not specified");
542             return;
543         }
544         cached = (cacheReq == null) ? true : cacheReq.equals("true");
545
546         Node node = null;
547         try {
548             node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId));
549         } catch (NumberFormatException e) {
550             logger.error("",e);
551         } catch (ConstructionException e) {
552             logger.error("",e);
553         }
554         NodeDescription desc = (cached) ? this.readDescription(node) : this
555                 .nonCachedReadDescription(node);
556         if (desc != null) {
557             ci.println(desc.toString());
558         } else {
559             ci.println("null");
560         }
561     }
562
563     private Flow getSampleFlow(Node node) throws UnknownHostException {
564         NodeConnector port = NodeConnectorCreator.createOFNodeConnector(
565                 (short) 24, node);
566         NodeConnector oport = NodeConnectorCreator.createOFNodeConnector(
567                 (short) 30, node);
568         byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78,
569                 (byte) 0x9a, (byte) 0xbc };
570         byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d,
571                 (byte) 0x5e, (byte) 0x6f };
572         InetAddress srcIP = InetAddress.getByName("172.28.30.50");
573         InetAddress dstIP = InetAddress.getByName("171.71.9.52");
574         InetAddress ipMask = InetAddress.getByName("255.255.255.0");
575         InetAddress ipMask2 = InetAddress.getByName("255.0.0.0");
576         short ethertype = EtherTypes.IPv4.shortValue();
577         short vlan = (short) 27;
578         byte vlanPr = 3;
579         Byte tos = 4;
580         byte proto = IPProtocols.TCP.byteValue();
581         short src = (short) 55000;
582         short dst = 80;
583
584         /*
585          * Create a SAL Flow aFlow
586          */
587         Match match = new Match();
588         match.setField(MatchType.IN_PORT, port);
589         match.setField(MatchType.DL_SRC, srcMac);
590         match.setField(MatchType.DL_DST, dstMac);
591         match.setField(MatchType.DL_TYPE, ethertype);
592         match.setField(MatchType.DL_VLAN, vlan);
593         match.setField(MatchType.DL_VLAN_PR, vlanPr);
594         match.setField(MatchType.NW_SRC, srcIP, ipMask);
595         match.setField(MatchType.NW_DST, dstIP, ipMask2);
596         match.setField(MatchType.NW_TOS, tos);
597         match.setField(MatchType.NW_PROTO, proto);
598         match.setField(MatchType.TP_SRC, src);
599         match.setField(MatchType.TP_DST, dst);
600
601         List<Action> actions = new ArrayList<Action>();
602         actions.add(new Output(oport));
603         actions.add(new PopVlan());
604         actions.add(new Flood());
605         actions.add(new Controller());
606         return new Flow(match, actions);
607     }
608 }