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',
36 """Add/remove/show datapaths using ``ovs-ofctl``.
38 def __init__(self, timeout=10):
41 :param timeout: Timeout to be used for each command
45 self.logger = logging.getLogger(__name__)
46 self.timeout = timeout
50 def run_vsctl(self, args, check_error=False):
51 """Run ``ovs-vsctl`` with supplied arguments.
53 :param args: Arguments to pass to ``ovs-vsctl``
54 :param check_error: Throw exception on error
58 cmd = ['sudo', _OVS_VSCTL_BIN, '--timeout', str(self.timeout)] + args
59 return tasks.run_task(
60 cmd, self.logger, 'Running ovs-vsctl...', check_error)
64 def add_br(self, br_name='br0'):
67 :param br_name: Name of bridge
69 :return: Instance of :class OFBridge:
71 self.logger.debug('add bridge')
72 self.run_vsctl(['add-br', br_name])
74 return OFBridge(br_name, self.timeout)
76 def del_br(self, br_name='br0'):
79 :param br_name: Name of bridge
83 self.logger.debug('delete bridge')
84 self.run_vsctl(['del-br', br_name])
87 class OFBridge(OFBase):
88 """Control a bridge instance using ``ovs-vsctl`` and ``ovs-ofctl``.
90 def __init__(self, br_name='br0', timeout=10):
93 :param br_name: Bridge name
94 :param timeout: Timeout to be used for each command
98 super(OFBridge, self).__init__(timeout)
99 self.br_name = br_name
111 def __exit__(self, type_, value, traceback):
119 def run_ofctl(self, args, check_error=False):
120 """Run ``ovs-ofctl`` with supplied arguments.
122 :param args: Arguments to pass to ``ovs-ofctl``
123 :param check_error: Throw exception on error
127 cmd = ['sudo', _OVS_OFCTL_BIN, '--timeout', str(self.timeout)] + args
128 return tasks.run_task(
129 cmd, self.logger, 'Running ovs-ofctl...', check_error)
134 self.logger.debug('create bridge')
135 self.add_br(self.br_name)
140 self.logger.debug('destroy bridge')
141 self.del_br(self.br_name)
146 self.logger.debug('reset bridge')
152 def add_port(self, port_name, params):
153 """Add port to bridge.
155 :param port_name: Name of port
156 :param params: Additional list of parameters to add-port
158 :return: OpenFlow port number for the port
160 self.logger.debug('add port')
161 self.run_vsctl(['add-port', self.br_name, port_name]+params)
163 # This is how port number allocation works currently
164 # This possibly will not work correctly if there are port deletions
166 of_port = len(self._ports) + 1
167 self._ports[port_name] = (of_port, params)
170 def del_port(self, port_name):
171 """Remove port from bridge.
173 :param port_name: Name of port
177 self.logger.debug('delete port')
178 self.run_vsctl(['del-port', self.br_name, port_name])
179 self._ports.pop(port_name)
181 def set_db_attribute(self, table_name, record, column, value):
182 """Set database attribute.
184 :param table_name: Name of table
185 :param record: Name of record
186 :param column: Name of column
187 :param value: Value to set
191 self.logger.debug('set attribute')
192 self.run_vsctl(['set', table_name, record, '%s=%s' % (column, value)])
195 """Get the ports of this bridge
197 Structure of the returned ports dictionary is
198 'portname': (openflow_port_number, extra_parameters)
203 (1, ['--', 'set', 'Interface', 'dpdkport0', 'type=dpdk']),
205 (2, ['--', 'set', 'Interface', 'dpdkvhostport0',
209 :return: Dictionary of ports
213 def clear_db_attribute(self, table_name, record, column):
214 """Clear database attribute.
216 :param table_name: Name of table
217 :param record: Name of record
218 :param column: Name of column
222 self.logger.debug('clear attribute')
223 self.run_vsctl(['clear', table_name, record, column])
227 def add_flow(self, flow):
228 """Add flow to bridge.
230 :param flow: Flow description as a dictionary
231 For flow dictionary structure, see function flow_key
235 if not flow.get('actions'):
236 self.logger.error('add flow requires actions')
239 self.logger.debug('add flow')
240 _flow_key = flow_key(flow)
241 self.logger.debug('key : %s', _flow_key)
242 self.run_ofctl(['add-flow', self.br_name, _flow_key])
244 def del_flow(self, flow):
245 """Delete flow from bridge.
247 :param flow: Flow description as a dictionary
248 For flow dictionary structure, see function flow_key
249 flow=None will delete all flows
253 self.logger.debug('delete flow')
254 _flow_key = flow_key(flow)
255 self.logger.debug('key : %s', _flow_key)
256 self.run_ofctl(['del-flows', self.br_name, _flow_key])
259 """Delete all flows from bridge.
261 self.logger.debug('delete flows')
262 self.run_ofctl(['del-flows', self.br_name])
264 def dump_flows(self):
265 """Dump all flows from bridge.
267 self.logger.debug('dump flows')
268 self.run_ofctl(['dump-flows', self.br_name])
275 """Model a flow key string for ``ovs-ofctl``.
277 Syntax taken from ``ovs-ofctl`` manpages:
278 http://openvswitch.org/cgi-bin/ovsman.cgi?page=utilities%2Fovs-ofctl.8
280 Example flow dictionary:
284 'actions': ['output:3']
287 :param flow: Flow description as a dictionary
292 _flow_add_key = string.Template('${fields},action=${actions}')
293 _flow_del_key = string.Template('${fields}')
297 user_params = (x for x in list(flow.items()) if x[0] != 'actions')
298 for (key, default) in user_params:
299 field_params.append('%(field)s=%(value)s' %
300 {'field': key, 'value': default})
302 field_params = ','.join(field_params)
305 'fields': field_params,
308 # no actions == delete key
309 if 'actions' in flow:
310 _flow_key_param['actions'] = ','.join(flow['actions'])
312 flow_str = _flow_add_key.substitute(_flow_key_param)
314 flow_str = _flow_del_key.substitute(_flow_key_param)