Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2021, Roberto Moreda <[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 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: dnf_versionlock
10 version_added: '4.0.0'
11 short_description: Locks package versions in C(dnf) based systems
12 description:
13 - Locks package versions using the C(versionlock) plugin in C(dnf) based systems. This plugin takes a set of name and versions
14 for packages and excludes all other versions of those packages. This allows you to for example protect packages from being
15 updated by newer versions. The state of the plugin that reflects locking of packages is the C(locklist).
16 extends_documentation_fragment:
17 - community.general._attributes
18 attributes:
19 check_mode:
20 support: partial
21 details:
22 - The logics of the C(versionlock) plugin for corner cases could be confusing, so please take in account that this module
23 does its best to give a C(check_mode) prediction on what is going to happen. In case of doubt, check the documentation
24 of the plugin.
25 - Sometimes the module could predict changes in C(check_mode) that are not fulfilled because C(versionlock) concludes
26 that there is already a entry in C(locklist) that already matches.
27 diff_mode:
28 support: none
29 options:
30 name:
31 description:
32 - Package name spec to add or exclude to or delete from the C(locklist) using the format expected by the C(dnf repoquery)
33 command.
34 - This parameter is mutually exclusive with O(state=clean).
35 type: list
36 elements: str
37 default: []
38 raw:
39 description:
40 - Do not resolve package name specs to NEVRAs to find specific version to lock to. Instead the package name specs are
41 used as they are. This enables locking to not yet available versions of the package.
42 type: bool
43 default: false
44 state:
45 description:
46 - Whether to add (V(present) or V(excluded)) to or remove (V(absent) or V(clean)) from the C(locklist).
47 - V(present) adds a package name spec to the C(locklist). If there is a installed package that matches, then only that
48 version is added. Otherwise, all available package versions are added.
49 - V(excluded) adds a package name spec as excluded to the C(locklist). It means that packages represented by the package
50 name spec are excluded from transaction operations. All available package versions are added.
51 - V(absent) deletes entries in the C(locklist) that match the package name spec.
52 - V(clean) deletes all entries in the C(locklist). This option is mutually exclusive with O(name).
53 choices: ['absent', 'clean', 'excluded', 'present']
54 type: str
55 default: present
56 notes:
57 - In an ideal world, the C(versionlock) plugin would have a dry-run option to know for sure what is going to happen. So
58 far we have to work with a best guess as close as possible to the behaviour inferred from its code.
59 - For most of cases where you want to lock and unlock specific versions of a package, this works fairly well.
60 - Does not work with C(dnf5).
61 requirements:
62 - dnf
63 - dnf-plugin-versionlock
64 author:
65 - Roberto Moreda (@moreda) <[email protected]>
66 """
67
68 EXAMPLES = r"""
69 - name: Prevent installed nginx from being updated
70 community.general.dnf_versionlock:
71 name: nginx
72 state: present
73
74 - name: Prevent multiple packages from being updated
75 community.general.dnf_versionlock:
76 name:
77 - nginx
78 - haproxy
79 state: present
80
81 - name: Remove lock from nginx to be updated again
82 community.general.dnf_versionlock:
83 name: nginx
84 state: absent
85
86 - name: Exclude bind 32:9.11 from installs or updates
87 community.general.dnf_versionlock:
88 name: bind-32:9.11*
89 state: excluded
90
91 - name: Keep bash package in major version 4
92 community.general.dnf_versionlock:
93 name: bash-0:4.*
94 raw: true
95 state: present
96
97 - name: Delete all entries in the locklist of versionlock
98 community.general.dnf_versionlock:
99 state: clean
100 """
101
102 RETURN = r"""
103 locklist_pre:
104 description: Locklist before module execution.
105 returned: success
106 type: list
107 elements: str
108 sample: ["bash-0:4.4.20-1.el8_4.*", "!bind-32:9.11.26-4.el8_4.*"]
109 locklist_post:
110 description: Locklist after module execution.
111 returned: success and (not check mode or state is clean)
112 type: list
113 elements: str
114 sample: ["bash-0:4.4.20-1.el8_4.*"]
115 specs_toadd:
116 description: Package name specs meant to be added by versionlock.
117 returned: success
118 type: list
119 elements: str
120 sample: ["bash"]
121 specs_todelete:
122 description: Package name specs meant to be deleted by versionlock.
123 returned: success
124 type: list
125 elements: str
126 sample: ["bind"]
127 """
128
129 import fnmatch
130 import os
131 import re
132
133 from ansible.module_utils.basic import AnsibleModule
134
135 DNF_BIN = "/usr/bin/dnf"
136 VERSIONLOCK_CONF = "/etc/dnf/plugins/versionlock.conf"
137 # NEVRA regex.
138 NEVRA_RE = re.compile(r"^(?P<name>.+)-(?P<epoch>\d+):(?P<version>.+)-(?P<release>.+)\.(?P<arch>.+)$")
139
140
141 def do_versionlock(module, command, patterns=None, raw=False):
142 patterns = patterns if patterns else []
143 raw_parameter = ["--raw"] if raw else []
144 # Call dnf versionlock using a just one full NEVR package-name-spec each
145 # time because multiple package-name-spec and globs are not well supported.
146 #
147 # This is a workaround for two alleged bugs in the dnf versionlock plugin:
148 # * Multiple package-name-spec arguments don't lock correctly
149 # (https://bugzilla.redhat.com/show_bug.cgi?id=2013324).
150 # * Locking a version of a not installed package disallows locking other
151 # versions later (https://bugzilla.redhat.com/show_bug.cgi?id=2013332)
152 #
153 # NOTE: This is suboptimal in terms of performance if there are more than a
154 # few package-name-spec patterns to lock, because there is a command
155 # execution per each. This will improve by changing the strategy once the
156 # mentioned alleged bugs in the dnf versionlock plugin are fixed.
157 if patterns:
158 outs = []
159 for p in patterns:
160 rc, out, err = module.run_command(
161 [DNF_BIN, "-q", "versionlock", command] + raw_parameter + [p], check_rc=True
162 )
163 outs.append(out)
164 out = "\n".join(outs)
165 else:
166 rc, out, err = module.run_command([DNF_BIN, "-q", "versionlock", command], check_rc=True)
167 return out
168
169
170 # This is equivalent to the _match function of the versionlock plugin.
171 def match(entry, pattern):
172 entry = entry.lstrip("!")
173 if entry == pattern:
174 return True
175 m = NEVRA_RE.match(entry)
176 if not m:
177 return False
178
179 for name in (
180 f"{m['name']}",
181 f"{m['name']}.{m['arch']}",
182 f"{m['name']}-{m['version']}",
183 f"{m['name']}-{m['version']}-{m['release']}",
184 f"{m['name']}-{m['epoch']}:{m['version']}",
185 f"{m['name']}-{m['version']}-{m['release']}.{m['arch']}",
186 f"{m['name']}-{m['epoch']}:{m['version']}-{m['release']}",
187 f"{m['epoch']}:{m['name']}-{m['version']}-{m['release']}.{m['arch']}",
188 f"{m['name']}-{m['epoch']}:{m['version']}-{m['release']}.{m['arch']}",
189 ):
190 if fnmatch.fnmatch(name, pattern):
191 return True
192 return False
193
194
195 def get_packages(module, patterns, only_installed=False):
196 packages_available_map_name_evrs = {}
197 rc, out, err = module.run_command(
198 [DNF_BIN, "-q", "repoquery"] + (["--installed"] if only_installed else []) + patterns, check_rc=True
199 )
200
201 for p in out.split():
202 # Extract the NEVRA pattern.
203 m = NEVRA_RE.match(p)
204 if not m:
205 module.fail_json(msg=f"failed to parse nevra for {p}", rc=rc, out=out, err=err)
206
207 evr = f"{m['epoch']}:{m['version']}-{m['release']}"
208
209 packages_available_map_name_evrs.setdefault(m["name"], set())
210 packages_available_map_name_evrs[m["name"]].add(evr)
211 return packages_available_map_name_evrs
212
213
214 def get_package_mgr():
215 for bin_path in (DNF_BIN,):
216 if os.path.exists(bin_path):
217 return "dnf5" if os.path.realpath(bin_path) == "/usr/bin/dnf5" else "dnf"
218 # fallback to dnf
219 return "dnf"
220
221
222 def get_package_list(module, package_mgr="dnf"):
223 if package_mgr == "dnf":
224 return do_versionlock(module, "list").split()
225
226 package_list = []
227 if package_mgr == "dnf5":
228 stanza_start = False
229 package_name = None
230 for line in do_versionlock(module, "list").splitlines():
231 if line.startswith(("#", " ")):
232 continue
233 if line.startswith("Package name:"):
234 stanza_start = True
235 dummy, name = line.split(":", 1)
236 name = name.strip()
237 pkg_name = get_packages(module, patterns=[name])
238 package_name = f"{name}-{pkg_name[name].pop()}.*"
239 if package_name and package_name not in package_list:
240 package_list.append(package_name)
241 if line.startswith("evr"):
242 dummy, package_version = line.split("=", 1)
243 package_version = package_version.strip()
244 if stanza_start:
245 if package_name and package_name not in package_list:
246 package_list.append(package_name)
247 stanza_start = False
248 return package_list
249
250
251 def main():
252 module = AnsibleModule(
253 argument_spec=dict(
254 name=dict(type="list", elements="str", default=[]),
255 raw=dict(type="bool", default=False),
256 state=dict(type="str", default="present", choices=["present", "absent", "excluded", "clean"]),
257 ),
258 supports_check_mode=True,
259 )
260 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
261
262 patterns = module.params["name"]
263 raw = module.params["raw"]
264 state = module.params["state"]
265 changed = False
266 msg = ""
267
268 # Check module pre-requisites.
269 global DNF_BIN
270 DNF_BIN = module.get_bin_path("dnf", True)
271 package_mgr = get_package_mgr()
272 if package_mgr == "dnf" and not os.path.exists(VERSIONLOCK_CONF):
273 module.fail_json(msg="plugin versionlock is required")
274
275 # Check incompatible options.
276 if state == "clean" and patterns:
277 module.fail_json(msg="clean state is incompatible with a name list")
278 if state != "clean" and not patterns:
279 module.fail_json(msg=f"name list is required for {state} state")
280
281 locklist_pre = get_package_list(module, package_mgr=package_mgr)
282
283 specs_toadd = []
284 specs_todelete = []
285
286 if state in ["present", "excluded"]:
287 if raw:
288 # Add raw patterns as specs to add.
289 for p in patterns:
290 if (p if state == "present" else f"!{p}") not in locklist_pre:
291 specs_toadd.append(p)
292 else:
293 # Get available packages that match the patterns.
294 packages_map_name_evrs = get_packages(module, patterns)
295
296 # Get installed packages that match the patterns.
297 packages_installed_map_name_evrs = get_packages(module, patterns, only_installed=True)
298
299 # Obtain the list of package specs that require an entry in the
300 # locklist. This list is composed by:
301 # a) the non-installed packages list with all available
302 # versions
303 # b) the installed packages list
304 packages_map_name_evrs.update(packages_installed_map_name_evrs)
305 for name in packages_map_name_evrs:
306 for evr in packages_map_name_evrs[name]:
307 locklist_entry = f"{name}-{evr}.*"
308
309 if (locklist_entry if state == "present" else f"!{locklist_entry}") not in locklist_pre:
310 specs_toadd.append(locklist_entry)
311
312 if specs_toadd and not module.check_mode:
313 cmd = "add" if state == "present" else "exclude"
314 msg = do_versionlock(module, cmd, patterns=specs_toadd, raw=raw)
315
316 elif state == "absent":
317 if raw:
318 # Add raw patterns as specs to delete.
319 for p in patterns:
320 if p in locklist_pre:
321 specs_todelete.append(p)
322
323 else:
324 # Get patterns that match the some line in the locklist.
325 for p in patterns:
326 for e in locklist_pre:
327 if match(e, p):
328 specs_todelete.append(p)
329
330 if specs_todelete and not module.check_mode:
331 msg = do_versionlock(module, "delete", patterns=specs_todelete, raw=raw)
332
333 elif state == "clean":
334 specs_todelete = locklist_pre
335
336 if specs_todelete and not module.check_mode:
337 msg = do_versionlock(module, "clear")
338
339 if specs_toadd or specs_todelete:
340 changed = True
341
342 response = {
343 "changed": changed,
344 "msg": msg,
345 "locklist_pre": locklist_pre,
346 "specs_toadd": specs_toadd,
347 "specs_todelete": specs_todelete,
348 }
349 if not module.check_mode:
350 response["locklist_post"] = get_package_list(module, package_mgr=package_mgr)
351 else:
352 if state == "clean":
353 response["locklist_post"] = []
354
355 module.exit_json(**response)
356
357
358 if __name__ == "__main__":
359 main()