1 # Copyright 2015-2017 Intel Corporation.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
15 """Simple kernel module manager implementation.
21 from tools import tasks
23 class ModuleManager(object):
24 """Simple module manager which acts as system wrapper for Kernel Modules.
27 _logger = logging.getLogger(__name__)
34 def insert_module(self, module, auto_remove=True):
35 """Method inserts given module.
37 In case that module name ends with .ko suffix then insmod will
38 be used for its insertion. Otherwise modprobe will be called.
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
44 module_base_name = os.path.basename(os.path.splitext(module)[0])
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
50 self._modules.append(module)
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)
61 tasks.run_task(['sudo', 'insmod', module], self._logger,
62 'Insmod module \'%s\'...' % module_base_name, True)
64 tasks.run_task(['sudo', 'modprobe', module], self._logger,
65 'Modprobe module \'%s\'...' % module_base_name, True)
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
73 def insert_modules(self, modules):
74 """Method inserts list of modules.
76 :param modules: a list of modules to be inserted
78 for module in modules:
79 self.insert_module(module)
81 def remove_module(self, module):
82 """Removes a single module.
84 :param module: a name of kernel module
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])
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)
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)
109 def remove_modules(self):
110 """Removes all modules that have been previously inserted.
112 # remove modules in reverse order to respect their dependencies
113 for module in reversed(self._modules):
114 self.remove_module(module)
116 def is_module_inserted(self, module):
117 """Check if a module is inserted on system.
119 :param module: a name of kernel module
121 module_base_name = os.path.basename(os.path.splitext(module)[0])
123 return self.get_module_details(module_base_name) != None
126 def get_module_details(module):
127 """Return details about given module
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.
133 # get list of modules from kernel
134 with open('/proc/modules') as mod_file:
135 loaded_mods = mod_file.readlines()
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('-', '_'):
146 def get_module_dependecies(self, module):
147 """Return list of modules, which must be loaded before module itself
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. [].
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
164 return deps.split(',')