Fix Make, Make clean and when the src directories are cloned
[vswitchperf.git] / src / ovs / ofctl.py
1 # Copyright 2015 Intel Corporation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #   http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 """Wrapper for an OVS bridge for convenient use of ``ovs-vsctl`` and
16 ``ovs-ofctl`` on it.
17
18 Much of this code is based on ``ovs-lib.py`` from Open Stack:
19
20 https://github.com/openstack/neutron/blob/6eac1dc99124ca024d6a69b3abfa3bc69c735667/neutron/agent/linux/ovs_lib.py
21 """
22
23 import os
24 import logging
25 import string
26
27 from tools import tasks
28 from conf import settings
29
30 _OVS_VSCTL_BIN = os.path.join(settings.getValue('OVS_DIR'), 'utilities',
31                               'ovs-vsctl')
32 _OVS_OFCTL_BIN = os.path.join(settings.getValue('OVS_DIR'), 'utilities',
33                               'ovs-ofctl')
34
35 _OVS_VAR_DIR = '/usr/local/var/run/openvswitch/'
36
37 _OVS_BRIDGE_NAME = settings.getValue('VSWITCH_BRIDGE_NAME')
38
39 class OFBase(object):
40     """Add/remove/show datapaths using ``ovs-ofctl``.
41     """
42     def __init__(self, timeout=10):
43         """Initialise logger.
44
45         :param timeout: Timeout to be used for each command
46
47         :returns: None
48         """
49         self.logger = logging.getLogger(__name__)
50         self.timeout = timeout
51
52     # helpers
53
54     def run_vsctl(self, args, check_error=False):
55         """Run ``ovs-vsctl`` with supplied arguments.
56
57         :param args: Arguments to pass to ``ovs-vsctl``
58         :param check_error: Throw exception on error
59
60         :return: None
61         """
62         cmd = ['sudo', _OVS_VSCTL_BIN, '--timeout', str(self.timeout)] + args
63         return tasks.run_task(
64             cmd, self.logger, 'Running ovs-vsctl...', check_error)
65
66     # datapath management
67
68     def add_br(self, br_name=_OVS_BRIDGE_NAME, params=None):
69         """Add datapath.
70
71         :param br_name: Name of bridge
72
73         :return: Instance of :class OFBridge:
74         """
75         if params is None:
76             params = []
77
78         self.logger.debug('add bridge')
79         self.run_vsctl(['add-br', br_name]+params)
80
81         return OFBridge(br_name, self.timeout)
82
83     def del_br(self, br_name=_OVS_BRIDGE_NAME):
84         """Delete datapath.
85
86         :param br_name: Name of bridge
87
88         :return: None
89         """
90         self.logger.debug('delete bridge')
91         self.run_vsctl(['del-br', br_name])
92
93
94 class OFBridge(OFBase):
95     """Control a bridge instance using ``ovs-vsctl`` and ``ovs-ofctl``.
96     """
97     def __init__(self, br_name=_OVS_BRIDGE_NAME, timeout=10):
98         """Initialise bridge.
99
100         :param br_name: Bridge name
101         :param timeout: Timeout to be used for each command
102
103         :returns: None
104         """
105         super(OFBridge, self).__init__(timeout)
106         self.br_name = br_name
107         self._ports = {}
108
109     # context manager
110
111     def __enter__(self):
112         """Create datapath
113
114         :returns: self
115         """
116         return self
117
118     def __exit__(self, type_, value, traceback):
119         """Remove datapath.
120         """
121         if not traceback:
122             self.destroy()
123
124     # helpers
125
126     def run_ofctl(self, args, check_error=False):
127         """Run ``ovs-ofctl`` with supplied arguments.
128
129         :param args: Arguments to pass to ``ovs-ofctl``
130         :param check_error: Throw exception on error
131
132         :return: None
133         """
134         cmd = ['sudo', _OVS_OFCTL_BIN, '-O', 'OpenFlow13', '--timeout',
135                str(self.timeout)] + args
136         return tasks.run_task(
137             cmd, self.logger, 'Running ovs-ofctl...', check_error)
138
139     def create(self, params=None):
140         """Create bridge.
141         """
142         if params is None:
143             params = []
144
145         self.logger.debug('create bridge')
146         self.add_br(self.br_name, params=params)
147
148     def destroy(self):
149         """Destroy bridge.
150         """
151         self.logger.debug('destroy bridge')
152         self.del_br(self.br_name)
153
154     def reset(self):
155         """Reset bridge.
156         """
157         self.logger.debug('reset bridge')
158         self.destroy()
159         self.create()
160
161     # port management
162
163     def add_port(self, port_name, params):
164         """Add port to bridge.
165
166         :param port_name: Name of port
167         :param params: Additional list of parameters to add-port
168
169         :return: OpenFlow port number for the port
170         """
171         self.logger.debug('add port')
172         self.run_vsctl(['add-port', self.br_name, port_name]+params)
173
174         # This is how port number allocation works currently
175         # This possibly will not work correctly if there are port deletions
176         # in between
177         of_port = len(self._ports) + 1
178         self._ports[port_name] = (of_port, params)
179         return of_port
180
181     def del_port(self, port_name):
182         """Remove port from bridge.
183
184         :param port_name: Name of port
185
186         :return: None
187         """
188         self.logger.debug('delete port')
189         self.run_vsctl(['del-port', self.br_name, port_name])
190         self._ports.pop(port_name)
191
192     def set_db_attribute(self, table_name, record, column, value):
193         """Set database attribute.
194
195         :param table_name: Name of table
196         :param record: Name of record
197         :param column: Name of column
198         :param value: Value to set
199
200         :return: None
201         """
202         self.logger.debug('set attribute')
203         self.run_vsctl(['set', table_name, record, '%s=%s' % (column, value)])
204
205     def get_ports(self):
206         """Get the ports of this bridge
207
208         Structure of the returned ports dictionary is
209         'portname': (openflow_port_number, extra_parameters)
210
211         Example:
212         ports = {
213             'dpdkport0':
214                 (1, ['--', 'set', 'Interface', 'dpdkport0', 'type=dpdk']),
215             'dpdkvhostport0':
216                 (2, ['--', 'set', 'Interface', 'dpdkvhostport0',
217                      'type=dpdkvhost'])
218         }
219
220         :return: Dictionary of ports
221         """
222         return self._ports
223
224     def clear_db_attribute(self, table_name, record, column):
225         """Clear database attribute.
226
227         :param table_name: Name of table
228         :param record: Name of record
229         :param column: Name of column
230
231         :return: None
232         """
233         self.logger.debug('clear attribute')
234         self.run_vsctl(['clear', table_name, record, column])
235
236     # flow mangement
237
238     def add_flow(self, flow):
239         """Add flow to bridge.
240
241         :param flow: Flow description as a dictionary
242         For flow dictionary structure, see function flow_key
243
244         :return: None
245         """
246         if not flow.get('actions'):
247             self.logger.error('add flow requires actions')
248             return
249
250         self.logger.debug('add flow')
251         _flow_key = flow_key(flow)
252         self.logger.debug('key : %s', _flow_key)
253         self.run_ofctl(['add-flow', self.br_name, _flow_key])
254
255     def del_flow(self, flow):
256         """Delete flow from bridge.
257
258         :param flow: Flow description as a dictionary
259         For flow dictionary structure, see function flow_key
260         flow=None will delete all flows
261
262         :return: None
263         """
264         self.logger.debug('delete flow')
265         _flow_key = flow_key(flow)
266         self.logger.debug('key : %s', _flow_key)
267         self.run_ofctl(['del-flows', self.br_name, _flow_key])
268
269     def del_flows(self):
270         """Delete all flows from bridge.
271         """
272         self.logger.debug('delete flows')
273         self.run_ofctl(['del-flows', self.br_name])
274
275     def dump_flows(self):
276         """Dump all flows from bridge.
277         """
278         self.logger.debug('dump flows')
279         self.run_ofctl(['dump-flows', self.br_name])
280
281 #
282 # helper functions
283 #
284
285 def flow_key(flow):
286     """Model a flow key string for ``ovs-ofctl``.
287
288     Syntax taken from ``ovs-ofctl`` manpages:
289         http://openvswitch.org/cgi-bin/ovsman.cgi?page=utilities%2Fovs-ofctl.8
290
291     Example flow dictionary:
292     flow = {
293         'in_port': '1',
294         'idle_timeout': '0',
295         'actions': ['output:3']
296     }
297
298     :param flow: Flow description as a dictionary
299
300     :return: String
301     :rtype: str
302     """
303     _flow_add_key = string.Template('${fields},action=${actions}')
304     _flow_del_key = string.Template('${fields}')
305
306     field_params = []
307
308     user_params = (x for x in list(flow.items()) if x[0] != 'actions')
309     for (key, default) in user_params:
310         field_params.append('%(field)s=%(value)s' %
311                             {'field': key, 'value': default})
312
313     field_params = ','.join(field_params)
314
315     _flow_key_param = {
316         'fields': field_params,
317     }
318
319     # no actions == delete key
320     if 'actions' in flow:
321         _flow_key_param['actions'] = ','.join(flow['actions'])
322
323         flow_str = _flow_add_key.substitute(_flow_key_param)
324     else:
325         flow_str = _flow_del_key.substitute(_flow_key_param)
326
327     return flow_str