1 # Copyright 2015-2017 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 """VSPERF Open vSwitch base class
26 from conf import settings
27 from src.ovs import OFBridge, flow_key, flow_match
28 from vswitches.vswitch import IVSwitch
29 from tools import tasks
30 from tools.module_manager import ModuleManager
31 # pylint: disable=too-many-public-methods
32 class IVSwitchOvs(IVSwitch, tasks.Process):
33 """Open vSwitch base class implementation
35 The method docstrings document only considerations specific to this
36 implementation. For generic information of the nature of the methods,
39 _proc_name = 'ovs-vswitchd'
42 """See IVswitch for general description
44 self._logfile = os.path.join(settings.getValue('LOG_DIR'),
45 settings.getValue('LOG_FILE_VSWITCHD'))
46 self._ovsdb_pidfile_path = os.path.join(settings.getValue('TOOLS')['ovs_var_tmp'],
48 self._vswitchd_pidfile_path = os.path.join(settings.getValue('TOOLS')['ovs_var_tmp'],
49 "{}.pid".format(self._proc_name))
50 self._logger = logging.getLogger(__name__)
51 self._expect = r'bridge|INFO|{}'.format(self._proc_name)
54 self._vswitchd_args = ['--pidfile=' + self._vswitchd_pidfile_path,
55 '--overwrite-pidfile', '--log-file=' + self._logfile]
57 self._cmd_template = ['sudo', '-E', settings.getValue('TOOLS')['ovs-vswitchd']]
59 self._module_manager = ModuleManager()
62 """ Start ``ovsdb-server`` and ``ovs-vswitchd`` instance.
64 :raises: pexpect.EOF, pexpect.TIMEOUT
66 self._logger.info("Starting vswitchd...")
68 # insert kernel modules if required
69 if 'vswitch_modules' in settings.getValue('TOOLS'):
70 self._module_manager.insert_modules(settings.getValue('TOOLS')['vswitch_modules'])
72 self._cmd = self._cmd_template + self._vswitchd_args
74 # DB must be started before vswitchd
78 # DB must be up before vswitchd config is altered or vswitchd started
84 tasks.Process.start(self)
86 except (pexpect.EOF, pexpect.TIMEOUT) as exc:
87 logging.error("Exception during VSwitch start.")
91 self._logger.info("Vswitchd...Started.")
94 """ Configure vswitchd through ovsdb if needed
99 """See IVswitch for general description
101 self._logger.info("Terminating vswitchd...")
103 self._logger.info("Vswitchd...Terminated.")
105 def add_switch(self, switch_name, params=None):
106 """See IVswitch for general description
108 bridge = OFBridge(switch_name)
109 bridge.create(params)
110 bridge.set_db_attribute('Open_vSwitch', '.',
111 'other_config:max-idle',
112 settings.getValue('VSWITCH_FLOW_TIMEOUT'))
113 self._bridges[switch_name] = bridge
115 def del_switch(self, switch_name):
116 """See IVswitch for general description
118 bridge = self._bridges[switch_name]
119 self._bridges.pop(switch_name)
122 def add_phy_port(self, switch_name):
123 """See IVswitch for general description
125 raise NotImplementedError
127 def add_vport(self, switch_name):
128 """See IVswitch for general description
130 raise NotImplementedError
132 def add_veth_pair_port(self, switch_name=None, remote_switch_name=None,
133 local_opts=None, remote_opts=None):
134 """Creates veth-pair port between 'switch_name' and 'remote_switch_name'
137 if switch_name is None or remote_switch_name is None:
140 bridge = self._bridges[switch_name]
141 remote_bridge = self._bridges[remote_switch_name]
142 pcount = str(self._get_port_count('type=patch'))
143 # NOTE ::: What if interface name longer than allowed width??
144 local_port_name = switch_name + '-' + remote_switch_name + '-' + pcount
145 remote_port_name = remote_switch_name + '-' + switch_name + '-' + pcount
146 local_params = ['--', 'set', 'Interface', local_port_name,
148 'options:peer=' + remote_port_name]
149 remote_params = ['--', 'set', 'Interface', remote_port_name,
151 'options:peer=' + local_port_name]
153 if local_opts is not None:
154 local_params = local_params + local_opts
156 if remote_opts is not None:
157 remote_params = remote_params + remote_opts
159 local_of_port = bridge.add_port(local_port_name, local_params)
160 remote_of_port = remote_bridge.add_port(remote_port_name, remote_params)
161 return [(local_port_name, local_of_port),
162 (remote_port_name, remote_of_port)]
164 def add_tunnel_port(self, switch_name, remote_ip, tunnel_type='vxlan', params=None):
165 """Creates tunneling port
167 bridge = self._bridges[switch_name]
168 pcount = str(self._get_port_count('type=' + tunnel_type))
169 port_name = tunnel_type + pcount
170 local_params = ['--', 'set', 'Interface', port_name,
171 'type=' + tunnel_type,
172 'options:remote_ip=' + remote_ip]
174 if params is not None:
175 local_params = local_params + params
177 of_port = bridge.add_port(port_name, local_params)
178 return (port_name, of_port)
180 def get_ports(self, switch_name):
181 """See IVswitch for general description
183 bridge = self._bridges[switch_name]
184 ports = list(bridge.get_ports().items())
185 return [(name, of_port) for (name, (of_port, _)) in ports]
187 def del_port(self, switch_name, port_name):
188 """See IVswitch for general description
190 bridge = self._bridges[switch_name]
191 bridge.del_port(port_name)
193 def add_flow(self, switch_name, flow, cache='off'):
194 """See IVswitch for general description
196 bridge = self._bridges[switch_name]
197 bridge.add_flow(flow, cache=cache)
199 def del_flow(self, switch_name, flow=None):
200 """See IVswitch for general description
203 bridge = self._bridges[switch_name]
204 bridge.del_flow(flow)
206 def dump_flows(self, switch_name):
207 """See IVswitch for general description
209 bridge = self._bridges[switch_name]
212 def add_route(self, switch_name, network, destination):
213 """See IVswitch for general description
215 bridge = self._bridges[switch_name]
216 bridge.add_route(network, destination)
218 def set_tunnel_arp(self, ip_addr, mac_addr, switch_name):
219 """See IVswitch for general description
221 bridge = self._bridges[switch_name]
222 bridge.set_tunnel_arp(ip_addr, mac_addr, switch_name)
224 def _get_port_count(self, param):
225 """Returns the number of ports having a certain parameter
228 for k in self._bridges:
229 pparams = [c for (_, (_, c)) in list(self._bridges[k].get_ports().items())]
230 phits = [i for i in pparams if param in i]
237 def disable_stp(self, switch_name):
239 Disable stp protocol on the bridge
240 :param switch_name: bridge to disable stp
243 bridge = self._bridges[switch_name]
244 bridge.set_stp(False)
245 self._logger.info('Sleeping for 50 secs to allow stp to stop.')
246 time.sleep(50) # needs time to disable
248 def enable_stp(self, switch_name):
250 Enable stp protocol on the bridge
251 :param switch_name: bridge to enable stp
254 bridge = self._bridges[switch_name]
256 self._logger.info('Sleeping for 50 secs to allow stp to start.')
257 time.sleep(50) # needs time to enable
259 def disable_rstp(self, switch_name):
261 Disable rstp on the bridge
262 :param switch_name: bridge to disable rstp
265 bridge = self._bridges[switch_name]
266 bridge.set_rstp(False)
267 self._logger.info('Sleeping for 15 secs to allow rstp to stop.')
268 time.sleep(15) # needs time to disable
270 def enable_rstp(self, switch_name):
272 Enable rstp on the bridge
273 :param switch_name: bridge to enable rstp
276 bridge = self._bridges[switch_name]
277 bridge.set_rstp(True)
278 self._logger.info('Sleeping for 15 secs to allow rstp to start.')
279 time.sleep(15) # needs time to enable
281 def kill(self, signal='-15', sleep=10):
282 """Kill ``ovs-vswitchd`` and ``ovs-ovsdb`` instances if they are alive.
286 if os.path.isfile(self._vswitchd_pidfile_path):
287 self._logger.info('Killing ovs-vswitchd...')
288 with open(self._vswitchd_pidfile_path, "r") as pidfile:
289 vswitchd_pid = pidfile.read().strip()
290 tasks.terminate_task(vswitchd_pid, logger=self._logger)
292 self._kill_ovsdb() # ovsdb must be killed after vswitchd
294 # just for case, that sudo envelope has not been terminated yet
295 tasks.Process.kill(self, signal, sleep)
299 def _reset_ovsdb(self):
300 """Reset system for 'ovsdb'.
304 self._logger.info('Resetting system after last run...')
306 # create a backup of ovs_var_tmp and ovs_etc_tmp; It is
307 # essential for OVS installed from binary packages.
308 self._stamp = '{:%Y%m%d_%H%M%S}_{}'.format(datetime.datetime.now(),
309 random.randrange(1000, 9999))
310 for tmp_dir in ['ovs_var_tmp', 'ovs_etc_tmp']:
311 if os.path.exists(settings.getValue('TOOLS')[tmp_dir]):
312 orig_dir = os.path.normpath(settings.getValue('TOOLS')[tmp_dir])
313 self._logger.info('Creating backup of %s directory...', tmp_dir)
314 tasks.run_task(['sudo', 'mv', orig_dir, '{}.{}'.format(orig_dir, self._stamp)],
317 # create fresh tmp dirs
318 tasks.run_task(['sudo', 'mkdir', '-p', settings.getValue('TOOLS')['ovs_var_tmp']], self._logger)
319 tasks.run_task(['sudo', 'mkdir', '-p', settings.getValue('TOOLS')['ovs_etc_tmp']], self._logger)
321 self._logger.info('System reset after last run.')
323 def _start_ovsdb(self):
324 """Start ``ovsdb-server`` instance.
328 ovsdb_tool_bin = settings.getValue('TOOLS')['ovsdb-tool']
329 tasks.run_task(['sudo', ovsdb_tool_bin, 'create',
330 os.path.join(settings.getValue('TOOLS')['ovs_etc_tmp'], 'conf.db'),
331 settings.getValue('TOOLS')['ovsschema']],
333 'Creating ovsdb configuration database...')
335 ovsdb_server_bin = settings.getValue('TOOLS')['ovsdb-server']
337 tasks.run_background_task(
338 ['sudo', ovsdb_server_bin,
339 '--remote=punix:%s' % os.path.join(settings.getValue('TOOLS')['ovs_var_tmp'], 'db.sock'),
340 '--remote=db:Open_vSwitch,Open_vSwitch,manager_options',
341 '--pidfile=' + self._ovsdb_pidfile_path, '--overwrite-pidfile'],
343 'Starting ovsdb-server...')
345 def _kill_ovsdb(self):
346 """Kill ``ovsdb-server`` instance.
350 if os.path.isfile(self._ovsdb_pidfile_path):
351 with open(self._ovsdb_pidfile_path, "r") as pidfile:
352 ovsdb_pid = pidfile.read().strip()
354 self._logger.info("Killing ovsdb with pid: " + ovsdb_pid)
357 tasks.terminate_task(ovsdb_pid, logger=self._logger)
359 # restore original content of ovs_var_tmp and ovs_etc_tmp; It is
360 # essential for OVS installed from binary packages.
362 for tmp_dir in ['ovs_var_tmp', 'ovs_etc_tmp']:
363 orig_dir = os.path.normpath(settings.getValue('TOOLS')[tmp_dir])
364 if os.path.exists('{}.{}'.format(orig_dir, self._stamp)):
365 self._logger.info('Restoring backup of %s directory...', tmp_dir)
366 tasks.run_task(['sudo', 'rm', '-rf', orig_dir], self._logger)
367 tasks.run_task(['sudo', 'mv', '{}.{}'.format(orig_dir, self._stamp), orig_dir],
371 def get_db_sock_path():
372 """Method returns location of db.sock file
374 :returns: path to db.sock file.
376 return os.path.join(settings.getValue('TOOLS')['ovs_var_tmp'], 'db.sock')
379 # validate methods required for integration testcases
381 def validate_add_switch(self, dummy_result, switch_name, dummy_params=None):
382 """Validate - Create a new logical switch with no ports
384 bridge = self._bridges[switch_name]
385 output = bridge.run_vsctl(['show'], check_error=True)
386 assert not output[1] # there shouldn't be any stderr, but in case
387 assert re.search('Bridge ["\']?%s["\']?' % switch_name, output[0]) is not None
390 # Method could be a function
391 # pylint: disable=no-self-use
392 def validate_del_switch(self, dummy_result, switch_name):
393 """Validate removal of switch
395 bridge = OFBridge('tmp')
396 output = bridge.run_vsctl(['show'], check_error=True)
397 assert not output[1] # there shouldn't be any stderr, but in case
398 assert re.search('Bridge ["\']?%s["\']?' % switch_name, output[0]) is None
401 def validate_add_phy_port(self, result, switch_name):
402 """ Validate that physical port was added to bridge.
404 bridge = self._bridges[switch_name]
405 output = bridge.run_vsctl(['show'], check_error=True)
406 assert not output[1] # there shouldn't be any stderr, but in case
407 assert re.search('Port ["\']?%s["\']?' % result[0], output[0]) is not None
408 assert re.search('Interface ["\']?%s["\']?' % result[0], output[0]) is not None
411 def validate_add_vport(self, result, switch_name):
412 """ Validate that virtual port was added to bridge.
414 return self.validate_add_phy_port(result, switch_name)
416 def validate_del_port(self, dummy_result, switch_name, port_name):
417 """ Validate that port_name was removed from bridge.
419 bridge = self._bridges[switch_name]
420 output = bridge.run_vsctl(['show'], check_error=True)
421 assert not output[1] # there shouldn't be any stderr, but in case
422 assert 'Port "%s"' % port_name not in output[0]
425 def validate_add_flow(self, dummy_result, switch_name, flow, dummy_cache='off'):
426 """ Validate insertion of the flow into the switch
429 if 'idle_timeout' in flow:
430 del flow['idle_timeout']
432 # Note: it should be possible to call `ovs-ofctl dump-flows switch flow`
433 # to verify flow insertion, but it doesn't accept the same flow syntax
434 # as add-flow, so we have to compare it the hard way
436 # get dump of flows and compare them one by one
437 flow_src = flow_key(flow)
438 bridge = self._bridges[switch_name]
439 output = bridge.run_ofctl(['dump-flows', switch_name], check_error=True)
440 for flow_dump in output[0].split('\n'):
441 if flow_match(flow_dump, flow_src):
442 # flow was added correctly
446 def validate_del_flow(self, dummy_result, switch_name, flow=None):
447 """ Validate removal of the flow
450 # what else we can do?
452 return not self.validate_add_flow(dummy_result, switch_name, flow)
454 def validate_dump_flows(self, dummy_result, dummy_switch_name):
455 """ Validate call of flow dump
459 def validate_disable_rstp(self, dummy_result, switch_name):
460 """ Validate rstp disable
462 bridge = self._bridges[switch_name]
463 return 'rstp_enable : false' in ''.join(bridge.bridge_info())
465 def validate_enable_rstp(self, dummy_result, switch_name):
466 """ Validate rstp enable
468 bridge = self._bridges[switch_name]
469 return 'rstp_enable : true' in ''.join(bridge.bridge_info())
471 def validate_disable_stp(self, dummy_result, switch_name):
472 """ Validate stp disable
474 bridge = self._bridges[switch_name]
475 return 'stp_enable : false' in ''.join(bridge.bridge_info())
477 def validate_enable_stp(self, dummy_result, switch_name):
478 """ Validate stp enable
480 bridge = self._bridges[switch_name]
481 return 'stp_enable : true' in ''.join(bridge.bridge_info())