bugfix: Fix errors related to removal of kernel modules
[vswitchperf.git] / src / dpdk / dpdk.py
1 # Copyright 2015-2016 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 """Automation of system configuration for DPDK use.
16
17 Parts of this based on ``tools/dpdk_nic_bind.py`` script from Intel(R)
18 DPDK.
19 """
20
21 from sys import platform as _platform
22
23 import os
24 import subprocess
25 import logging
26 import locale
27
28 from tools import tasks
29 from conf import settings
30 from tools.module_manager import ModuleManager
31
32 _LOGGER = logging.getLogger(__name__)
33 RTE_PCI_TOOL = os.path.join(
34     settings.getValue('RTE_SDK'), 'tools', 'dpdk_nic_bind.py')
35
36 _DPDK_MODULE_MANAGER = ModuleManager()
37 #
38 # system management
39 #
40
41
42 def init():
43     """Setup system for DPDK.
44     """
45     if not _is_linux():
46         _LOGGER.error('Not running on a compatible Linux version. Exiting...')
47         return
48     _insert_modules()
49     _remove_vhost_net()
50     _bind_nics()
51
52
53 def cleanup():
54     """Setup system for DPDK.
55     """
56     if not _is_linux():
57         _LOGGER.error('Not running on a compatible Linux version. Exiting...')
58         return
59
60     _unbind_nics()
61     _remove_modules()
62     _vhost_user_cleanup()
63
64 #
65 # basic compatibility test
66 #
67
68 def _is_linux():
69     """Check if running on Linux.
70
71     Many of the functions in this file rely on features commonly found
72     only on Linux (i.e. ``/proc`` is not present on FreeBSD). Hence, this
73     check is important to ensure someone doesn't run this on an incompatible
74     OS or distro.
75     """
76     return _platform.startswith('linux') and os.path.isdir('/proc')
77
78 #
79 # module management
80 #
81
82 def _insert_modules():
83     """Ensure required modules are inserted on system.
84     """
85
86     _DPDK_MODULE_MANAGER.insert_modules(settings.getValue('SYS_MODULES'))
87
88     mod_path_prefix = settings.getValue('OVS_DIR')
89     _DPDK_MODULE_MANAGER.insert_module_group(settings.getValue('OVS_MODULES'),
90                                              mod_path_prefix)
91     if 'vfio-pci' not in settings.getValue('DPDK_MODULES'):
92         mod_path_prefix = os.path.join(settings.getValue('RTE_SDK'),
93                                        settings.getValue('RTE_TARGET'))
94         _DPDK_MODULE_MANAGER.insert_module_group(settings.getValue('DPDK_MODULES'),
95                                                  mod_path_prefix)
96     else:
97         _DPDK_MODULE_MANAGER.insert_modules(settings.getValue('DPDK_MODULES'))
98
99 def _remove_modules():
100     """Ensure required modules are removed from system.
101     """
102     _DPDK_MODULE_MANAGER.remove_modules()
103
104 #
105 # vhost specific modules management
106 #
107
108 def insert_vhost_modules():
109     """Inserts VHOST related kernel modules
110     """
111     mod_path_prefix = os.path.join(settings.getValue('RTE_SDK'),
112                                    'lib',
113                                    'librte_vhost')
114     _DPDK_MODULE_MANAGER.insert_module_group(settings.getValue('VHOST_MODULE'), mod_path_prefix)
115
116
117 def remove_vhost_modules():
118     """Removes all VHOST related kernel modules
119     """
120     # all modules are removed automatically by _remove_modules() method
121     pass
122
123
124 #
125 # 'vhost-net' module cleanup
126 #
127
128 def _remove_vhost_net():
129     """Remove vhost-net driver and file.
130     """
131     _DPDK_MODULE_MANAGER.remove_module('vhost-net')
132     try:
133         tasks.run_task(['sudo', 'rm', '-f', '/dev/vhost-net'], _LOGGER,
134                        'Removing \'/dev/vhost-net\' directory...', True)
135     except subprocess.CalledProcessError:
136         _LOGGER.error('Unable to remove directory \'/dev/vhost-net\'.')
137
138 #
139 # Vhost-user cleanup
140 #
141
142 def _vhost_user_cleanup():
143     """Remove files created by vhost-user tests.
144     """
145     for sock in settings.getValue('VHOST_USER_SOCKS'):
146         if os.path.exists(sock):
147             try:
148                 tasks.run_task(['sudo', 'rm', sock],
149                                _LOGGER,
150                                'Deleting vhost-user socket \'%s\'...' %
151                                sock,
152                                True)
153
154             except subprocess.CalledProcessError:
155                 _LOGGER.error('Unable to delete vhost-user socket \'%s\'.',
156                               sock)
157                 continue
158 #
159 # NIC management
160 #
161
162
163 def _bind_nics():
164     """Bind NICs using the Intel DPDK ``dpdk_nic_bind.py`` tool.
165     """
166     try:
167         _driver = 'igb_uio'
168         if 'vfio-pci' in settings.getValue('DPDK_MODULES'):
169             _driver = 'vfio-pci'
170             tasks.run_task(['sudo', 'chmod', 'a+x', '/dev/vfio'],
171                            _LOGGER, 'Setting VFIO permissions .. a+x',
172                            True)
173             tasks.run_task(['sudo', 'chmod', '-R', '666', '/dev/vfio/'],
174                            _LOGGER, 'Setting VFIO permissions .. 0666',
175                            True)
176
177         tasks.run_task(['sudo', RTE_PCI_TOOL, '--bind=' + _driver] +
178                        settings.getValue('WHITELIST_NICS'), _LOGGER,
179                        'Binding NICs %s...' %
180                        settings.getValue('WHITELIST_NICS'),
181                        True)
182     except subprocess.CalledProcessError:
183         _LOGGER.error('Unable to bind NICs %s',
184                       str(settings.getValue('WHITELIST_NICS')))
185
186 def _unbind_nics_get_driver():
187     """Check what driver the NICs should be bound to
188        after unbinding them from DPDK.
189     """
190     _driver_list = []
191     _output = subprocess.check_output([os.path.expanduser(RTE_PCI_TOOL), '--status'])
192     _my_encoding = locale.getdefaultlocale()[1]
193     for line in _output.decode(_my_encoding).split('\n'):
194         for nic in settings.getValue('WHITELIST_NICS'):
195             if nic in line:
196                 _driver_list.append((line.split("unused=", 1)[1]))
197     return _driver_list
198
199 def _unbind_nics():
200     """Unbind NICs using the Intel DPDK ``dpdk_nic_bind.py`` tool.
201     """
202     nic_drivers = _unbind_nics_get_driver()
203     try:
204         tasks.run_task(['sudo', RTE_PCI_TOOL, '--unbind'] +
205                        settings.getValue('WHITELIST_NICS'), _LOGGER,
206                        'Unbinding NICs %s...' %
207                        str(settings.getValue('WHITELIST_NICS')),
208                        True)
209     except subprocess.CalledProcessError:
210         _LOGGER.error('Unable to unbind NICs %s',
211                       str(settings.getValue('WHITELIST_NICS')))
212     # Rebind NICs to their original drivers
213     # using the Intel DPDK ``dpdk_nic_bind.py`` tool.
214     for i, nic in enumerate(settings.getValue('WHITELIST_NICS')):
215         try:
216             if nic_drivers[i] != '':
217                 tasks.run_task(['sudo', RTE_PCI_TOOL, '--bind',
218                                 nic_drivers[i], nic],
219                                _LOGGER, 'Binding NIC %s...' %
220                                nic,
221                                True)
222         except subprocess.CalledProcessError:
223             _LOGGER.error('Unable to bind NICs %s to drivers %s',
224                           str(settings.getValue('WHITELIST_NICS')),
225                           nic_drivers)
226
227 class Dpdk(object):
228     """A context manager for the system init/cleanup.
229     """
230     def __enter__(self):
231         _LOGGER.info('Setting up DPDK')
232         init()
233         return self
234
235     def __exit__(self, type_, value, traceback):
236         _LOGGER.info('Cleaning up DPDK')
237         cleanup()