1 # Copyright 2015 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
27 from tools import tasks
28 from conf import settings
30 _OVS_VSCTL_BIN = os.path.join(settings.getValue('OVS_DIR'), 'utilities',
32 _OVS_OFCTL_BIN = os.path.join(settings.getValue('OVS_DIR'), 'utilities',
35 _OVS_VAR_DIR = '/usr/local/var/run/openvswitch/'
38 """Add/remove/show datapaths using ``ovs-ofctl``.
40 def __init__(self, timeout=10):
43 :param timeout: Timeout to be used for each command
47 self.logger = logging.getLogger(__name__)
48 self.timeout = timeout
52 def run_vsctl(self, args, check_error=False):
53 """Run ``ovs-vsctl`` with supplied arguments.
55 :param args: Arguments to pass to ``ovs-vsctl``
56 :param check_error: Throw exception on error
60 cmd = ['sudo', _OVS_VSCTL_BIN, '--timeout', str(self.timeout)] + args
61 return tasks.run_task(
62 cmd, self.logger, 'Running ovs-vsctl...', check_error)
66 def add_br(self, br_name='br0'):
69 :param br_name: Name of bridge
71 :return: Instance of :class OFBridge:
73 self.logger.debug('add bridge')
74 self.run_vsctl(['add-br', br_name])
76 return OFBridge(br_name, self.timeout)
78 def del_br(self, br_name='br0'):
81 :param br_name: Name of bridge
85 self.logger.debug('delete bridge')
86 self.run_vsctl(['del-br', br_name])
89 class OFBridge(OFBase):
90 """Control a bridge instance using ``ovs-vsctl`` and ``ovs-ofctl``.
92 def __init__(self, br_name='br0', timeout=10):
95 :param br_name: Bridge name
96 :param timeout: Timeout to be used for each command
100 super(OFBridge, self).__init__(timeout)
101 self.br_name = br_name
113 def __exit__(self, type_, value, traceback):
121 def run_ofctl(self, args, check_error=False):
122 """Run ``ovs-ofctl`` with supplied arguments.
124 :param args: Arguments to pass to ``ovs-ofctl``
125 :param check_error: Throw exception on error
129 cmd = ['sudo', _OVS_OFCTL_BIN, '-O', 'OpenFlow13', '--timeout', str(self.timeout)] + args
130 return tasks.run_task(
131 cmd, self.logger, 'Running ovs-ofctl...', check_error)
136 self.logger.debug('create bridge')
137 self.add_br(self.br_name)
142 self.logger.debug('destroy bridge')
143 self.del_br(self.br_name)
148 self.logger.debug('reset bridge')
154 def add_port(self, port_name, params):
155 """Add port to bridge.
157 :param port_name: Name of port
158 :param params: Additional list of parameters to add-port
160 :return: OpenFlow port number for the port
162 self.logger.debug('add port')
163 self.run_vsctl(['add-port', self.br_name, port_name]+params)
165 # This is how port number allocation works currently
166 # This possibly will not work correctly if there are port deletions
168 of_port = len(self._ports) + 1
169 self._ports[port_name] = (of_port, params)
172 def del_port(self, port_name):
173 """Remove port from bridge.
175 :param port_name: Name of port
179 self.logger.debug('delete port')
180 self.run_vsctl(['del-port', self.br_name, port_name])
181 self._ports.pop(port_name)
183 def set_db_attribute(self, table_name, record, column, value):
184 """Set database attribute.
186 :param table_name: Name of table
187 :param record: Name of record
188 :param column: Name of column
189 :param value: Value to set
193 self.logger.debug('set attribute')
194 self.run_vsctl(['set', table_name, record, '%s=%s' % (column, value)])
197 """Get the ports of this bridge
199 Structure of the returned ports dictionary is
200 'portname': (openflow_port_number, extra_parameters)
205 (1, ['--', 'set', 'Interface', 'dpdkport0', 'type=dpdk']),
207 (2, ['--', 'set', 'Interface', 'dpdkvhostport0',
211 :return: Dictionary of ports
215 def clear_db_attribute(self, table_name, record, column):
216 """Clear database attribute.
218 :param table_name: Name of table
219 :param record: Name of record
220 :param column: Name of column
224 self.logger.debug('clear attribute')
225 self.run_vsctl(['clear', table_name, record, column])
229 def add_flow(self, flow):
230 """Add flow to bridge.
232 :param flow: Flow description as a dictionary
233 For flow dictionary structure, see function flow_key
237 if not flow.get('actions'):
238 self.logger.error('add flow requires actions')
241 self.logger.debug('add flow')
242 _flow_key = flow_key(flow)
243 self.logger.debug('key : %s', _flow_key)
244 self.run_ofctl(['add-flow', self.br_name, _flow_key])
246 def del_flow(self, flow):
247 """Delete flow from bridge.
249 :param flow: Flow description as a dictionary
250 For flow dictionary structure, see function flow_key
251 flow=None will delete all flows
255 self.logger.debug('delete flow')
256 _flow_key = flow_key(flow)
257 self.logger.debug('key : %s', _flow_key)
258 self.run_ofctl(['del-flows', self.br_name, _flow_key])
261 """Delete all flows from bridge.
263 self.logger.debug('delete flows')
264 self.run_ofctl(['del-flows', self.br_name])
266 def dump_flows(self):
267 """Dump all flows from bridge.
269 self.logger.debug('dump flows')
270 self.run_ofctl(['dump-flows', self.br_name])
277 """Model a flow key string for ``ovs-ofctl``.
279 Syntax taken from ``ovs-ofctl`` manpages:
280 http://openvswitch.org/cgi-bin/ovsman.cgi?page=utilities%2Fovs-ofctl.8
282 Example flow dictionary:
286 'actions': ['output:3']
289 :param flow: Flow description as a dictionary
294 _flow_add_key = string.Template('${fields},action=${actions}')
295 _flow_del_key = string.Template('${fields}')
299 user_params = (x for x in list(flow.items()) if x[0] != 'actions')
300 for (key, default) in user_params:
301 field_params.append('%(field)s=%(value)s' %
302 {'field': key, 'value': default})
304 field_params = ','.join(field_params)
307 'fields': field_params,
310 # no actions == delete key
311 if 'actions' in flow:
312 _flow_key_param['actions'] = ','.join(flow['actions'])
314 flow_str = _flow_add_key.substitute(_flow_key_param)
316 flow_str = _flow_del_key.substitute(_flow_key_param)