Merge "opnfvresultdb: Add mapping for VPP TCs"
[vswitchperf.git] / src / ovs / ofctl.py
1 # Copyright 2015-2017 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 import logging
23 import string
24 import re
25 import netaddr
26
27 from tools import tasks
28 from conf import settings
29
30 _OVS_BRIDGE_NAME = settings.getValue('VSWITCH_BRIDGE_NAME')
31 _OVS_CMD_TIMEOUT = settings.getValue('OVS_CMD_TIMEOUT')
32
33 _CACHE_FILE_NAME = '/tmp/vsperf_flows_cache'
34
35 # only simple regex is used; validity of IPv4 is not checked by regex
36 _IPV4_REGEX = r"([0-9]{1,3}(\.[0-9]{1,3}){3}(\/[0-9]{1,2})?)"
37
38 class OFBase(object):
39     """Add/remove/show datapaths using ``ovs-ofctl``.
40     """
41     def __init__(self, timeout=_OVS_CMD_TIMEOUT):
42         """Initialise logger.
43
44         :param timeout: Timeout to be used for each command
45
46         :returns: None
47         """
48         self.logger = logging.getLogger(__name__)
49         self.timeout = timeout
50
51     # helpers
52
53     def run_vsctl(self, args, check_error=False):
54         """Run ``ovs-vsctl`` with supplied arguments.
55
56         In case that timeout is set to -1, then ovs-vsctl
57         will be called with --no-wait option.
58
59         :param args: Arguments to pass to ``ovs-vsctl``
60         :param check_error: Throw exception on error
61
62         :return: None
63         """
64         if self.timeout == -1:
65             cmd = ['sudo', settings.getValue('TOOLS')['ovs-vsctl'], '--no-wait'] + args
66         else:
67             cmd = ['sudo', settings.getValue('TOOLS')['ovs-vsctl'], '--timeout', str(self.timeout)] + args
68         return tasks.run_task(
69             cmd, self.logger, 'Running ovs-vsctl...', check_error)
70
71
72     def run_appctl(self, args, check_error=False):
73         """Run ``ovs-appctl`` with supplied arguments.
74
75         :param args: Arguments to pass to ``ovs-appctl``
76         :param check_error: Throw exception on error
77
78         :return: None
79         """
80         cmd = ['sudo', settings.getValue('TOOLS')['ovs-appctl'],
81                '--timeout',
82                str(self.timeout)] + args
83         return tasks.run_task(
84             cmd, self.logger, 'Running ovs-appctl...', check_error)
85
86
87     # datapath management
88
89     def add_br(self, br_name=_OVS_BRIDGE_NAME, params=None):
90         """Add datapath.
91
92         :param br_name: Name of bridge
93
94         :return: Instance of :class OFBridge:
95         """
96         if params is None:
97             params = []
98
99         self.logger.debug('add bridge')
100         self.run_vsctl(['add-br', br_name]+params)
101
102         return OFBridge(br_name, self.timeout)
103
104     def del_br(self, br_name=_OVS_BRIDGE_NAME):
105         """Delete datapath.
106
107         :param br_name: Name of bridge
108
109         :return: None
110         """
111         self.logger.debug('delete bridge')
112         self.run_vsctl(['del-br', br_name])
113
114     # Route and ARP functions
115
116     def add_route(self, network, destination):
117         """Add route to tunneling routing table.
118
119         :param network: Network
120         :param destination: Gateway
121
122         :return: None
123         """
124         self.logger.debug('add ovs/route')
125         self.run_appctl(['ovs/route/add', network, destination])
126
127
128     def set_tunnel_arp(self, ip_addr, mac_addr, br_name=_OVS_BRIDGE_NAME):
129         """Add OVS arp entry for tunneling
130
131         :param ip: IP of bridge
132         :param mac_addr: MAC address of the bridge
133         :param br_name: Name of the bridge
134
135         :return: None
136         """
137         self.logger.debug('tnl/arp/set')
138         self.run_appctl(['tnl/arp/set', br_name, ip_addr, mac_addr])
139
140
141 class OFBridge(OFBase):
142     """Control a bridge instance using ``ovs-vsctl`` and ``ovs-ofctl``.
143     """
144     def __init__(self, br_name=_OVS_BRIDGE_NAME, timeout=_OVS_CMD_TIMEOUT):
145         """Initialise bridge.
146
147         :param br_name: Bridge name
148         :param timeout: Timeout to be used for each command
149
150         :returns: None
151         """
152         super(OFBridge, self).__init__(timeout)
153         self.br_name = br_name
154         self._ports = {}
155         self._cache_file = None
156
157     # context manager
158
159     def __enter__(self):
160         """Create datapath
161
162         :returns: self
163         """
164         return self
165
166     def __exit__(self, type_, value, traceback):
167         """Remove datapath.
168         """
169         if not traceback:
170             self.destroy()
171
172     # helpers
173
174     def run_ofctl(self, args, check_error=False, timeout=None):
175         """Run ``ovs-ofctl`` with supplied arguments.
176
177         :param args: Arguments to pass to ``ovs-ofctl``
178         :param check_error: Throw exception on error
179
180         :return: None
181         """
182         tmp_timeout = self.timeout if timeout is None else timeout
183         cmd = ['sudo', settings.getValue('TOOLS')['ovs-ofctl'], '-O',
184                'OpenFlow13', '--timeout', str(tmp_timeout)] + args
185         return tasks.run_task(
186             cmd, self.logger, 'Running ovs-ofctl...', check_error)
187
188     def create(self, params=None):
189         """Create bridge.
190         """
191         if params is None:
192             params = []
193
194         self.logger.debug('create bridge')
195         self.add_br(self.br_name, params=params)
196
197     def destroy(self):
198         """Destroy bridge.
199         """
200         self.logger.debug('destroy bridge')
201         self.del_br(self.br_name)
202
203     def reset(self):
204         """Reset bridge.
205         """
206         self.logger.debug('reset bridge')
207         self.destroy()
208         self.create()
209
210     # port management
211
212     def add_port(self, port_name, params):
213         """Add port to bridge.
214
215         :param port_name: Name of port
216         :param params: Additional list of parameters to add-port
217
218         :return: OpenFlow port number for the port
219         """
220         self.logger.debug('add port')
221         self.run_vsctl(['add-port', self.br_name, port_name]+params)
222
223         # This is how port number allocation works currently
224         # This possibly will not work correctly if there are port deletions
225         # in between
226         of_port = len(self._ports) + 1
227         self._ports[port_name] = (of_port, params)
228         return of_port
229
230     def del_port(self, port_name):
231         """Remove port from bridge.
232
233         :param port_name: Name of port
234
235         :return: None
236         """
237         self.logger.debug('delete port')
238         self.run_vsctl(['del-port', self.br_name, port_name])
239         self._ports.pop(port_name)
240
241     def set_db_attribute(self, table_name, record, column, value):
242         """Set database attribute.
243
244         :param table_name: Name of table
245         :param record: Name of record
246         :param column: Name of column
247         :param value: Value to set
248
249         :return: None
250         """
251         self.logger.debug('set attribute')
252         self.run_vsctl(['set', table_name, record, '%s=%s' % (column, value)])
253
254     def get_ports(self):
255         """Get the ports of this bridge
256
257         Structure of the returned ports dictionary is
258         'portname': (openflow_port_number, extra_parameters)
259
260         Example:
261         ports = {
262             'dpdkport0':
263                 (1, ['--', 'set', 'Interface', 'dpdkport0', 'type=dpdk']),
264             'dpdkvhostport0':
265                 (2, ['--', 'set', 'Interface', 'dpdkvhostport0',
266                      'type=dpdkvhost'])
267         }
268
269         :return: Dictionary of ports
270         """
271         return self._ports
272
273     def clear_db_attribute(self, table_name, record, column):
274         """Clear database attribute.
275
276         :param table_name: Name of table
277         :param record: Name of record
278         :param column: Name of column
279
280         :return: None
281         """
282         self.logger.debug('clear attribute')
283         self.run_vsctl(['clear', table_name, record, column])
284
285     # flow mangement
286
287     def add_flow(self, flow, cache='off'):
288         """Add flow to bridge.
289
290         :param flow: Flow description as a dictionary
291         For flow dictionary structure, see function flow_key
292
293         :return: None
294         """
295         # insert flows from cache into OVS if needed
296         if cache == 'flush':
297             if self._cache_file is None:
298                 self.logger.error('flow cache flush called, but nothing is cached')
299                 return
300             self.logger.debug('flows cached in %s will be added to the bridge', _CACHE_FILE_NAME)
301             self._cache_file.close()
302             self._cache_file = None
303             self.run_ofctl(['add-flows', self.br_name, _CACHE_FILE_NAME], timeout=600)
304             return
305
306         if not flow.get('actions'):
307             self.logger.error('add flow requires actions')
308             return
309
310         _flow_key = flow_key(flow)
311         self.logger.debug('key : %s', _flow_key)
312
313         # insert flow to the cache or OVS
314         if cache == 'on':
315             # create and open cache file if needed
316             if self._cache_file is None:
317                 self._cache_file = open(_CACHE_FILE_NAME, 'w')
318             self._cache_file.write(_flow_key + '\n')
319         else:
320             self.run_ofctl(['add-flow', self.br_name, _flow_key])
321
322     def del_flow(self, flow):
323         """Delete flow from bridge.
324
325         :param flow: Flow description as a dictionary
326         For flow dictionary structure, see function flow_key
327         flow=None will delete all flows
328
329         :return: None
330         """
331         self.logger.debug('delete flow')
332         _flow_key = flow_key(flow)
333         self.logger.debug('key : %s', _flow_key)
334         self.run_ofctl(['del-flows', self.br_name, _flow_key])
335
336     def del_flows(self):
337         """Delete all flows from bridge.
338         """
339         self.logger.debug('delete flows')
340         self.run_ofctl(['del-flows', self.br_name])
341
342     def dump_flows(self):
343         """Dump all flows from bridge.
344         """
345         self.logger.debug('dump flows')
346         self.run_ofctl(['dump-flows', self.br_name], timeout=120)
347
348     def set_stp(self, enable=True):
349         """
350         Set stp status
351         :param enable: Boolean to enable or disable stp
352         :return: None
353         """
354         self.logger.debug(
355             'Setting stp on bridge to %s', 'on' if enable else 'off')
356         self.run_vsctl(
357             ['set', 'Bridge', self.br_name, 'stp_enable={}'.format(
358                 'true' if enable else 'false')])
359
360     def set_rstp(self, enable=True):
361         """
362         Set rstp status
363         :param enable: Boolean to enable or disable rstp
364         :return: None
365         """
366         self.logger.debug(
367             'Setting rstp on bridge to %s', 'on' if enable else 'off')
368         self.run_vsctl(
369             ['set', 'Bridge', self.br_name, 'rstp_enable={}'.format(
370                 'true' if enable else 'false')])
371
372     def bridge_info(self):
373         """
374         Get bridge info
375         :return: Returns bridge info from list bridge command
376         """
377         return self.run_vsctl(['list', 'bridge', self.br_name])
378
379 #
380 # helper functions
381 #
382
383 def flow_key(flow):
384     """Model a flow key string for ``ovs-ofctl``.
385
386     Syntax taken from ``ovs-ofctl`` manpages:
387         http://openvswitch.org/cgi-bin/ovsman.cgi?page=utilities%2Fovs-ofctl.8
388
389     Example flow dictionary:
390     flow = {
391         'in_port': '1',
392         'idle_timeout': '0',
393         'actions': ['output:3']
394     }
395
396     :param flow: Flow description as a dictionary
397
398     :return: String
399     :rtype: str
400     """
401     _flow_add_key = string.Template('${fields},action=${actions}')
402     _flow_del_key = string.Template('${fields}')
403
404     field_params = []
405
406     user_params = (x for x in list(flow.items()) if x[0] != 'actions')
407     for (key, default) in user_params:
408         field_params.append('%(field)s=%(value)s' %
409                             {'field': key, 'value': default})
410
411     field_params_str = ','.join(field_params)
412
413     _flow_key_param = {
414         'fields': field_params_str,
415     }
416
417     # no actions == delete key
418     if 'actions' in flow:
419         _flow_key_param['actions'] = ','.join(flow['actions'])
420
421         flow_str = _flow_add_key.substitute(_flow_key_param)
422     else:
423         flow_str = _flow_del_key.substitute(_flow_key_param)
424
425     return flow_str
426
427 def flow_match(flow_dump, flow_src):
428     """ Compares two flows
429
430     :param flow_dump: string - a string with flow obtained by ovs-ofctl dump-flows
431     :param flow_src: string - a string with flow obtained by call of flow_key()
432
433     :return: boolean
434     """
435     # perform unifications on both source and destination flows
436     flow_dump = flow_dump.replace('actions=', 'action=')
437     flow_src = flow_src.replace('actions=', 'action=')
438     # For complex flows the output of "ovs-ofctl dump-flows" can use the
439     # shorthand notation.
440     # eg if we set a flow with constraints on UDP ports like in the following
441     # {'dl_type': '0x0800', 'nw_proto': '17', 'in_port': '1', 'udp_dst': '0', 'actions': ['output:2']}
442     # dump-flows output can combine the first 2 constraints into 'udp' and translate
443     # 'udp_dst' into 'tp_dst' like
444     # "udp,in_port=1,tp_dst=0 actions=output:2".
445     # So the next replacements are needed.
446     flow_dump = flow_dump.replace('ip', 'dl_type=0x0800')
447     flow_dump = flow_dump.replace('tcp', 'nw_proto=6,dl_type=0x0800')
448     flow_dump = flow_dump.replace('udp', 'nw_proto=17,dl_type=0x0800')
449     flow_src = flow_src.replace('udp_src', 'tp_src')
450     flow_src = flow_src.replace('udp_dst', 'tp_dst')
451     flow_src = flow_src.replace('tcp_src', 'tp_src')
452     flow_src = flow_src.replace('tcp_dst', 'tp_dst')
453     flow_src = flow_src.replace('0x800', '0x0800')
454
455     # modify IPv4 CIDR to real network addresses
456     for ipv4_cidr in re.findall(_IPV4_REGEX, flow_src):
457         if ipv4_cidr[2]:
458             tmp_cidr = str(netaddr.IPNetwork(ipv4_cidr[0]).cidr)
459             flow_src = flow_src.replace(ipv4_cidr[0], tmp_cidr)
460
461     # split flow strings into lists of comparable elements
462     flow_dump_list = re.findall(r"[\w.:=()/]+", flow_dump)
463     flow_src_list = re.findall(r"[\w.:=()/]+", flow_src)
464
465     # check if all items from source flow are present in dump flow
466     flow_src_ctrl = list(flow_src_list)
467     for rule in flow_src_list:
468         if rule in flow_dump_list:
469             flow_src_ctrl.remove(rule)
470     return True if not len(flow_src_ctrl) else False