1 # Copyright 2015 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.
20 from tools import tasks
22 class ModuleManager(object):
23 """Simple module manager which acts as system wrapper for Kernel Modules.
26 _logger = logging.getLogger(__name__)
33 def insert_modules(self, modules):
34 """Method inserts list of modules. In case that module name ends
35 with .ko suffix then insmod will be used for its insertion. Otherwise
36 modprobe will be called.
40 self._modules = modules
41 for module in modules:
42 if ModuleManager.is_module_inserted(module):
46 if module.endswith('.ko'):
47 tasks.run_task(['sudo', 'insmod', module], self._logger,
48 'Insmod module \'%s\'...' % module, True)
50 tasks.run_task(['sudo', 'modprobe', module], self._logger,
51 'Modprobe module \'%s\'...' % module, True)
53 except subprocess.CalledProcessError:
54 self._logger.error('Unable to insert module \'%s\'.', module)
55 raise # fail catastrophically
57 def remove_modules(self):
58 """Removes all modules that have been previously instereted.
60 for module in self._modules:
61 # first check if module is loaded
62 if not ModuleManager.is_module_inserted(module):
66 # rmmod supports both simple module name and full module path
68 tasks.run_task(['sudo', 'rmmod', module], self._logger,
69 'Removing module \'%s\'...' % module, True)
70 except subprocess.CalledProcessError:
71 self._logger.error('Unable to remove module \'%s\'.', module)
75 def is_module_inserted(module):
76 """Check if a module is inserted on system.
78 # get module base name, i.e strip path and .ko suffix if possible
79 module_base_name = module.split('.')[0].split('/').pop()
81 # get list of modules from kernel
82 with open('/proc/modules') as mod_file:
83 loaded_mods = mod_file.readlines()
85 # first check if module is loaded
86 for line in loaded_mods:
87 if line.startswith(module_base_name):