Debian Codegraph @

ansible_collections/community/general/plugins/modules/modprobe.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, David Stygstra <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: modprobe
11 short_description: Load or unload kernel modules
12 author:
13 - David Stygstra (@stygstra)
14 - Julien Dauphant (@jdauphant)
15 - Matt Jeffery (@mattjeffery)
16 description:
17 - Load or unload kernel modules.
18 extends_documentation_fragment:
19 - community.general._attributes
20 attributes:
21 check_mode:
22 support: full
23 diff_mode:
24 support: none
25 options:
26 name:
27 type: str
28 required: true
29 description:
30 - Name of kernel module to manage.
31 state:
32 type: str
33 description:
34 - Whether the module should be present or absent.
35 choices: [absent, present]
36 default: present
37 params:
38 type: str
39 description:
40 - Modules parameters.
41 default: ''
42 persistent:
43 type: str
44 choices: [disabled, absent, present]
45 default: disabled
46 version_added: 7.0.0
47 description:
48 - Persistency between reboots for configured module.
49 - This option creates files in C(/etc/modules-load.d/) and C(/etc/modprobe.d/) that make your module configuration persistent
50 during reboots.
51 - If V(present), adds module name to C(/etc/modules-load.d/) and params to C(/etc/modprobe.d/) so the module is loaded
52 on next reboot.
53 - If V(absent), comments out module name from C(/etc/modules-load.d/) and comments out params from C(/etc/modprobe.d/)
54 so the module is not loaded on next reboot.
55 - If V(disabled), does not touch anything and leaves C(/etc/modules-load.d/) and C(/etc/modprobe.d/) as it is.
56 - Note that it is usually a better idea to rely on the automatic module loading by PCI IDs, USB IDs, DMI IDs or similar
57 triggers encoded in the kernel modules themselves instead of configuration like this.
58 - In fact, most modern kernel modules are prepared for automatic loading already.
59 - B(Note:) This option works only with distributions that use C(systemd) when set to values other than V(disabled).
60 """
61
62 EXAMPLES = r"""
63 - name: Add the 802.1q module
64 community.general.modprobe:
65 name: 8021q
66 state: present
67
68 - name: Add the dummy module
69 community.general.modprobe:
70 name: dummy
71 state: present
72 params: 'numdummies=2'
73
74 - name: Add the dummy module and make sure it is loaded after reboots
75 community.general.modprobe:
76 name: dummy
77 state: present
78 params: 'numdummies=2'
79 persistent: present
80 """
81
82 import os.path
83 import platform
84 import re
85 import shlex
86 import traceback
87
88 from ansible.module_utils.basic import AnsibleModule
89
90 RELEASE_VER = platform.release()
91 MODULES_LOAD_LOCATION = "/etc/modules-load.d"
92 PARAMETERS_FILES_LOCATION = "/etc/modprobe.d"
93
94
95 class Modprobe:
96 def __init__(self, module):
97 self.module = module
98 self.modprobe_bin = module.get_bin_path("modprobe", True)
99
100 self.check_mode = module.check_mode
101 self.desired_state = module.params["state"]
102 self.name = module.params["name"]
103 self.params = module.params["params"]
104 self.persistent = module.params["persistent"]
105
106 self.changed = False
107
108 self.re_find_module = re.compile(rf"^ *{self.name} *(?:[#;].*)?\n?\Z")
109 self.re_find_params = re.compile(rf"^options {self.name} \w+=\S+ *(?:[#;].*)?\n?\Z")
110 self.re_get_params_and_values = re.compile(rf"^options {self.name} (\w+=\S+) *(?:[#;].*)?\n?\Z")
111
112 def load_module(self):
113 command = [self.modprobe_bin]
114 if self.check_mode:
115 command.append("-n")
116 command.extend([self.name] + shlex.split(self.params))
117
118 rc, out, err = self.module.run_command(command)
119
120 if rc != 0:
121 return self.module.fail_json(msg=err, rc=rc, stdout=out, stderr=err, **self.result)
122
123 if self.check_mode or self.module_loaded():
124 self.changed = True
125 else:
126 rc, stdout, stderr = self.module.run_command(
127 [self.modprobe_bin, "-n", "--first-time", self.name] + shlex.split(self.params)
128 )
129 if rc != 0:
130 self.module.warn(stderr)
131
132 @property
133 def module_is_loaded_persistently(self):
134 for module_file in self.modules_files:
135 with open(module_file) as file:
136 for line in file:
137 if self.re_find_module.match(line):
138 return True
139
140 return False
141
142 @property
143 def params_is_set(self):
144 desired_params = set(self.params.split())
145
146 return desired_params == self.permanent_params
147
148 @property
149 def permanent_params(self):
150 params = set()
151
152 for modprobe_file in self.modprobe_files:
153 with open(modprobe_file) as file:
154 for line in file:
155 match = self.re_get_params_and_values.match(line)
156 if match:
157 params.add(match.group(1))
158
159 return params
160
161 def create_module_file(self):
162 file_path = os.path.join(MODULES_LOAD_LOCATION, f"{self.name}.conf")
163 if not self.check_mode:
164 with open(file_path, "w") as file:
165 file.write(f"{self.name}\n")
166
167 @property
168 def module_options_file_content(self):
169 file_content = "\n".join([f"options {self.name} {param}" for param in self.params.split()])
170 return f"{file_content}\n"
171
172 def create_module_options_file(self):
173 new_file_path = os.path.join(PARAMETERS_FILES_LOCATION, f"{self.name}.conf")
174 if not self.check_mode:
175 with open(new_file_path, "w") as file:
176 file.write(self.module_options_file_content)
177
178 def disable_old_params(self):
179 for modprobe_file in self.modprobe_files:
180 with open(modprobe_file) as file:
181 file_content = file.readlines()
182
183 content_changed = False
184 for index, line in enumerate(file_content):
185 if self.re_find_params.match(line):
186 file_content[index] = f"#{line}"
187 content_changed = True
188
189 if not self.check_mode and content_changed:
190 with open(modprobe_file, "w") as file:
191 file.write("\n".join(file_content))
192
193 def disable_module_permanent(self):
194 for module_file in self.modules_files:
195 with open(module_file) as file:
196 file_content = file.readlines()
197
198 content_changed = False
199 for index, line in enumerate(file_content):
200 if self.re_find_module.match(line):
201 file_content[index] = f"#{line}"
202 content_changed = True
203
204 if not self.check_mode and content_changed:
205 with open(module_file, "w") as file:
206 file.write("\n".join(file_content))
207
208 def load_module_permanent(self):
209 if not self.module_is_loaded_persistently:
210 self.create_module_file()
211 self.changed = True
212
213 if not self.params_is_set:
214 self.disable_old_params()
215 self.create_module_options_file()
216 self.changed = True
217
218 def unload_module_permanent(self):
219 if self.module_is_loaded_persistently:
220 self.disable_module_permanent()
221 self.changed = True
222
223 if self.permanent_params:
224 self.disable_old_params()
225 self.changed = True
226
227 @property
228 def modules_files(self):
229 if not os.path.isdir(MODULES_LOAD_LOCATION):
230 return []
231 modules_paths = [os.path.join(MODULES_LOAD_LOCATION, path) for path in os.listdir(MODULES_LOAD_LOCATION)]
232 return [path for path in modules_paths if os.path.isfile(path)]
233
234 @property
235 def modprobe_files(self):
236 if not os.path.isdir(PARAMETERS_FILES_LOCATION):
237 return []
238 modules_paths = [
239 os.path.join(PARAMETERS_FILES_LOCATION, path) for path in os.listdir(PARAMETERS_FILES_LOCATION)
240 ]
241 return [path for path in modules_paths if os.path.isfile(path)]
242
243 def module_loaded(self):
244 is_loaded = False
245 try:
246 with open("/proc/modules") as modules:
247 module_name = f"{self.name.replace('-', '_')} "
248 for line in modules:
249 if line.startswith(module_name):
250 is_loaded = True
251 break
252
253 if not is_loaded:
254 module_file = f"/{self.name}.ko"
255 builtin_path = os.path.join("/lib/modules/", RELEASE_VER, "modules.builtin")
256 with open(builtin_path) as builtins:
257 for line in builtins:
258 if line.rstrip().endswith(module_file):
259 is_loaded = True
260 break
261 except OSError as e:
262 self.module.fail_json(msg=f"{e}", exception=traceback.format_exc(), **self.result)
263
264 return is_loaded
265
266 def unload_module(self):
267 command = [self.modprobe_bin, "-r", self.name]
268 if self.check_mode:
269 command.append("-n")
270
271 rc, out, err = self.module.run_command(command)
272 if rc != 0:
273 return self.module.fail_json(msg=err, rc=rc, stdout=out, stderr=err, **self.result)
274
275 self.changed = True
276
277 @property
278 def result(self):
279 return {
280 "changed": self.changed,
281 "name": self.name,
282 "params": self.params,
283 "state": self.desired_state,
284 }
285
286
287 def build_module():
288 return AnsibleModule(
289 argument_spec=dict(
290 name=dict(type="str", required=True),
291 state=dict(type="str", default="present", choices=["absent", "present"]),
292 params=dict(type="str", default=""),
293 persistent=dict(type="str", default="disabled", choices=["disabled", "present", "absent"]),
294 ),
295 supports_check_mode=True,
296 )
297
298
299 def main():
300 module = build_module()
301 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
302
303 modprobe = Modprobe(module)
304
305 if modprobe.desired_state == "present" and not modprobe.module_loaded():
306 modprobe.load_module()
307 elif modprobe.desired_state == "absent" and modprobe.module_loaded():
308 modprobe.unload_module()
309
310 if modprobe.persistent == "present" and not (modprobe.module_is_loaded_persistently and modprobe.params_is_set):
311 modprobe.load_module_permanent()
312 elif modprobe.persistent == "absent" and (modprobe.module_is_loaded_persistently or modprobe.permanent_params):
313 modprobe.unload_module_permanent()
314
315 module.exit_json(**modprobe.result)
316
317
318 if __name__ == "__main__":
319 main()