1 # Copyright 2015-2016 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):
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
42 module_base_name = os.path.basename(os.path.splitext(module)[0])
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)
51 if module.endswith('.ko'):
52 tasks.run_task(['sudo', 'insmod', module], self._logger,
53 'Insmod module \'%s\'...' % module_base_name, True)
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
63 def insert_modules(self, modules):
64 """Method inserts list of modules.
66 :param modules: a list of modules to be inserted
68 for module in modules:
69 self.insert_module(module)
71 def insert_module_group(self, module_group, path_prefix):
72 """Ensure all modules in a group are inserted into the system.
74 :param module_group: A name of configuration item containing a list
76 :param path_prefix: A name of directory which contains given
79 for (path_suffix, module) in module_group:
80 self.insert_module(os.path.join(path_prefix, path_suffix, '%s.ko' % module))
82 def remove_module(self, module):
83 """Removes a single module.
85 :param module: a name of kernel module
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])
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)
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)
110 def remove_modules(self):
111 """Removes all modules that have been previously inserted.
113 # remove modules in reverse order to respect their dependencies
114 for module in reversed(self._modules):
115 self.remove_module(module)
117 def is_module_inserted(self, module):
118 """Check if a module is inserted on system.
120 :param module: a name of kernel module
122 module_base_name = os.path.basename(os.path.splitext(module)[0])
124 return self.get_module_details(module_base_name) != None
127 def get_module_details(module):
128 """Return details about given module
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.
134 # get list of modules from kernel
135 with open('/proc/modules') as mod_file:
136 loaded_mods = mod_file.readlines()
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('-', '_'):