1 # Copyright 2015-2016 Intel Corporation.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 """Wrapper for an OVS bridge for convenient use of ``ovs-vsctl`` and
18 Much of this code is based on ``ovs-lib.py`` from Open Stack:
20 https://github.com/openstack/neutron/blob/6eac1dc99124ca024d6a69b3abfa3bc69c735667/neutron/agent/linux/ovs_lib.py
28 from tools import tasks
29 from conf import settings
31 _OVS_VSCTL_BIN = os.path.join(settings.getValue('OVS_DIR'), 'utilities',
33 _OVS_OFCTL_BIN = os.path.join(settings.getValue('OVS_DIR'), 'utilities',
35 _OVS_APPCTL_BIN = os.path.join(settings.getValue('OVS_DIR'), 'utilities',
38 _OVS_BRIDGE_NAME = settings.getValue('VSWITCH_BRIDGE_NAME')
40 _CACHE_FILE_NAME = '/tmp/vsperf_flows_cache'
43 """Add/remove/show datapaths using ``ovs-ofctl``.
45 def __init__(self, timeout=10):
48 :param timeout: Timeout to be used for each command
52 self.logger = logging.getLogger(__name__)
53 self.timeout = timeout
57 def run_vsctl(self, args, check_error=False):
58 """Run ``ovs-vsctl`` with supplied arguments.
60 In case that timeout is set to -1, then ovs-vsctl
61 will be called with --no-wait option.
63 :param args: Arguments to pass to ``ovs-vsctl``
64 :param check_error: Throw exception on error
68 if self.timeout == -1:
69 cmd = ['sudo', _OVS_VSCTL_BIN, '--no-wait'] + args
71 cmd = ['sudo', _OVS_VSCTL_BIN, '--timeout', str(self.timeout)] + args
72 return tasks.run_task(
73 cmd, self.logger, 'Running ovs-vsctl...', check_error)
76 def run_appctl(self, args, check_error=False):
77 """Run ``ovs-appctl`` with supplied arguments.
79 :param args: Arguments to pass to ``ovs-appctl``
80 :param check_error: Throw exception on error
84 cmd = ['sudo', _OVS_APPCTL_BIN,
86 str(self.timeout)] + args
87 return tasks.run_task(
88 cmd, self.logger, 'Running ovs-appctl...', check_error)
93 def add_br(self, br_name=_OVS_BRIDGE_NAME, params=None):
96 :param br_name: Name of bridge
98 :return: Instance of :class OFBridge:
103 self.logger.debug('add bridge')
104 self.run_vsctl(['add-br', br_name]+params)
106 return OFBridge(br_name, self.timeout)
108 def del_br(self, br_name=_OVS_BRIDGE_NAME):
111 :param br_name: Name of bridge
115 self.logger.debug('delete bridge')
116 self.run_vsctl(['del-br', br_name])
118 # Route and ARP functions
120 def add_route(self, network, destination):
121 """Add route to tunneling routing table.
123 :param network: Network
124 :param destination: Gateway
128 self.logger.debug('add ovs/route')
129 self.run_appctl(['ovs/route/add', network, destination])
132 def set_tunnel_arp(self, ip_addr, mac_addr, br_name=_OVS_BRIDGE_NAME):
133 """Add OVS arp entry for tunneling
135 :param ip: IP of bridge
136 :param mac_addr: MAC address of the bridge
137 :param br_name: Name of the bridge
141 self.logger.debug('tnl/arp/set')
142 self.run_appctl(['tnl/arp/set', br_name, ip_addr, mac_addr])
145 class OFBridge(OFBase):
146 """Control a bridge instance using ``ovs-vsctl`` and ``ovs-ofctl``.
148 def __init__(self, br_name=_OVS_BRIDGE_NAME, timeout=10):
149 """Initialise bridge.
151 :param br_name: Bridge name
152 :param timeout: Timeout to be used for each command
156 super(OFBridge, self).__init__(timeout)
157 self.br_name = br_name
159 self._cache_file = None
170 def __exit__(self, type_, value, traceback):
178 def run_ofctl(self, args, check_error=False, timeout=None):
179 """Run ``ovs-ofctl`` with supplied arguments.
181 :param args: Arguments to pass to ``ovs-ofctl``
182 :param check_error: Throw exception on error
186 tmp_timeout = self.timeout if timeout == None else timeout
187 cmd = ['sudo', _OVS_OFCTL_BIN, '-O', 'OpenFlow13', '--timeout',
188 str(tmp_timeout)] + args
189 return tasks.run_task(
190 cmd, self.logger, 'Running ovs-ofctl...', check_error)
192 def create(self, params=None):
198 self.logger.debug('create bridge')
199 self.add_br(self.br_name, params=params)
204 self.logger.debug('destroy bridge')
205 self.del_br(self.br_name)
210 self.logger.debug('reset bridge')
216 def add_port(self, port_name, params):
217 """Add port to bridge.
219 :param port_name: Name of port
220 :param params: Additional list of parameters to add-port
222 :return: OpenFlow port number for the port
224 self.logger.debug('add port')
225 self.run_vsctl(['add-port', self.br_name, port_name]+params)
227 # This is how port number allocation works currently
228 # This possibly will not work correctly if there are port deletions
230 of_port = len(self._ports) + 1
231 self._ports[port_name] = (of_port, params)
234 def del_port(self, port_name):
235 """Remove port from bridge.
237 :param port_name: Name of port
241 self.logger.debug('delete port')
242 self.run_vsctl(['del-port', self.br_name, port_name])
243 self._ports.pop(port_name)
245 def set_db_attribute(self, table_name, record, column, value):
246 """Set database attribute.
248 :param table_name: Name of table
249 :param record: Name of record
250 :param column: Name of column
251 :param value: Value to set
255 self.logger.debug('set attribute')
256 self.run_vsctl(['set', table_name, record, '%s=%s' % (column, value)])
259 """Get the ports of this bridge
261 Structure of the returned ports dictionary is
262 'portname': (openflow_port_number, extra_parameters)
267 (1, ['--', 'set', 'Interface', 'dpdkport0', 'type=dpdk']),
269 (2, ['--', 'set', 'Interface', 'dpdkvhostport0',
273 :return: Dictionary of ports
277 def clear_db_attribute(self, table_name, record, column):
278 """Clear database attribute.
280 :param table_name: Name of table
281 :param record: Name of record
282 :param column: Name of column
286 self.logger.debug('clear attribute')
287 self.run_vsctl(['clear', table_name, record, column])
291 def add_flow(self, flow, cache='off'):
292 """Add flow to bridge.
294 :param flow: Flow description as a dictionary
295 For flow dictionary structure, see function flow_key
299 # insert flows from cache into OVS if needed
301 if self._cache_file == None:
302 self.logger.error('flow cache flush called, but nothing is cached')
304 self.logger.debug('flows cached in %s will be added to the bridge', _CACHE_FILE_NAME)
305 self._cache_file.close()
306 self._cache_file = None
307 self.run_ofctl(['add-flows', self.br_name, _CACHE_FILE_NAME], timeout=600)
310 if not flow.get('actions'):
311 self.logger.error('add flow requires actions')
314 _flow_key = flow_key(flow)
315 self.logger.debug('key : %s', _flow_key)
317 # insert flow to the cache or OVS
319 # create and open cache file if needed
320 if self._cache_file == None:
321 self._cache_file = open(_CACHE_FILE_NAME, 'w')
322 self._cache_file.write(_flow_key + '\n')
324 self.run_ofctl(['add-flow', self.br_name, _flow_key])
326 def del_flow(self, flow):
327 """Delete flow from bridge.
329 :param flow: Flow description as a dictionary
330 For flow dictionary structure, see function flow_key
331 flow=None will delete all flows
335 self.logger.debug('delete flow')
336 _flow_key = flow_key(flow)
337 self.logger.debug('key : %s', _flow_key)
338 self.run_ofctl(['del-flows', self.br_name, _flow_key])
341 """Delete all flows from bridge.
343 self.logger.debug('delete flows')
344 self.run_ofctl(['del-flows', self.br_name])
346 def dump_flows(self):
347 """Dump all flows from bridge.
349 self.logger.debug('dump flows')
350 self.run_ofctl(['dump-flows', self.br_name], timeout=120)
357 """Model a flow key string for ``ovs-ofctl``.
359 Syntax taken from ``ovs-ofctl`` manpages:
360 http://openvswitch.org/cgi-bin/ovsman.cgi?page=utilities%2Fovs-ofctl.8
362 Example flow dictionary:
366 'actions': ['output:3']
369 :param flow: Flow description as a dictionary
374 _flow_add_key = string.Template('${fields},action=${actions}')
375 _flow_del_key = string.Template('${fields}')
379 user_params = (x for x in list(flow.items()) if x[0] != 'actions')
380 for (key, default) in user_params:
381 field_params.append('%(field)s=%(value)s' %
382 {'field': key, 'value': default})
384 field_params_str = ','.join(field_params)
387 'fields': field_params_str,
390 # no actions == delete key
391 if 'actions' in flow:
392 _flow_key_param['actions'] = ','.join(flow['actions'])
394 flow_str = _flow_add_key.substitute(_flow_key_param)
396 flow_str = _flow_del_key.substitute(_flow_key_param)
400 def flow_match(flow_dump, flow_src):
401 """ Compares two flows
403 :param flow_dump: string - a string with flow obtained by ovs-ofctl dump-flows
404 :param flow_src: string - a string with flow obtained by call of flow_key()
408 # perform unifications on both source and destination flows
409 flow_dump = flow_dump.replace('actions=', 'action=')
410 flow_src = flow_src.replace('actions=', 'action=')
412 # split flow strings into lists of comparable elements
413 flow_dump_list = re.findall(r"[\w.:=()]+", flow_dump)
414 flow_src_list = re.findall(r"[\w.:=()]+", flow_src)
416 # check if all items from source flow are present in dump flow
417 flow_src_ctrl = list(flow_src_list)
418 for rule in flow_src_list:
419 if rule in flow_dump_list:
420 flow_src_ctrl.remove(rule)
421 return True if not len(flow_src_ctrl) else False