- Plugin sends Barrier msg every 100 async msgs (configurable thru config.ini: of...
[controller.git] / opendaylight / sal / implementation / src / main / java / org / opendaylight / controller / sal / implementation / internal / FlowProgrammerService.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.sal.implementation.internal;
10
11 import java.util.Map;
12 import java.util.concurrent.ConcurrentHashMap;
13 import java.util.concurrent.atomic.AtomicLong;
14 import java.net.InetAddress;
15 import java.net.UnknownHostException;
16 import java.util.ArrayList;
17 import java.util.HashSet;
18 import java.util.List;
19 import java.util.Set;
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.action.SetNwDst;
29 import org.opendaylight.controller.sal.core.ConstructionException;
30 import org.opendaylight.controller.sal.core.Node;
31 import org.opendaylight.controller.sal.core.NodeConnector;
32 import org.opendaylight.controller.sal.core.Node.NodeIDType;
33 import org.opendaylight.controller.sal.flowprogrammer.Flow;
34 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerListener;
35 import org.opendaylight.controller.sal.flowprogrammer.IFlowProgrammerService;
36 import org.opendaylight.controller.sal.flowprogrammer.IPluginInFlowProgrammerService;
37 import org.opendaylight.controller.sal.flowprogrammer.IPluginOutFlowProgrammerService;
38 import org.opendaylight.controller.sal.match.Match;
39 import org.opendaylight.controller.sal.match.MatchType;
40 import org.opendaylight.controller.sal.utils.StatusCode;
41 import org.opendaylight.controller.sal.utils.EtherTypes;
42 import org.opendaylight.controller.sal.utils.IPProtocols;
43 import org.opendaylight.controller.sal.utils.NodeConnectorCreator;
44 import org.opendaylight.controller.sal.utils.Status;
45 import org.osgi.framework.BundleContext;
46 import org.osgi.framework.FrameworkUtil;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 /**
51  * The SAL Flow Programmer Service. It dispatches the flow programming requests
52  * to the proper SDN protocol plugin and it notifies about asynchronous messages
53  * received from the network node related to flow programming.
54  */
55 public class FlowProgrammerService implements IFlowProgrammerService,
56         IPluginOutFlowProgrammerService, CommandProvider {
57
58     protected static final Logger logger = LoggerFactory
59             .getLogger(FlowProgrammerService.class);
60     private ConcurrentHashMap<String, IPluginInFlowProgrammerService> pluginFlowProgrammer;
61     private Set<IFlowProgrammerListener> listener;
62     private AtomicLong seq;
63
64     public FlowProgrammerService() {
65         pluginFlowProgrammer = new ConcurrentHashMap<String, IPluginInFlowProgrammerService>();
66         listener = new HashSet<IFlowProgrammerListener>();
67         seq = new AtomicLong();
68         /*
69          * This Request ID generator starts with 1. Each aysnc message is
70          * associated with an unique Request ID (!= 0).
71          */
72         seq.lazySet(1);
73     }
74
75     /**
76      * Function called by the dependency manager when all the required
77      * dependencies are satisfied
78      * 
79      */
80     void init() {
81         logger.debug("INIT called!");
82     }
83
84     /**
85      * Function called by the dependency manager when at least one dependency
86      * become unsatisfied or when the component is shutting down because for
87      * example bundle is being stopped.
88      * 
89      */
90     void destroy() {
91         // Clear previous registration to avoid they are left hanging
92         this.pluginFlowProgrammer.clear();
93         logger.debug("DESTROY called!");
94     }
95
96     /**
97      * Function called by dependency manager after "init ()" is called and after
98      * the services provided by the class are registered in the service registry
99      * 
100      */
101     void start() {
102         logger.debug("START called!");
103         // OSGI console
104         registerWithOSGIConsole();
105     }
106
107     /**
108      * Function called by the dependency manager before the services exported by
109      * the component are unregistered, this will be followed by a "destroy ()"
110      * calls
111      * 
112      */
113     void stop() {
114         logger.debug("STOP called!");
115     }
116
117     // Set the reference to the plugin flow programmer
118     public void setService(Map props, IPluginInFlowProgrammerService s) {
119         if (this.pluginFlowProgrammer == null) {
120             logger.error("pluginFlowProgrammer store null");
121             return;
122         }
123
124         logger.trace("Got a service set request {}", s);
125         String type = null;
126         for (Object e : props.entrySet()) {
127             Map.Entry entry = (Map.Entry) e;
128             logger.trace("Prop key:({}) value:({})", entry.getKey(),
129                     entry.getValue());
130         }
131
132         Object value = props.get("protocolPluginType");
133         if (value instanceof String) {
134             type = (String) value;
135         }
136         if (type == null) {
137             logger.error("Received a pluginFlowProgrammer without any "
138                     + "protocolPluginType provided");
139         } else {
140             this.pluginFlowProgrammer.put(type, s);
141             logger.debug("Stored the pluginFlowProgrammer for type: {}", type);
142         }
143     }
144
145     public void unsetService(Map props, IPluginInFlowProgrammerService s) {
146         if (this.pluginFlowProgrammer == null) {
147             logger.error("pluginFlowProgrammer store null");
148             return;
149         }
150
151         String type = null;
152         logger.debug("Received unsetpluginFlowProgrammer request");
153         for (Object e : props.entrySet()) {
154             Map.Entry entry = (Map.Entry) e;
155             logger.trace("Prop key:({}) value:({})", entry.getKey(),
156                     entry.getValue());
157         }
158
159         Object value = props.get("protocoloPluginType");
160         if (value instanceof String) {
161             type = (String) value;
162         }
163         if (type == null) {
164             logger.error("Received a pluginFlowProgrammer without any "
165                     + "protocolPluginType provided");
166         } else if (this.pluginFlowProgrammer.get(type).equals(s)) {
167             this.pluginFlowProgrammer.remove(type);
168             logger.debug("Removed the pluginFlowProgrammer for type: {}", type);
169         }
170     }
171
172     public void setListener(IFlowProgrammerListener s) {
173         this.listener.add(s);
174     }
175
176     public void unsetListener(IFlowProgrammerListener s) {
177         this.listener.remove(s);
178     }
179
180     @Override
181     public Status addFlow(Node node, Flow flow) {
182         if (pluginFlowProgrammer != null) {
183             if (this.pluginFlowProgrammer.get(node.getType()) != null) {
184                 return this.pluginFlowProgrammer.get(node.getType()).addFlow(
185                         node, flow);
186             }
187         }
188         return new Status(StatusCode.NOSERVICE, "Plugin unuvailable");
189     }
190
191     @Override
192     public Status removeFlow(Node node, Flow flow) {
193         if (pluginFlowProgrammer != null) {
194             if (this.pluginFlowProgrammer.get(node.getType()) != null) {
195                 return this.pluginFlowProgrammer.get(node.getType())
196                         .removeFlow(node, flow);
197             }
198         }
199         return new Status(StatusCode.NOSERVICE, "Plugin unuvailable");
200     }
201
202     @Override
203     public Status removeAllFlows(Node node) {
204         if (pluginFlowProgrammer != null) {
205             if (this.pluginFlowProgrammer.get(node.getType()) != null) {
206                 return this.pluginFlowProgrammer.get(node.getType())
207                         .removeAllFlows(node);
208             }
209         }
210         return new Status(StatusCode.NOSERVICE, "Plugin unuvailable");
211     }
212
213     @Override
214     public Status modifyFlow(Node node, Flow oldFlow, Flow newFlow) {
215         if (pluginFlowProgrammer != null) {
216             if (this.pluginFlowProgrammer.get(node.getType()) != null) {
217                 return this.pluginFlowProgrammer.get(node.getType())
218                         .modifyFlow(node, oldFlow, newFlow);
219             }
220         }
221         return new Status(StatusCode.NOSERVICE, "Plugin unuvailable");
222     }
223
224     @Override
225     public Status addFlowAsync(Node node, Flow flow) {
226         if (pluginFlowProgrammer != null) {
227             if (this.pluginFlowProgrammer.get(node.getType()) != null) {
228                 return this.pluginFlowProgrammer.get(node.getType()).addFlowAsync(
229                         node, flow, getNextRid());
230             }
231         }
232         return new Status(StatusCode.NOSERVICE, "Plugin unuvailable");
233     }
234
235     @Override
236     public Status removeFlowAsync(Node node, Flow flow) {
237         if (pluginFlowProgrammer != null) {
238             if (this.pluginFlowProgrammer.get(node.getType()) != null) {
239                 return this.pluginFlowProgrammer.get(node.getType())
240                         .removeFlowAsync(node, flow, getNextRid());
241             }
242         }
243         return new Status(StatusCode.NOSERVICE, "Plugin unuvailable");
244     }
245
246     @Override
247     public Status modifyFlowAsync(Node node, Flow oldFlow, Flow newFlow) {
248         if (pluginFlowProgrammer != null) {
249             if (this.pluginFlowProgrammer.get(node.getType()) != null) {
250                 return this.pluginFlowProgrammer.get(node.getType())
251                         .modifyFlowAsync(node, oldFlow, newFlow, getNextRid());
252             }
253         }
254         return new Status(StatusCode.NOSERVICE, "Plugin unuvailable");
255     }
256
257     @Override
258     public void flowRemoved(Node node, Flow flow) {
259         for (IFlowProgrammerListener l : listener) {
260             l.flowRemoved(node, flow);
261         }
262     }
263
264     // ---------------- OSGI TEST CODE ------------------------------//
265
266     private void registerWithOSGIConsole() {
267         BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass())
268                 .getBundleContext();
269         bundleContext.registerService(CommandProvider.class.getName(), this,
270                 null);
271     }
272
273     @Override
274     public String getHelp() {
275         StringBuffer help = new StringBuffer();
276         help.append("---SAL Flow Programmer testing commands---\n");
277         help.append("\t addflow <sid> - Add a sample flow to the openflow switch <sid>\n");
278         help.append("\t removeflow <sid> - Remove the sample flow from the openflow switch <sid>\n");
279         return help.toString();
280     }
281
282     public void _addflow(CommandInterpreter ci) throws UnknownHostException {
283         Node node = null;
284         String nodeId = ci.nextArgument();
285         if (nodeId == null) {
286             ci.print("Node id not specified");
287             return;
288         }
289         try {
290             node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId));
291         } catch (NumberFormatException e) {
292             logger.error("",e);
293         } catch (ConstructionException e) {
294             logger.error("",e);
295         }
296         ci.println(this.addFlow(node, getSampleFlow(node)));
297     }
298     
299     public void _modifyflow(CommandInterpreter ci) throws UnknownHostException {
300         Node node = null;
301         String nodeId = ci.nextArgument();
302         if (nodeId == null) {
303             ci.print("Node id not specified");
304             return;
305         }
306         try {
307             node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId));
308         } catch (NumberFormatException e) {
309             logger.error("",e);
310         } catch (ConstructionException e) {
311             logger.error("",e);
312         }
313         Flow flowA = getSampleFlow(node);
314         Flow flowB = getSampleFlow(node);
315         Match matchB = flowB.getMatch();
316         matchB.setField(MatchType.NW_DST,
317                 InetAddress.getByName("190.190.190.190"));
318         flowB.setMatch(matchB);
319         ci.println(this.modifyFlow(node, flowA, flowB));
320     }
321
322     public void _removeflow(CommandInterpreter ci) throws UnknownHostException {
323         Node node = null;
324         String nodeId = ci.nextArgument();
325         if (nodeId == null) {
326             ci.print("Node id not specified");
327             return;
328         }
329         try {
330             node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId));
331         } catch (NumberFormatException e) {
332             logger.error("",e);
333         } catch (ConstructionException e) {
334             logger.error("",e);
335         }
336         ci.println(this.removeFlow(node, getSampleFlow(node)));
337     }
338
339     public void _addflowv6(CommandInterpreter ci) throws UnknownHostException {
340         Node node = null;
341         String nodeId = ci.nextArgument();
342         if (nodeId == null) {
343             ci.print("Node id not specified");
344             return;
345         }
346         try {
347             node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId));
348         } catch (NumberFormatException e) {
349             logger.error("",e);
350         } catch (ConstructionException e) {
351             logger.error("",e);
352         }
353         ci.println(this.addFlow(node, getSampleFlowV6(node)));
354     }
355
356     public void _removeflowv6(CommandInterpreter ci)
357             throws UnknownHostException {
358         Node node = null;
359         String nodeId = ci.nextArgument();
360         if (nodeId == null) {
361             ci.print("Node id not specified");
362             return;
363         }
364         try {
365             node = new Node(NodeIDType.OPENFLOW, Long.valueOf(nodeId));
366         } catch (NumberFormatException e) {
367             logger.error("",e);
368         } catch (ConstructionException e) {
369             logger.error("",e);
370         }
371         ci.println(this.removeFlow(node, getSampleFlowV6(node)));
372     }
373
374     private Flow getSampleFlow(Node node) throws UnknownHostException {
375         NodeConnector port = NodeConnectorCreator.createOFNodeConnector(
376                 (short) 24, node);
377         NodeConnector oport = NodeConnectorCreator.createOFNodeConnector(
378                 (short) 30, node);
379         byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78,
380                 (byte) 0x9a, (byte) 0xbc };
381         byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d,
382                 (byte) 0x5e, (byte) 0x6f };
383         InetAddress srcIP = InetAddress.getByName("172.28.30.50");
384         InetAddress dstIP = InetAddress.getByName("171.71.9.52");
385         InetAddress newIP = InetAddress.getByName("200.200.100.1");
386         InetAddress ipMask = InetAddress.getByName("255.255.255.0");
387         InetAddress ipMask2 = InetAddress.getByName("255.240.0.0");
388         short ethertype = EtherTypes.IPv4.shortValue();
389         short vlan = (short) 27;
390         byte vlanPr = 3;
391         Byte tos = 4;
392         byte proto = IPProtocols.TCP.byteValue();
393         short src = (short) 55000;
394         short dst = 80;
395
396         /*
397          * Create a SAL Flow aFlow
398          */
399         Match match = new Match();
400         match.setField(MatchType.IN_PORT, port);
401         match.setField(MatchType.DL_SRC, srcMac);
402         match.setField(MatchType.DL_DST, dstMac);
403         match.setField(MatchType.DL_TYPE, ethertype);
404         match.setField(MatchType.DL_VLAN, vlan);
405         match.setField(MatchType.DL_VLAN_PR, vlanPr);
406         match.setField(MatchType.NW_SRC, srcIP, ipMask);
407         match.setField(MatchType.NW_DST, dstIP, ipMask2);
408         match.setField(MatchType.NW_TOS, tos);
409         match.setField(MatchType.NW_PROTO, proto);
410         match.setField(MatchType.TP_SRC, src);
411         match.setField(MatchType.TP_DST, dst);
412
413         List<Action> actions = new ArrayList<Action>();
414         actions.add(new SetNwDst(newIP));
415         actions.add(new Output(oport));
416         actions.add(new PopVlan());
417         actions.add(new Flood());
418         actions.add(new Controller());
419
420         Flow flow = new Flow(match, actions);
421         flow.setPriority((short) 100);
422         flow.setHardTimeout((short) 360);
423
424         return flow;
425     }
426
427     private Flow getSampleFlowV6(Node node) throws UnknownHostException {
428         NodeConnector port = NodeConnectorCreator.createOFNodeConnector(
429                 (short) 24, node);
430         NodeConnector oport = NodeConnectorCreator.createOFNodeConnector(
431                 (short) 30, node);
432         byte srcMac[] = { (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78,
433                 (byte) 0x9a, (byte) 0xbc };
434         byte dstMac[] = { (byte) 0x1a, (byte) 0x2b, (byte) 0x3c, (byte) 0x4d,
435                 (byte) 0x5e, (byte) 0x6f };
436         InetAddress srcIP = InetAddress
437                 .getByName("2001:420:281:1004:407a:57f4:4d15:c355");
438         InetAddress dstIP = InetAddress
439                 .getByName("2001:420:281:1004:e123:e688:d655:a1b0");
440         InetAddress ipMask = null; // InetAddress.getByName("ffff:ffff:ffff:ffff:0:0:0:0");
441                                    // V6Match implementation assumes no mask is
442                                    // specified
443         InetAddress ipMask2 = null; // InetAddress.getByName("ffff:ffff:ffff:ffff:ffff:ffff:ffff:0");
444         short ethertype = EtherTypes.IPv6.shortValue();
445         short vlan = (short) 27;
446         byte vlanPr = (byte) 3;
447         Byte tos = 4;
448         byte proto = IPProtocols.UDP.byteValue();
449         short src = (short) 5500;
450         // short dst = 80;
451
452         /*
453          * Create a SAL Flow aFlow
454          */
455         Match match = new Match();
456         match.setField(MatchType.IN_PORT, port);
457         match.setField(MatchType.DL_SRC, srcMac);
458         match.setField(MatchType.DL_DST, dstMac);
459         match.setField(MatchType.DL_TYPE, ethertype);
460         match.setField(MatchType.DL_VLAN, vlan);
461         match.setField(MatchType.DL_VLAN_PR, vlanPr); // V6Match does not handle
462                                                       // this properly...
463         match.setField(MatchType.NW_SRC, srcIP, ipMask);
464         match.setField(MatchType.NW_DST, dstIP, ipMask2);
465         match.setField(MatchType.NW_TOS, tos);
466         match.setField(MatchType.NW_PROTO, proto);
467         match.setField(MatchType.TP_SRC, src); // V6Match does not handle this
468                                                // properly...
469         // match.setField(MatchType.TP_DST, dst); V6Match does not handle this
470         // properly...
471
472         List<Action> actions = new ArrayList<Action>();
473         actions.add(new Output(oport));
474         actions.add(new PopVlan());
475         actions.add(new Flood());
476
477         Flow flow = new Flow(match, actions);
478         flow.setPriority((short) 300);
479         flow.setHardTimeout((short) 240);
480
481         return flow;
482     }
483
484     /*
485      * This Request ID generator starts with 1. Each aysnc message is
486      * associated with an unique Request ID (!= 0).
487      */
488     private long getNextRid() {
489         return seq.getAndIncrement();
490     }
491
492     @Override
493     public Status sendBarrierMessage(Node node) {
494         if (this.pluginFlowProgrammer != null) {
495             if (this.pluginFlowProgrammer.get(node.getType()) != null) {
496                 return this.pluginFlowProgrammer.get(node.getType())
497                         .sendBarrierMessage(node);
498             }
499         }
500         return new Status(StatusCode.NOSERVICE, "Plugin unuvailable");
501     }
502 }