pkt_gen: Reporting FPS and MBPS from Spirent Testcenter
[vswitchperf.git] / tools / module_manager.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 """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):
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         """
42         module_base_name = os.path.basename(os.path.splitext(module)[0])
43
44         if self.is_module_inserted(module):
45             self._logger.info('Module already loaded \'%s\'.', module_base_name)
46             # add it to internal list, so we can try to remove it at the end
47             self._modules.append(module)
48             return
49
50         try:
51             if module.endswith('.ko'):
52                 tasks.run_task(['sudo', 'insmod', module], self._logger,
53                                'Insmod module \'%s\'...' % module_base_name, True)
54             else:
55                 tasks.run_task(['sudo', 'modprobe', module], self._logger,
56                                'Modprobe module \'%s\'...' % module_base_name, True)
57             self._modules.append(module)
58         except subprocess.CalledProcessError:
59             # in case of error, show full module name
60             self._logger.error('Unable to insert module \'%s\'.', module)
61             raise  # fail catastrophically
62
63     def insert_modules(self, modules):
64         """Method inserts list of modules.
65
66         :param modules: a list of modules to be inserted
67         """
68         for module in modules:
69             self.insert_module(module)
70
71     def insert_module_group(self, module_group, path_prefix):
72         """Ensure all modules in a group are inserted into the system.
73
74         :param module_group: A name of configuration item containing a list
75             of module names
76         :param path_prefix: A name of directory which contains given
77             group of modules
78         """
79         for (path_suffix, module) in module_group:
80             self.insert_module(os.path.join(path_prefix, path_suffix, '%s.ko' % module))
81
82     def remove_module(self, module):
83         """Removes a single module.
84
85         :param module: a name of kernel module
86         """
87         if self.is_module_inserted(module):
88             # get module base name, i.e strip path and .ko suffix if possible
89             module_base_name = os.path.basename(os.path.splitext(module)[0])
90
91             try:
92                 self._logger.info('Removing module \'%s\'...', module_base_name)
93                 subprocess.check_call('sudo rmmod {}'.format(module_base_name),
94                                       shell=True, stderr=subprocess.DEVNULL)
95                 # in case that module was loaded automatically by modprobe
96                 # to solve dependecies, then it is not in internal list of modules
97                 if module in self._modules:
98                     self._modules.remove(module)
99             except subprocess.CalledProcessError:
100                 # in case of error, show full module name...
101                 self._logger.info('Unable to remove module \'%s\'.', module)
102                 # ...and list of dependend modules, if there are any
103                 module_details = self.get_module_details(module_base_name)
104                 if module_details:
105                     mod_dep = module_details.split(' ')[3].rstrip(',')
106                     if mod_dep[0] != '-':
107                         self._logger.debug('Module \'%s\' is used by module(s) \'%s\'.',
108                                            module_base_name, mod_dep)
109
110     def remove_modules(self):
111         """Removes all modules that have been previously inserted.
112         """
113         # remove modules in reverse order to respect their dependencies
114         for module in reversed(self._modules):
115             self.remove_module(module)
116
117     def is_module_inserted(self, module):
118         """Check if a module is inserted on system.
119
120         :param module: a name of kernel module
121         """
122         module_base_name = os.path.basename(os.path.splitext(module)[0])
123
124         return self.get_module_details(module_base_name) != None
125
126     @staticmethod
127     def get_module_details(module):
128         """Return details about given module
129
130         :param module: a name of kernel module
131         :returns: In case that module is loaded in OS, then corresponding
132             line from /proc/modules will be returned. Otherwise it returns None.
133         """
134         # get list of modules from kernel
135         with open('/proc/modules') as mod_file:
136             loaded_mods = mod_file.readlines()
137
138         # check if module is loaded
139         for line in loaded_mods:
140             # underscores '_' and dashes '-' in module names are interchangeable, so we
141             # have to normalize module names before comparision
142             if line.split(' ')[0].replace('-', '_') == module.replace('-', '_'):
143                 return line
144
145         return None