Create the ovs-vswitchd logging directory
[yardstick.git] / yardstick / benchmark / contexts / standalone / ovs_dpdk.py
1 # Copyright (c) 2016-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 from __future__ import absolute_import
16 import os
17 import logging
18 import collections
19 import time
20
21 from collections import OrderedDict
22
23 from yardstick import ssh
24 from yardstick.network_services.utils import get_nsb_option
25 from yardstick.network_services.utils import provision_tool
26 from yardstick.benchmark.contexts.base import Context
27 from yardstick.benchmark.contexts.standalone.model import Libvirt
28 from yardstick.benchmark.contexts.standalone.model import StandaloneContextHelper
29 from yardstick.benchmark.contexts.standalone.model import Server
30 from yardstick.benchmark.contexts.standalone.model import OvsDeploy
31 from yardstick.network_services.utils import PciAddress
32
33 LOG = logging.getLogger(__name__)
34
35
36 class OvsDpdkContext(Context):
37     """ This class handles OVS standalone nodes - VM running on Non-Managed NFVi
38     Configuration: ovs_dpdk
39     """
40
41     __context_type__ = "StandaloneOvsDpdk"
42
43     SUPPORTED_OVS_TO_DPDK_MAP = {
44         '2.6.0': '16.07.1',
45         '2.6.1': '16.07.2',
46         '2.7.0': '16.11.1',
47         '2.7.1': '16.11.2',
48         '2.7.2': '16.11.3',
49         '2.8.0': '17.05.2'
50     }
51
52     DEFAULT_OVS = '2.6.0'
53
54     PKILL_TEMPLATE = "pkill %s %s"
55
56     def __init__(self):
57         self.file_path = None
58         self.sriov = []
59         self.first_run = True
60         self.dpdk_nic_bind = ""
61         self.vm_names = []
62         self.name = None
63         self.nfvi_host = []
64         self.nodes = []
65         self.networks = {}
66         self.attrs = {}
67         self.vm_flavor = None
68         self.servers = None
69         self.helper = StandaloneContextHelper()
70         self.vnf_node = Server()
71         self.ovs_properties = {}
72         self.wait_for_vswitchd = 10
73         super(OvsDpdkContext, self).__init__()
74
75     def init(self, attrs):
76         """initializes itself from the supplied arguments"""
77
78         self.name = attrs["name"]
79         self.file_path = attrs.get("file", "pod.yaml")
80
81         self.nodes, self.nfvi_host, self.host_mgmt = \
82             self.helper.parse_pod_file(self.file_path, 'OvsDpdk')
83
84         self.attrs = attrs
85         self.vm_flavor = attrs.get('flavor', {})
86         self.servers = attrs.get('servers', {})
87         self.vm_deploy = attrs.get("vm_deploy", True)
88         self.ovs_properties = attrs.get('ovs_properties', {})
89         # add optional static network definition
90         self.networks = attrs.get("networks", {})
91
92         LOG.debug("Nodes: %r", self.nodes)
93         LOG.debug("NFVi Node: %r", self.nfvi_host)
94         LOG.debug("Networks: %r", self.networks)
95
96     def setup_ovs(self):
97         vpath = self.ovs_properties.get("vpath", "/usr/local")
98         xargs_kill_cmd = self.PKILL_TEMPLATE % ('-9', 'ovs')
99
100         create_from = os.path.join(vpath, 'etc/openvswitch/conf.db')
101         create_to = os.path.join(vpath, 'share/openvswitch/vswitch.ovsschema')
102
103         cmd_list = [
104             "chmod 0666 /dev/vfio/*",
105             "chmod a+x /dev/vfio",
106             "pkill -9 ovs",
107             xargs_kill_cmd,
108             "killall -r 'ovs*'",
109             "mkdir -p {0}/etc/openvswitch".format(vpath),
110             "mkdir -p {0}/var/run/openvswitch".format(vpath),
111             "rm {0}/etc/openvswitch/conf.db".format(vpath),
112             "ovsdb-tool create {0} {1}".format(create_from, create_to),
113             "modprobe vfio-pci",
114             "chmod a+x /dev/vfio",
115             "chmod 0666 /dev/vfio/*",
116         ]
117         for cmd in cmd_list:
118             self.connection.execute(cmd)
119         bind_cmd = "{dpdk_nic_bind} --force -b {driver} {port}"
120         phy_driver = "vfio-pci"
121         for key, port in self.networks.items():
122             vpci = port.get("phy_port")
123             self.connection.execute(bind_cmd.format(dpdk_nic_bind=self.dpdk_nic_bind,
124                                                     driver=phy_driver, port=vpci))
125
126     def start_ovs_serverswitch(self):
127         vpath = self.ovs_properties.get("vpath")
128         pmd_nums = int(self.ovs_properties.get("pmd_threads", 2))
129         ovs_sock_path = '/var/run/openvswitch/db.sock'
130         log_path = '/var/log/openvswitch/ovs-vswitchd.log'
131
132         pmd_mask = hex(sum(2 ** num for num in range(pmd_nums)) << 1)
133         socket0 = self.ovs_properties.get("ram", {}).get("socket_0", "2048")
134         socket1 = self.ovs_properties.get("ram", {}).get("socket_1", "2048")
135
136         ovs_other_config = "ovs-vsctl {0}set Open_vSwitch . other_config:{1}"
137         detach_cmd = "ovs-vswitchd unix:{0}{1} --pidfile --detach --log-file={2}"
138
139         cmd_list = [
140             "mkdir -p /usr/local/var/run/openvswitch",
141             "mkdir -p {}".format(os.path.dirname(log_path)),
142             "ovsdb-server --remote=punix:/{0}/{1}  --pidfile --detach".format(vpath,
143                                                                               ovs_sock_path),
144             ovs_other_config.format("--no-wait ", "dpdk-init=true"),
145             ovs_other_config.format("--no-wait ", "dpdk-socket-mem='%s,%s'" % (socket0, socket1)),
146             detach_cmd.format(vpath, ovs_sock_path, log_path),
147             ovs_other_config.format("", "pmd-cpu-mask=%s" % pmd_mask),
148         ]
149
150         for cmd in cmd_list:
151             LOG.info(cmd)
152             self.connection.execute(cmd)
153         time.sleep(self.wait_for_vswitchd)
154
155     def setup_ovs_bridge_add_flows(self):
156         dpdk_args = ""
157         dpdk_list = []
158         vpath = self.ovs_properties.get("vpath", "/usr/local")
159         version = self.ovs_properties.get('version', {})
160         ovs_ver = [int(x) for x in version.get('ovs', self.DEFAULT_OVS).split('.')]
161         ovs_add_port = \
162             "ovs-vsctl add-port {br} {port} -- set Interface {port} type={type_}{dpdk_args}"
163         ovs_add_queue = "ovs-vsctl set Interface {port} options:n_rxq={queue}"
164         chmod_vpath = "chmod 0777 {0}/var/run/openvswitch/dpdkvhostuser*"
165
166         cmd_dpdk_list = [
167             "ovs-vsctl del-br br0",
168             "rm -rf /usr/local/var/run/openvswitch/dpdkvhostuser*",
169             "ovs-vsctl add-br br0 -- set bridge br0 datapath_type=netdev",
170         ]
171
172         ordered_network = OrderedDict(self.networks)
173         for index, (key, vnf) in enumerate(ordered_network.items()):
174             if ovs_ver >= [2, 7, 0]:
175                 dpdk_args = " options:dpdk-devargs=%s" % vnf.get("phy_port")
176             dpdk_list.append(ovs_add_port.format(br='br0', port='dpdk%s' % vnf.get("port_num", 0),
177                                                  type_='dpdk', dpdk_args=dpdk_args))
178             dpdk_list.append(ovs_add_queue.format(port='dpdk%s' % vnf.get("port_num", 0),
179                                                   queue=self.ovs_properties.get("queues", 4)))
180
181         # Sorting the array to make sure we execute dpdk0... in the order
182         list.sort(dpdk_list)
183         cmd_dpdk_list.extend(dpdk_list)
184
185         # Need to do two for loop to maintain the dpdk/vhost ports.
186         for index, _ in enumerate(ordered_network):
187             cmd_dpdk_list.append(ovs_add_port.format(br='br0', port='dpdkvhostuser%s' % index,
188                                                      type_='dpdkvhostuser', dpdk_args=""))
189
190         for cmd in cmd_dpdk_list:
191             LOG.info(cmd)
192             self.connection.execute(cmd)
193
194         # Fixme: add flows code
195         ovs_flow = "ovs-ofctl add-flow br0 in_port=%s,action=output:%s"
196
197         network_count = len(ordered_network) + 1
198         for in_port, out_port in zip(range(1, network_count),
199                                      range(network_count, network_count * 2)):
200             self.connection.execute(ovs_flow % (in_port, out_port))
201             self.connection.execute(ovs_flow % (out_port, in_port))
202
203         self.connection.execute(chmod_vpath.format(vpath))
204
205     def cleanup_ovs_dpdk_env(self):
206         self.connection.execute("ovs-vsctl del-br br0")
207         self.connection.execute("pkill -9 ovs")
208
209     def check_ovs_dpdk_env(self):
210         self.cleanup_ovs_dpdk_env()
211
212         version = self.ovs_properties.get("version", {})
213         ovs_ver = version.get("ovs", self.DEFAULT_OVS)
214         dpdk_ver = version.get("dpdk", "16.07.2").split('.')
215
216         supported_version = self.SUPPORTED_OVS_TO_DPDK_MAP.get(ovs_ver, None)
217         if supported_version is None or supported_version.split('.')[:2] != dpdk_ver[:2]:
218             raise Exception("Unsupported ovs '{}'. Please check the config...".format(ovs_ver))
219
220         status = self.connection.execute("ovs-vsctl -V | grep -i '%s'" % ovs_ver)[0]
221         if status:
222             deploy = OvsDeploy(self.connection,
223                                get_nsb_option("bin_path"),
224                                self.ovs_properties)
225             deploy.ovs_deploy()
226
227     def deploy(self):
228         """don't need to deploy"""
229
230         # Todo: NFVi deploy (sriov, vswitch, ovs etc) based on the config.
231         if not self.vm_deploy:
232             return
233
234         self.connection = ssh.SSH.from_node(self.host_mgmt)
235         self.dpdk_nic_bind = provision_tool(
236             self.connection,
237             os.path.join(get_nsb_option("bin_path"), "dpdk-devbind.py"))
238
239         # Check dpdk/ovs version, if not present install
240         self.check_ovs_dpdk_env()
241         #    Todo: NFVi deploy (sriov, vswitch, ovs etc) based on the config.
242         StandaloneContextHelper.install_req_libs(self.connection)
243         self.networks = StandaloneContextHelper.get_nic_details(self.connection,
244                                                                 self.networks,
245                                                                 self.dpdk_nic_bind)
246
247         self.setup_ovs()
248         self.start_ovs_serverswitch()
249         self.setup_ovs_bridge_add_flows()
250         self.nodes = self.setup_ovs_dpdk_context()
251         LOG.debug("Waiting for VM to come up...")
252         self.nodes = StandaloneContextHelper.wait_for_vnfs_to_start(self.connection,
253                                                                     self.servers,
254                                                                     self.nodes)
255
256     def undeploy(self):
257
258         if not self.vm_deploy:
259             return
260
261         # Cleanup the ovs installation...
262         self.cleanup_ovs_dpdk_env()
263
264         # Bind nics back to kernel
265         bind_cmd = "{dpdk_nic_bind} --force -b {driver} {port}"
266         for key, port in self.networks.items():
267             vpci = port.get("phy_port")
268             phy_driver = port.get("driver")
269             self.connection.execute(bind_cmd.format(dpdk_nic_bind=self.dpdk_nic_bind,
270                                                     driver=phy_driver, port=vpci))
271
272         # Todo: NFVi undeploy (sriov, vswitch, ovs etc) based on the config.
273         for vm in self.vm_names:
274             Libvirt.check_if_vm_exists_and_delete(vm, self.connection)
275
276     def _get_server(self, attr_name):
277         """lookup server info by name from context
278
279         Keyword arguments:
280         attr_name -- A name for a server listed in nodes config file
281         """
282         node_name, name = self.split_name(attr_name)
283         if name is None or self.name != name:
284             return None
285
286         matching_nodes = (n for n in self.nodes if n["name"] == node_name)
287         try:
288             # A clone is created in order to avoid affecting the
289             # original one.
290             node = dict(next(matching_nodes))
291         except StopIteration:
292             return None
293
294         try:
295             duplicate = next(matching_nodes)
296         except StopIteration:
297             pass
298         else:
299             raise ValueError("Duplicate nodes!!! Nodes: %s %s",
300                              (node, duplicate))
301
302         node["name"] = attr_name
303         return node
304
305     def _get_network(self, attr_name):
306         if not isinstance(attr_name, collections.Mapping):
307             network = self.networks.get(attr_name)
308
309         else:
310             # Don't generalize too much  Just support vld_id
311             vld_id = attr_name.get('vld_id', {})
312             # for standalone context networks are dicts
313             iter1 = (n for n in self.networks.values() if n.get('vld_id') == vld_id)
314             network = next(iter1, None)
315
316         if network is None:
317             return None
318
319         result = {
320             # name is required
321             "name": network["name"],
322             "vld_id": network.get("vld_id"),
323             "segmentation_id": network.get("segmentation_id"),
324             "network_type": network.get("network_type"),
325             "physical_network": network.get("physical_network"),
326         }
327         return result
328
329     def configure_nics_for_ovs_dpdk(self):
330         portlist = OrderedDict(self.networks)
331         for key, ports in portlist.items():
332             mac = StandaloneContextHelper.get_mac_address()
333             portlist[key].update({'mac': mac})
334         self.networks = portlist
335         LOG.info("Ports %s" % self.networks)
336
337     def _enable_interfaces(self, index, vfs, cfg):
338         vpath = self.ovs_properties.get("vpath", "/usr/local")
339         vf = self.networks[vfs[0]]
340         port_num = vf.get('port_num', 0)
341         vpci = PciAddress.parse_address(vf['vpci'].strip(), multi_line=True)
342         # Generate the vpci for the interfaces
343         slot = index + port_num + 10
344         vf['vpci'] = \
345             "{}:{}:{:02x}.{}".format(vpci.domain, vpci.bus, slot, vpci.function)
346         Libvirt.add_ovs_interface(vpath, port_num, vf['vpci'], vf['mac'], str(cfg))
347
348     def setup_ovs_dpdk_context(self):
349         nodes = []
350
351         self.configure_nics_for_ovs_dpdk()
352
353         for index, (key, vnf) in enumerate(OrderedDict(self.servers).items()):
354             cfg = '/tmp/vm_ovs_%d.xml' % index
355             vm_name = "vm_%d" % index
356
357             # 1. Check and delete VM if already exists
358             Libvirt.check_if_vm_exists_and_delete(vm_name, self.connection)
359
360             vcpu, mac = Libvirt.build_vm_xml(self.connection, self.vm_flavor, cfg, vm_name, index)
361             # 2: Cleanup already available VMs
362             for idx, (vkey, vfs) in enumerate(OrderedDict(vnf["network_ports"]).items()):
363                 if vkey == "mgmt":
364                     continue
365                 self._enable_interfaces(index, vfs, cfg)
366
367             # copy xml to target...
368             self.connection.put(cfg, cfg)
369
370             #    FIXME: launch through libvirt
371             LOG.info("virsh create ...")
372             Libvirt.virsh_create_vm(self.connection, cfg)
373
374             #    5: Tunning for better performace
375             Libvirt.pin_vcpu_for_perf(self.connection, vm_name, vcpu)
376             self.vm_names.append(vm_name)
377
378             # build vnf node details
379             nodes.append(self.vnf_node.generate_vnf_instance(self.vm_flavor,
380                                                              self.networks,
381                                                              self.host_mgmt.get('ip'),
382                                                              key, vnf, mac))
383
384         return nodes