Tools: Dockerfile to run VSPERF in a Container.
[vswitchperf.git] / tools / module_manager.py
1 # Copyright 2015-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 """Simple kernel module manager implementation.
16 """
17 import os
18 import subprocess
19 import logging
20
21 from tools import tasks
22
23 class ModuleManager(object):
24     """Simple module manager which acts as system wrapper for Kernel Modules.
25     """
26
27     _logger = logging.getLogger(__name__)
28
29     def __init__(self):
30         """Initializes data
31         """
32         self._modules = []
33
34     def insert_module(self, module, auto_remove=True):
35         """Method inserts given module.
36
37         In case that module name ends with .ko suffix then insmod will
38         be used for its insertion. Otherwise modprobe will be called.
39
40         :param module: a name of kernel module
41         :param auto_remove: if True (by default), then module will be
42             automatically removed by remove_modules() method
43         """
44         module_base_name = os.path.basename(os.path.splitext(module)[0])
45
46         if self.is_module_inserted(module):
47             self._logger.info('Module already loaded \'%s\'.', module_base_name)
48             # add it to internal list, so we can try to remove it at the end
49             if auto_remove:
50                 self._modules.append(module)
51             return
52
53         try:
54             if module.endswith('.ko'):
55                 # load module dependecies first, but suppress automatic
56                 # module removal at the end; Just for case, that module
57                 # depends on generic module
58                 for depmod in self.get_module_dependecies(module):
59                     self.insert_module(depmod, auto_remove=False)
60
61                 tasks.run_task(['sudo', 'insmod', module], self._logger,
62                                'Insmod module \'%s\'...' % module_base_name, True)
63             else:
64                 tasks.run_task(['sudo', 'modprobe', module], self._logger,
65                                'Modprobe module \'%s\'...' % module_base_name, True)
66             if auto_remove:
67                 self._modules.append(module)
68         except subprocess.CalledProcessError:
69             # in case of error, show full module name
70             self._logger.error('Unable to insert module \'%s\'.', module)
71             raise  # fail catastrophically
72
73     def insert_modules(self, modules):
74         """Method inserts list of modules.
75
76         :param modules: a list of modules to be inserted
77         """
78         for module in modules:
79             self.insert_module(module)
80
81     def remove_module(self, module):
82         """Removes a single module.
83
84         :param module: a name of kernel module
85         """
86         if self.is_module_inserted(module):
87             # get module base name, i.e strip path and .ko suffix if possible
88             module_base_name = os.path.basename(os.path.splitext(module)[0])
89
90             try:
91                 self._logger.info('Removing module \'%s\'...', module_base_name)
92                 subprocess.check_call('sudo rmmod {}'.format(module_base_name),
93                                       shell=True, stderr=subprocess.DEVNULL)
94                 # in case that module was loaded automatically by modprobe
95                 # to solve dependecies, then it is not in internal list of modules
96                 if module in self._modules:
97                     self._modules.remove(module)
98             except subprocess.CalledProcessError:
99                 # in case of error, show full module name...
100                 self._logger.info('Unable to remove module \'%s\'.', module)
101                 # ...and list of dependend modules, if there are any
102                 module_details = self.get_module_details(module_base_name)
103                 if module_details:
104                     mod_dep = module_details.split(' ')[3].rstrip(',')
105                     if mod_dep[0] != '-':
106                         self._logger.debug('Module \'%s\' is used by module(s) \'%s\'.',
107                                            module_base_name, mod_dep)
108
109     def remove_modules(self):
110         """Removes all modules that have been previously inserted.
111         """
112         # remove modules in reverse order to respect their dependencies
113         for module in reversed(self._modules):
114             self.remove_module(module)
115
116     def is_module_inserted(self, module):
117         """Check if a module is inserted on system.
118
119         :param module: a name of kernel module
120         """
121         module_base_name = os.path.basename(os.path.splitext(module)[0])
122
123         return self.get_module_details(module_base_name) != None
124
125     @staticmethod
126     def get_module_details(module):
127         """Return details about given module
128
129         :param module: a name of kernel module
130         :returns: In case that module is loaded in OS, then corresponding
131             line from /proc/modules will be returned. Otherwise it returns None.
132         """
133         # get list of modules from kernel
134         with open('/proc/modules') as mod_file:
135             loaded_mods = mod_file.readlines()
136
137         # check if module is loaded
138         for line in loaded_mods:
139             # underscores '_' and dashes '-' in module names are interchangeable, so we
140             # have to normalize module names before comparision
141             if line.split(' ')[0].replace('-', '_') == module.replace('-', '_'):
142                 return line
143
144         return None
145
146     def get_module_dependecies(self, module):
147         """Return list of modules, which must be loaded before module itself
148
149         :param module: a name of kernel module
150         :returns: In case that module has any dependencies, then list of module
151             names will be returned. Otherwise it returns empty list, i.e. [].
152         """
153         deps = ''
154         try:
155             # get list of module dependecies from kernel
156             deps = subprocess.check_output('modinfo -F depends {}'.format(module),
157                                            shell=True).decode().rstrip('\n')
158         except subprocess.CalledProcessError:
159             # in case of error, show full module name...
160             self._logger.info('Unable to get list of dependecies for module \'%s\'.', module)
161             # ...and try to continue, just for case that dependecies are already loaded
162
163         if deps:
164             return deps.split(',')
165         else:
166             return []