Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, Evgenii Terechkov
4 # Written by Evgenii Terechkov <[email protected]>
5 # Based on urpmi module written by Philippe Makowski <[email protected]>
6
7 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
8 # SPDX-License-Identifier: GPL-3.0-or-later
9
10 from __future__ import annotations
11
12 DOCUMENTATION = r"""
13 module: apt_rpm
14 short_description: APT-RPM package manager
15 description:
16 - Manages packages with C(apt-rpm). Both low-level (C(rpm)) and high-level (C(apt-get)) package manager binaries required.
17 extends_documentation_fragment:
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: none
22 diff_mode:
23 support: none
24 options:
25 package:
26 description:
27 - List of packages to install, upgrade, or remove.
28 - Since community.general 8.0.0, may include paths to local C(.rpm) files if O(state=installed) or O(state=present),
29 requires C(rpm) Python module.
30 aliases: [name, pkg]
31 type: list
32 elements: str
33 state:
34 description:
35 - Indicates the desired package state.
36 - The states V(latest) and V(present_not_latest) have been added in community.general 8.6.0.
37 - Please note before community.general 11.0.0, V(present) and V(installed) were equivalent to V(latest). This changed
38 in community.general 11.0.0. Now they are equivalent to V(present_not_latest).
39 choices:
40 - absent
41 - present
42 - present_not_latest
43 - installed
44 - removed
45 - latest
46 default: present
47 type: str
48 update_cache:
49 description:
50 - Run the equivalent of C(apt-get update) before the operation. Can be run as part of the package installation or as
51 a separate step.
52 - Default is not to update the cache.
53 type: bool
54 default: false
55 clean:
56 description:
57 - Run the equivalent of C(apt-get clean) to clear out the local repository of retrieved package files. It removes everything
58 but the lock file from C(/var/cache/apt/archives/) and C(/var/cache/apt/archives/partial/).
59 - Can be run as part of the package installation (clean runs before install) or as a separate step.
60 type: bool
61 default: false
62 version_added: 6.5.0
63 dist_upgrade:
64 description:
65 - If true performs an C(apt-get dist-upgrade) to upgrade system.
66 type: bool
67 default: false
68 version_added: 6.5.0
69 update_kernel:
70 description:
71 - If true performs an C(update-kernel) to upgrade kernel packages.
72 type: bool
73 default: false
74 version_added: 6.5.0
75 requirements:
76 - C(rpm) Python package (rpm bindings), optional. Required if O(package) option includes local files.
77 author:
78 - Evgenii Terechkov (@evgkrsk)
79 """
80
81 EXAMPLES = r"""
82 - name: Install package foo
83 community.general.apt_rpm:
84 pkg: foo
85 state: present
86
87 - name: Install packages foo and bar
88 community.general.apt_rpm:
89 pkg:
90 - foo
91 - bar
92 state: present
93
94 - name: Remove package foo
95 community.general.apt_rpm:
96 pkg: foo
97 state: absent
98
99 - name: Remove packages foo and bar
100 community.general.apt_rpm:
101 pkg: foo,bar
102 state: absent
103
104 # bar will be the updated if a newer version exists
105 - name: Update the package database and install bar
106 community.general.apt_rpm:
107 name: bar
108 state: present
109 update_cache: true
110
111 - name: Run the equivalent of "apt-get clean" as a separate step
112 community.general.apt_rpm:
113 clean: true
114
115 - name: Perform cache update and complete system upgrade (includes kernel)
116 community.general.apt_rpm:
117 update_cache: true
118 dist_upgrade: true
119 update_kernel: true
120 """
121
122 import os
123 import re
124 import traceback
125
126 from ansible.module_utils.basic import (
127 AnsibleModule,
128 missing_required_lib,
129 )
130 from ansible.module_utils.common.text.converters import to_native
131
132 RPM_PYTHON_IMPORT_ERROR: str | None
133 try:
134 import rpm
135 except ImportError:
136 HAS_RPM_PYTHON = False
137 RPM_PYTHON_IMPORT_ERROR = traceback.format_exc()
138 else:
139 HAS_RPM_PYTHON = True
140 RPM_PYTHON_IMPORT_ERROR = None
141
142 APT_CACHE = "/usr/bin/apt-cache"
143 APT_PATH = "/usr/bin/apt-get"
144 RPM_PATH = "/usr/bin/rpm"
145 APT_GET_ZERO = "\n0 upgraded, 0 newly installed"
146 UPDATE_KERNEL_ZERO = "\nTry to install new kernel "
147 UPDATE_KERNEL_NO_NEW = "There are no available kernels"
148
149
150 def local_rpm_package_name(path):
151 """return package name of a local rpm passed in.
152 Inspired by ansible.builtin.yum"""
153
154 header = get_local_rpm_header(path)
155 if header is None:
156 return None
157
158 return to_native(header[rpm.RPMTAG_NAME])
159
160
161 def get_local_rpm_header(path):
162 """return rpm header of a local rpm file."""
163 ts = rpm.TransactionSet()
164 ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES)
165 fd = os.open(path, os.O_RDONLY)
166 try:
167 return ts.hdrFromFdno(fd)
168 except rpm.error:
169 return None
170 finally:
171 os.close(fd)
172
173
174 def get_installed_rpm_header(name):
175 """return rpm header of an installed package."""
176 ts = rpm.TransactionSet()
177 return next(ts.dbMatch(rpm.RPMTAG_NAME, name), None)
178
179
180 def query_package(module, name):
181 # rpm -q returns 0 if the package is installed,
182 # 1 if it is not installed
183 rc, out, err = module.run_command([RPM_PATH, "-q", name])
184 return rc == 0
185
186
187 def check_package_version(module, name, local_rpm_path):
188 # compare installed and candidate version
189 # if newest version already installed return True
190 # otherwise return False
191
192 if local_rpm_path is not None:
193 local_hdr = get_local_rpm_header(local_rpm_path)
194 if local_hdr is None:
195 module.fail_json(msg=f"Failed to read version from local RPM file: {local_rpm_path}")
196 inst_hdr = get_installed_rpm_header(name)
197 if inst_hdr is None:
198 return False
199 result = rpm.versionCompare(inst_hdr, local_hdr)
200 return result >= 0
201 else:
202 rc, out, err = module.run_command([APT_CACHE, "policy", name], environ_update={"LANGUAGE": "C", "LC_ALL": "C"})
203 installed = re.split("\n |: ", out)[2]
204 candidate = re.split("\n |: ", out)[4]
205 return installed >= candidate
206
207
208 def query_package_provides(module, name, allow_upgrade=False):
209 # rpm -q returns 0 if the package is installed,
210 # 1 if it is not installed
211 local_rpm_path = None
212 if name.endswith(".rpm"):
213 # Likely a local RPM file
214 if not HAS_RPM_PYTHON:
215 module.fail_json(
216 msg=missing_required_lib("rpm"),
217 exception=RPM_PYTHON_IMPORT_ERROR,
218 )
219
220 local_rpm_path = name
221 name = local_rpm_package_name(name)
222
223 rc, out, err = module.run_command([RPM_PATH, "-q", "--provides", name])
224 if rc == 0:
225 if not allow_upgrade:
226 return True
227 if check_package_version(module, name, local_rpm_path):
228 return True
229 return False
230
231
232 def update_package_db(module):
233 rc, update_out, err = module.run_command(
234 [APT_PATH, "update"], check_rc=True, environ_update={"LANGUAGE": "C", "LC_ALL": "C"}
235 )
236 return (False, update_out)
237
238
239 def dir_size(module, path):
240 total_size = 0
241 for cur_path, _dirs, files in os.walk(path):
242 for f in files:
243 total_size += os.path.getsize(os.path.join(cur_path, f))
244 return total_size
245
246
247 def clean(module):
248 t = dir_size(module, "/var/cache/apt/archives")
249 rc, out, err = module.run_command([APT_PATH, "clean"], check_rc=True)
250 return (t != dir_size(module, "/var/cache/apt/archives"), out)
251
252
253 def dist_upgrade(module):
254 rc, out, err = module.run_command(
255 [APT_PATH, "-y", "dist-upgrade"], check_rc=True, environ_update={"LANGUAGE": "C", "LC_ALL": "C"}
256 )
257 return (APT_GET_ZERO not in out, out)
258
259
260 def update_kernel(module):
261 rc, out, err = module.run_command(
262 ["/usr/sbin/update-kernel", "-y"], environ_update={"LANGUAGE": "C", "LC_ALL": "C"}
263 )
264 if rc != 0:
265 if UPDATE_KERNEL_NO_NEW in err:
266 return (False, out)
267 module.fail_json(msg=f"Error while updating kernel: {err or out}", rc=rc, stdout=out, stderr=err)
268 return (UPDATE_KERNEL_ZERO not in out, out)
269
270
271 def remove_packages(module, packages):
272 if packages is None:
273 return (False, "Empty package list")
274
275 remove_c = 0
276 # Using a for loop in case of error, we can report the package that failed
277 for package in packages:
278 # Query the package first, to see if we even need to remove
279 if not query_package(module, package):
280 continue
281
282 rc, out, err = module.run_command(
283 [APT_PATH, "-y", "remove", package], environ_update={"LANGUAGE": "C", "LC_ALL": "C"}
284 )
285
286 if rc != 0:
287 module.fail_json(msg=f"failed to remove {package}: {err}")
288
289 remove_c += 1
290
291 if remove_c > 0:
292 return (True, f"removed {remove_c} package(s)")
293
294 return (False, "package(s) already absent")
295
296
297 def install_packages(module, pkgspec, allow_upgrade=False):
298 if pkgspec is None:
299 return (False, "Empty package list")
300
301 packages = []
302 for package in pkgspec:
303 if not query_package_provides(module, package, allow_upgrade=allow_upgrade):
304 packages.append(package)
305
306 if packages:
307 command = [APT_PATH, "-y", "install"] + packages
308 rc, out, err = module.run_command(command, environ_update={"LANGUAGE": "C", "LC_ALL": "C"})
309
310 installed = True
311 for package in pkgspec:
312 if not query_package_provides(module, package, allow_upgrade=False):
313 installed = False
314
315 # apt-rpm always have 0 for exit code if --force is used
316 if rc or not installed:
317 module.fail_json(msg=f"'{' '.join(command)}' failed: {err}")
318 else:
319 return (True, f"{packages} present(s)")
320 else:
321 return (False, "Nothing to install")
322
323
324 def main():
325 module = AnsibleModule(
326 argument_spec=dict(
327 state=dict(
328 type="str",
329 default="present",
330 choices=["absent", "installed", "present", "removed", "present_not_latest", "latest"],
331 ),
332 update_cache=dict(type="bool", default=False),
333 clean=dict(type="bool", default=False),
334 dist_upgrade=dict(type="bool", default=False),
335 update_kernel=dict(type="bool", default=False),
336 package=dict(type="list", elements="str", aliases=["name", "pkg"]),
337 ),
338 )
339
340 if not os.path.exists(APT_PATH) or not os.path.exists(RPM_PATH):
341 module.fail_json(msg="cannot find /usr/bin/apt-get and/or /usr/bin/rpm")
342
343 p = module.params
344
345 modified = False
346 output = ""
347
348 if p["update_cache"]:
349 update_package_db(module)
350
351 if p["clean"]:
352 (m, out) = clean(module)
353 modified = modified or m
354
355 if p["dist_upgrade"]:
356 (m, out) = dist_upgrade(module)
357 modified = modified or m
358 output += out
359
360 if p["update_kernel"]:
361 (m, out) = update_kernel(module)
362 modified = modified or m
363 output += out
364
365 packages = p["package"]
366 if p["state"] in ["installed", "present", "present_not_latest", "latest"]:
367 (m, out) = install_packages(module, packages, allow_upgrade=p["state"] == "latest")
368 modified = modified or m
369 output += out
370
371 if p["state"] in ["absent", "removed"]:
372 (m, out) = remove_packages(module, packages)
373 modified = modified or m
374 output += out
375
376 # Return total modification status and output of all commands
377 module.exit_json(changed=modified, msg=output)
378
379
380 if __name__ == "__main__":
381 main()