BUG-2315: Remove dependency to OFJava-impl
[openflowplugin.git] / test-scripts / openvswitch / mininet_tools.py
1 '''
2 Created on Jan 24, 2014
3
4 @author: vdemcak
5 '''
6
7 import logging
8 import mininet.net
9 from mininet.node import OVSKernelSwitch, RemoteController
10 import mininet.topo
11 import mininet.util
12 import re
13
14
15 class MininetTools():
16     """
17     Tool class provides static method for Open_vswitch
18     mininet out of box controls 
19     """
20     @staticmethod
21     def create_network(controller_ip, controller_port):
22         """Create topology and mininet network."""
23         topo = mininet.topo.Topo()
24
25         topo.addSwitch('s1')
26         topo.addHost('h1')
27         topo.addHost('h2')
28
29         topo.addLink('h1', 's1')
30         topo.addLink('h2', 's1')
31
32         switch=mininet.util.customConstructor(
33             {'ovsk':OVSKernelSwitch}, 'ovsk,protocols=OpenFlow13')
34
35         controller=mininet.util.customConstructor(
36             {'remote': RemoteController}, 'remote,ip=%s,port=%s' % (controller_ip,controller_port))
37
38
39         net = mininet.net.Mininet(topo=topo, switch=switch, controller=controller)
40
41         return net
42     
43     @staticmethod
44     def __mininet_parse_response(resp_str='', x_dict={}, ikwd={}):
45         for elm in re.split('\s', resp_str.strip()) :
46             elm_prop = re.split('=',elm,1)
47             a_key = (elm_prop[0]).strip()
48             if (ikwd.get(a_key, None) is None) :
49                 a_value = ''
50                 if (len(elm_prop) > 1):
51                     if len(elm_prop[1].split('=')) > 1 :
52                         new_dict={}
53                         MininetTools.__mininet_parse_response(elm_prop[1],new_dict,ikwd)
54                         a_value = new_dict
55                     else :
56                         a_value = elm_prop[1]
57                         a_value = a_value.strip() if isinstance(a_value,str) else (str(a_value)).strip()
58                 x_dict[a_key] = a_value
59
60     
61     @staticmethod
62     def get_dict_of_flows(net, ikwd={}):
63         """Get list of flows from network's first switch.
64
65         Return list of all flows on switch, sorted by duration (newest first)
66         One flow is a dictionary with all flow's attribute:value pairs. Matches
67         are stored under 'matches' key as another dictionary.
68         Example:
69
70         {
71             'actions': 'drop',
72             'cookie': '0xa,',
73             'duration': '3.434s,',
74             'hard_timeout': '12,',
75             'idle_timeout': '34,',
76             'matches': {
77                 'ip': None,
78                 'nw_dst': '10.0.0.0/24'
79             },
80             'n_bytes': '0,',
81             'n_packets': '0,',
82             'priority': '2',
83             'table': '1,'
84         }
85
86         """
87         log = logging.getLogger(__name__)
88
89         # dictionary for return
90         flows = {}
91         # flow command prompt output
92         output = MininetTools.get_flows_string(net)
93         # prepare cmd for parsing to dictionary
94         output = output.replace(',',' ') ;
95         output = output.replace('  ',' ')
96
97         # action has to be parsed in different way
98         if (len(re.split('actions=', output, 1)) > 0) :
99             action_str = re.split('actions=',output,1)[1]
100             action_dict = {}
101             MininetTools.__mininet_parse_response(action_str, action_dict, ikwd)
102             flows['actions'] = str(action_dict)
103         else :
104             flows['actions'] = ''
105
106         # remove actions from string (always last) and parse everything else
107         output= re.split('actions=',output,1)[0]
108         MininetTools.__mininet_parse_response(output, flows, ikwd)
109
110         return flows
111
112     @staticmethod
113     def get_flows_string(net=None):
114         """
115         Return flows from switch in string format 
116         same as by a call 'ovs-ofctl -O OpenFlow13 dump-flows sx'
117         """
118         if net is None:
119             return []
120
121         switch = net.switches[0]
122         output = switch.cmdPrint(
123         'ovs-ofctl -O OpenFlow13 dump-flows %s' % switch.name)
124
125         return output.splitlines()[1:]