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 KernelModuleInsertMode(object):
23 """Module manager type of insert definition.
26 INSMOD = 2 #NOT IMPLEMENTED
28 class ModuleManager(object):
29 """Simple module manager which acts as system wrapper for Kernel Modules.
32 _logger = logging.getLogger(__name__)
34 def __init__(self, insert_mode=KernelModuleInsertMode.MODPROBE):
35 """Initializes data and sets insert mode.
37 :param insert_mode: insert mode defines how modules are going to
38 be inserted in system.
41 self._insert_mode = insert_mode
43 def insert_modules(self, modules):
44 """Method inserts list of modules using defined insert mode.
46 :param modules: list of modules to be inserted. Each element on
47 list should represent format which is expected
48 by KernelModuleInsertMode (e.g. for MODPROBE it
49 would be module name).
53 self._modules = modules
54 for module in modules:
55 if ModuleManager.is_module_inserted(module):
59 if self._insert_mode == KernelModuleInsertMode.MODPROBE:
60 tasks.run_task(['sudo', 'modprobe', module], self._logger,
61 'Inserting module \'%s\'...' % module, True)
64 "Kernel module insert mode NOT IMPLEMENTED.")
67 except subprocess.CalledProcessError:
68 self._logger.error('Unable to insert module \'%s\'.', module)
69 raise # fail catastrophically
71 def remove_modules(self):
72 """Removes all modules that have been previously instereted.
74 for module in self._modules:
75 # first check if module is loaded
76 if not ModuleManager.is_module_inserted(module):
80 tasks.run_task(['sudo', 'rmmod', module], self._logger,
81 'Removing module \'%s\'...' % module, True)
82 except subprocess.CalledProcessError:
83 self._logger.error('Unable to remove module \'%s\'.', module)
87 def is_module_inserted(module):
88 """Check if a module is inserted on system.
90 with open('/proc/modules') as mod_file:
91 loaded_mods = mod_file.readlines()
93 # first check if module is loaded
94 for line in loaded_mods:
95 if line.startswith(module):