Merge "Add test case sample to enable mixed network"
[yardstick.git] / yardstick / benchmark / contexts / standalone / sriov.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 from collections import OrderedDict
20
21 from yardstick import ssh
22 from yardstick.network_services.utils import get_nsb_option
23 from yardstick.network_services.utils import provision_tool
24 from yardstick.benchmark.contexts.base import Context
25 from yardstick.benchmark.contexts.standalone.model import Libvirt
26 from yardstick.benchmark.contexts.standalone.model import StandaloneContextHelper
27 from yardstick.benchmark.contexts.standalone.model import Server
28 from yardstick.network_services.utils import PciAddress
29
30 LOG = logging.getLogger(__name__)
31
32
33 class SriovContext(Context):
34     """ This class handles SRIOV standalone nodes - VM running on Non-Managed NFVi
35     Configuration: sr-iov
36     """
37
38     __context_type__ = "StandaloneSriov"
39
40     def __init__(self):
41         self.file_path = None
42         self.sriov = []
43         self.first_run = True
44         self.dpdk_devbind = ''
45         self.vm_names = []
46         self.nfvi_host = []
47         self.nodes = []
48         self.networks = {}
49         self.attrs = {}
50         self.vm_flavor = None
51         self.servers = None
52         self.helper = StandaloneContextHelper()
53         self.vnf_node = Server()
54         self.drivers = []
55         super(SriovContext, self).__init__()
56
57     def init(self, attrs):
58         """initializes itself from the supplied arguments"""
59         super(SriovContext, self).init(attrs)
60
61         self.file_path = attrs.get("file", "pod.yaml")
62
63         self.nodes, self.nfvi_host, self.host_mgmt = \
64             self.helper.parse_pod_file(self.file_path, 'Sriov')
65
66         self.attrs = attrs
67         self.vm_flavor = attrs.get('flavor', {})
68         self.servers = attrs.get('servers', {})
69         self.vm_deploy = attrs.get("vm_deploy", True)
70         # add optional static network definition
71         self.networks = attrs.get("networks", {})
72
73         LOG.debug("Nodes: %r", self.nodes)
74         LOG.debug("NFVi Node: %r", self.nfvi_host)
75         LOG.debug("Networks: %r", self.networks)
76
77     def deploy(self):
78         """don't need to deploy"""
79
80         # Todo: NFVi deploy (sriov, vswitch, ovs etc) based on the config.
81         if not self.vm_deploy:
82             return
83
84         self.connection = ssh.SSH.from_node(self.host_mgmt)
85         self.dpdk_devbind = provision_tool(
86             self.connection,
87             os.path.join(get_nsb_option("bin_path"), "dpdk-devbind.py"))
88
89         #    Todo: NFVi deploy (sriov, vswitch, ovs etc) based on the config.
90         StandaloneContextHelper.install_req_libs(self.connection)
91         self.networks = StandaloneContextHelper.get_nic_details(
92             self.connection, self.networks, self.dpdk_devbind)
93         self.nodes = self.setup_sriov_context()
94
95         LOG.debug("Waiting for VM to come up...")
96         self.nodes = StandaloneContextHelper.wait_for_vnfs_to_start(self.connection,
97                                                                     self.servers,
98                                                                     self.nodes)
99
100     def undeploy(self):
101         """don't need to undeploy"""
102
103         if not self.vm_deploy:
104             return
105
106         # Todo: NFVi undeploy (sriov, vswitch, ovs etc) based on the config.
107         for vm in self.vm_names:
108             Libvirt.check_if_vm_exists_and_delete(vm, self.connection)
109
110         # Bind nics back to kernel
111         for ports in self.networks.values():
112             # enable VFs for given...
113             build_vfs = "echo 0 > /sys/bus/pci/devices/{0}/sriov_numvfs"
114             self.connection.execute(build_vfs.format(ports.get('phy_port')))
115
116     def _get_server(self, attr_name):
117         """lookup server info by name from context
118
119         Keyword arguments:
120         attr_name -- A name for a server listed in nodes config file
121         """
122         node_name, name = self.split_name(attr_name)
123         if name is None or self.name != name:
124             return None
125
126         matching_nodes = (n for n in self.nodes if n["name"] == node_name)
127         try:
128             # A clone is created in order to avoid affecting the
129             # original one.
130             node = dict(next(matching_nodes))
131         except StopIteration:
132             return None
133
134         try:
135             duplicate = next(matching_nodes)
136         except StopIteration:
137             pass
138         else:
139             raise ValueError("Duplicate nodes!!! Nodes: %s %s" %
140                              (node, duplicate))
141
142         node["name"] = attr_name
143         return node
144
145     def _get_network(self, attr_name):
146         if not isinstance(attr_name, collections.Mapping):
147             network = self.networks.get(attr_name)
148
149         else:
150             # Don't generalize too much  Just support vld_id
151             vld_id = attr_name.get('vld_id', {})
152             # for standalone context networks are dicts
153             iter1 = (n for n in self.networks.values() if n.get('vld_id') == vld_id)
154             network = next(iter1, None)
155
156         if network is None:
157             return None
158
159         result = {
160             # name is required
161             "name": network["name"],
162             "vld_id": network.get("vld_id"),
163             "segmentation_id": network.get("segmentation_id"),
164             "network_type": network.get("network_type"),
165             "physical_network": network.get("physical_network"),
166         }
167         return result
168
169     def configure_nics_for_sriov(self):
170         vf_cmd = "ip link set {0} vf 0 mac {1}"
171         for ports in self.networks.values():
172             host_driver = ports.get('driver')
173             if host_driver not in self.drivers:
174                 self.connection.execute("rmmod %svf" % host_driver)
175                 self.drivers.append(host_driver)
176
177             # enable VFs for given...
178             build_vfs = "echo 1 > /sys/bus/pci/devices/{0}/sriov_numvfs"
179             self.connection.execute(build_vfs.format(ports.get('phy_port')))
180
181             # configure VFs...
182             mac = StandaloneContextHelper.get_mac_address()
183             interface = ports.get('interface')
184             if interface is not None:
185                 self.connection.execute(vf_cmd.format(interface, mac))
186
187             vf_pci = self._get_vf_data(ports.get('phy_port'), mac, interface)
188             ports.update({
189                 'vf_pci': vf_pci,
190                 'mac': mac
191             })
192
193         LOG.info('Ports %s', self.networks)
194
195     def _enable_interfaces(self, index, idx, vfs, cfg):
196         vf_spoofchk = "ip link set {0} vf 0 spoofchk off"
197
198         vf = self.networks[vfs[0]]
199         vpci = PciAddress(vf['vpci'].strip())
200         # Generate the vpci for the interfaces
201         slot = index + idx + 10
202         vf['vpci'] = \
203             "{}:{}:{:02x}.{}".format(vpci.domain, vpci.bus, slot, vpci.function)
204         Libvirt.add_sriov_interfaces(
205             vf['vpci'], vf['vf_pci']['vf_pci'], vf['mac'], str(cfg))
206         self.connection.execute("ifconfig %s up" % vf['interface'])
207         self.connection.execute(vf_spoofchk.format(vf['interface']))
208
209     def setup_sriov_context(self):
210         nodes = []
211
212         #   1 : modprobe host_driver with num_vfs
213         self.configure_nics_for_sriov()
214
215         for index, (key, vnf) in enumerate(OrderedDict(self.servers).items()):
216             cfg = '/tmp/vm_sriov_%s.xml' % str(index)
217             vm_name = "vm_%s" % str(index)
218
219             # 1. Check and delete VM if already exists
220             Libvirt.check_if_vm_exists_and_delete(vm_name, self.connection)
221
222             _, mac = Libvirt.build_vm_xml(self.connection, self.vm_flavor, cfg, vm_name, index)
223             # 2: Cleanup already available VMs
224             for idx, (vkey, vfs) in enumerate(OrderedDict(vnf["network_ports"]).items()):
225                 if vkey == "mgmt":
226                     continue
227                 self._enable_interfaces(index, idx, vfs, cfg)
228
229             # copy xml to target...
230             self.connection.put(cfg, cfg)
231
232             # NOTE: launch through libvirt
233             LOG.info("virsh create ...")
234             Libvirt.virsh_create_vm(self.connection, cfg)
235
236             self.vm_names.append(vm_name)
237
238             # build vnf node details
239             nodes.append(self.vnf_node.generate_vnf_instance(self.vm_flavor,
240                                                              self.networks,
241                                                              self.host_mgmt.get('ip'),
242                                                              key, vnf, mac))
243
244         return nodes
245
246     def _get_vf_data(self, value, vfmac, pfif):
247         vf_data = {
248             "mac": vfmac,
249             "pf_if": pfif
250         }
251         vfs = StandaloneContextHelper.get_virtual_devices(self.connection, value)
252         for k, v in vfs.items():
253             m = PciAddress(k.strip())
254             m1 = PciAddress(value.strip())
255             if m.bus == m1.bus:
256                 vf_data.update({"vf_pci": str(v)})
257                 break
258
259         return vf_data