Debian Codegraph @

lib/ansible/modules/dnf5.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright 2023 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7
8 DOCUMENTATION = """
9 module: dnf5
10 author: Ansible Core Team
11 description:
12 - Installs, upgrade, removes, and lists packages and groups with the I(dnf5) package manager.
13 - "WARNING: The I(dnf5) package manager is still under development and not all features that the existing M(ansible.builtin.dnf) module
14 provides are implemented in M(ansible.builtin.dnf5), please consult specific options for more information."
15 short_description: Manages packages with the I(dnf5) package manager
16 options:
17 auto_install_module_deps:
18 description:
19 - Automatically install dependencies required to run this module.
20 type: bool
21 default: yes
22 version_added: 2.19
23 name:
24 description:
25 - "A package name or package specifier with version, like C(name-1.0).
26 When using O(state=latest), this can be C(*) which means run: C(dnf -y update).
27 You can also pass a url or a local path to an rpm file.
28 To operate on several packages this can accept a comma separated string of packages or a list of packages."
29 - Comparison operators for package version are valid here C(>), C(<), C(>=), C(<=). Example - C(name >= 1.0).
30 Spaces around the operator are required.
31 - You can also pass an absolute path for a binary which is provided by the package to install.
32 See examples for more information.
33 aliases:
34 - pkg
35 type: list
36 elements: str
37 default: []
38 list:
39 description:
40 - Various (non-idempotent) commands for usage with C(/usr/bin/ansible) and I(not) playbooks.
41 Use M(ansible.builtin.package_facts) instead of the O(list) argument as a best practice.
42 type: str
43 state:
44 description:
45 - Whether to install (V(present), V(latest)), or remove (V(absent)) a package.
46 - Default is V(None), however in effect the default action is V(present) unless the O(autoremove=true),
47 then V(absent) is inferred.
48 choices: ['absent', 'present', 'installed', 'removed', 'latest']
49 type: str
50 enablerepo:
51 description:
52 - I(Repoid) of repositories to enable for the install/update operation.
53 These repos will not persist beyond the transaction.
54 When specifying multiple repos, separate them with a C(,).
55 type: list
56 elements: str
57 default: []
58 disablerepo:
59 description:
60 - I(Repoid) of repositories to disable for the install/update operation.
61 These repos will not persist beyond the transaction.
62 When specifying multiple repos, separate them with a C(,).
63 type: list
64 elements: str
65 default: []
66 conf_file:
67 description:
68 - The remote dnf configuration file to use for the transaction.
69 type: str
70 disable_gpg_check:
71 description:
72 - Whether to disable the GPG checking of signatures of packages being
73 installed. Has an effect only if O(state) is V(present) or V(latest).
74 - This setting affects packages installed from a repository as well as
75 "local" packages installed from the filesystem or a URL.
76 type: bool
77 default: 'no'
78 installroot:
79 description:
80 - Specifies an alternative installroot, relative to which all packages
81 will be installed.
82 default: "/"
83 type: str
84 releasever:
85 description:
86 - Specifies an alternative release from which all packages will be
87 installed.
88 type: str
89 autoremove:
90 description:
91 - If V(true), removes all "leaf" packages from the system that were originally
92 installed as dependencies of user-installed packages but which are no longer
93 required by any such package. Should be used alone or when O(state=absent).
94 type: bool
95 default: "no"
96 exclude:
97 description:
98 - Package name(s) to exclude from the operation. This can be a list or a comma separated string.
99 - Works with all O(state) values, including V(absent), V(present), and V(latest).
100 type: list
101 elements: str
102 default: []
103 skip_broken:
104 description:
105 - Skip all unavailable packages or packages with broken dependencies
106 without raising an error. Equivalent to passing the C(--skip-broken) option.
107 type: bool
108 default: "no"
109 update_cache:
110 description:
111 - Force dnf to check if cache is out of date and redownload if needed.
112 Has an effect only if O(state=present) or O(state=latest).
113 type: bool
114 default: "no"
115 aliases: [ expire-cache ]
116 update_only:
117 description:
118 - When using latest, only update installed packages. Do not install packages.
119 - Has an effect only if O(state=present) or O(state=latest).
120 default: "no"
121 type: bool
122 security:
123 description:
124 - If set to V(true), and O(state=latest) then only installs updates that have been marked security related.
125 - Note that, similar to C(dnf upgrade-minimal), this filter applies to dependencies as well.
126 type: bool
127 default: "no"
128 bugfix:
129 description:
130 - If set to V(true), and O(state=latest) then only installs updates that have been marked bugfix related.
131 - Note that, similar to C(dnf upgrade-minimal), this filter applies to dependencies as well.
132 default: "no"
133 type: bool
134 enable_plugin:
135 description:
136 - I(Plugin) name to enable for the install/update operation.
137 The enabled plugin will not persist beyond the transaction.
138 - O(disable_plugin) takes precedence in case a plugin is listed in both O(enable_plugin) and O(disable_plugin).
139 - Requires python3-libdnf5 5.2.0.0+.
140 type: list
141 elements: str
142 default: []
143 disable_plugin:
144 description:
145 - I(Plugin) name to disable for the install/update operation.
146 The disabled plugins will not persist beyond the transaction.
147 - O(disable_plugin) takes precedence in case a plugin is listed in both O(enable_plugin) and O(disable_plugin).
148 - Requires python3-libdnf5 5.2.0.0+.
149 type: list
150 default: []
151 elements: str
152 disable_excludes:
153 description:
154 - Disable the excludes defined in DNF config files.
155 - If set to V(all), disables all excludes.
156 - If set to V(main), disable excludes defined in C([main]) in C(dnf.conf).
157 - If set to V(repoid), disable excludes defined for given repo id.
158 type: str
159 validate_certs:
160 description:
161 - This is effectively a no-op in the dnf5 module as dnf5 itself handles downloading a https url as the source of the rpm,
162 but is an accepted parameter for feature parity/compatibility with the M(ansible.builtin.dnf) module.
163 type: bool
164 default: "yes"
165 sslverify:
166 description:
167 - Disables SSL validation of the repository server for this transaction.
168 - This should be set to V(false) if one of the configured repositories is using an untrusted or self-signed certificate.
169 type: bool
170 default: "yes"
171 allow_downgrade:
172 description:
173 - Specify if the named package and version is allowed to downgrade
174 a maybe already installed higher version of that package.
175 Note that setting O(allow_downgrade=true) can make this module
176 behave in a non-idempotent way. The task could end up with a set
177 of packages that does not match the complete list of specified
178 packages to install (because dependencies between the downgraded
179 package and others can cause changes to the packages which were
180 in the earlier transaction).
181 - Since this feature is not provided by C(dnf5) itself but by M(ansible.builtin.dnf5) module,
182 using this in combination with wildcard characters in O(name) may result in an unexpected results.
183 type: bool
184 default: "no"
185 download_only:
186 description:
187 - Only download the packages, do not install them.
188 default: "no"
189 type: bool
190 lock_timeout:
191 description:
192 - This is currently a no-op as dnf5 does not provide an option to configure it.
193 - Amount of time to wait for the dnf lockfile to be freed.
194 required: false
195 default: 30
196 type: int
197 install_weak_deps:
198 description:
199 - Will also install all packages linked by a weak dependency relation.
200 type: bool
201 default: "yes"
202 download_dir:
203 description:
204 - Specifies an alternate directory to store packages.
205 - Has an effect only if O(download_only) is specified.
206 type: str
207 allowerasing:
208 description:
209 - If V(true) it allows erasing of installed packages to resolve dependencies.
210 required: false
211 type: bool
212 default: "no"
213 nobest:
214 description:
215 - This is the opposite of the O(best) option kept for backwards compatibility.
216 - Since ansible-core 2.17 the default value is set by the operating system distribution.
217 required: false
218 type: bool
219 best:
220 description:
221 - When set to V(true), either use a package with the highest version available or fail.
222 - When set to V(false), if the latest version cannot be installed go with the lower version.
223 - Default is set by the operating system distribution.
224 required: false
225 type: bool
226 version_added: "2.17"
227 cacheonly:
228 description:
229 - Tells dnf to run entirely from system cache; does not download or update metadata.
230 type: bool
231 default: "no"
232 extends_documentation_fragment:
233 - action_common_attributes
234 - action_common_attributes.flow
235 attributes:
236 action:
237 details: dnf5 has 2 action plugins that use it under the hood, M(ansible.builtin.dnf) and M(ansible.builtin.package).
238 support: partial
239 async:
240 support: none
241 bypass_host_loop:
242 support: none
243 check_mode:
244 support: full
245 diff_mode:
246 support: full
247 platform:
248 platforms: rhel
249 requirements:
250 - "python3-libdnf5"
251 notes:
252 - If the interpreter can't import C(python3-libdnf5) the module will check for it in system-owned interpreters as well.
253 If the dependency can't be found, depending on the value of O(auto_install_module_deps) the module will attempt to install it.
254 If the dependency is found or installed, the module will be respawned under the correct interpreter.
255 version_added: 2.15
256 """
257
258 EXAMPLES = """
259 - name: Install the latest version of Apache
260 ansible.builtin.dnf5:
261 name: httpd
262 state: latest
263
264 - name: Install Apache >= 2.4
265 ansible.builtin.dnf5:
266 name: httpd >= 2.4
267 state: present
268
269 - name: Install the latest version of Apache and MariaDB
270 ansible.builtin.dnf5:
271 name:
272 - httpd
273 - mariadb-server
274 state: latest
275
276 - name: Remove the Apache package
277 ansible.builtin.dnf5:
278 name: httpd
279 state: absent
280
281 - name: Install the latest version of Apache from the testing repo
282 ansible.builtin.dnf5:
283 name: httpd
284 enablerepo: testing
285 state: present
286
287 - name: Upgrade all packages
288 ansible.builtin.dnf5:
289 name: "*"
290 state: latest
291
292 - name: Update the webserver, depending on which is installed on the system. Do not install the other one
293 ansible.builtin.dnf5:
294 name:
295 - httpd
296 - nginx
297 state: latest
298 update_only: yes
299
300 - name: Install the nginx rpm from a remote repo
301 ansible.builtin.dnf5:
302 name: 'http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm'
303 state: present
304
305 - name: Install nginx rpm from a local file
306 ansible.builtin.dnf5:
307 name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm
308 state: present
309
310 - name: Install Package based upon the file it provides
311 ansible.builtin.dnf5:
312 name: /usr/bin/cowsay
313 state: present
314
315 - name: Install the 'Development tools' package group
316 ansible.builtin.dnf5:
317 name: '@Development tools'
318 state: present
319
320 - name: Autoremove unneeded packages installed as dependencies
321 ansible.builtin.dnf5:
322 autoremove: yes
323
324 - name: Uninstall httpd but keep its dependencies
325 ansible.builtin.dnf5:
326 name: httpd
327 state: absent
328 autoremove: no
329 """
330
331 RETURN = """
332 msg:
333 description: Additional information about the result
334 returned: always
335 type: str
336 sample: "Nothing to do"
337 results:
338 description: A list of the dnf transaction results
339 returned: success
340 type: list
341 sample: ["Installed: lsof-4.94.0-4.fc37.x86_64"]
342 failures:
343 description: A list of the dnf transaction failures
344 returned: failure
345 type: list
346 sample: ["Argument 'lsof' matches only excluded packages."]
347 rc:
348 description: For compatibility, 0 for success, 1 for failure
349 returned: always
350 type: int
351 sample: 0
352 """
353
354 import os
355 import sys
356
357 from ansible.module_utils.basic import AnsibleModule
358 from ansible.module_utils.common.locale import get_best_parsable_locale
359 from ansible.module_utils.common.respawn import has_respawned, probe_interpreters_for_module, respawn_module
360 from ansible.module_utils.yumdnf import YumDnf, yumdnf_argument_spec
361
362 libdnf5 = None
363 # Through dnf5-5.2.12 all exceptions raised through swig became RuntimeError
364 LIBDNF5_ERRORS = RuntimeError
365
366
367 def get_resolve_spec_settings():
368 settings = libdnf5.base.ResolveSpecSettings()
369 try:
370 settings.set_group_with_name(True)
371 # Disable checking whether SPEC is a binary -> `/usr/(s)bin/<SPEC>`,
372 # this prevents scenarios like the following:
373 # * the `sssd-common` package is installed and provides `/usr/sbin/sssd` binary
374 # * the `sssd` package is NOT installed
375 # * due to `set_with_binaries(True)` being default `is_installed(base, "sssd")` would "unexpectedly" return True
376 # If users wish to target the `sssd` binary they can by specifying the full path `name=/usr/sbin/sssd` explicitly
377 # due to settings.set_with_filenames(True) being default.
378 settings.set_with_binaries(False)
379 # Disable checking whether SPEC is provided by an installed package.
380 # Consider following real scenario from the rpmfusion repo:
381 # * the `ffmpeg-libs` package is installed and provides `libavcodec-freeworld`
382 # * but `libavcodec-freeworld` is NOT installed (???)
383 # * due to `set_with_provides(True)` being default `is_installed(base, "libavcodec-freeworld")`
384 # would "unexpectedly" return True
385 # We disable provides only for this `is_installed` check, for actual installation we leave the default
386 # setting to mirror the dnf cmdline behavior.
387 settings.set_with_provides(False)
388 except AttributeError:
389 # dnf5 < 5.2.0.0
390 settings.group_with_name = True
391 settings.with_binaries = False
392 settings.with_provides = False
393 return settings
394
395
396 def is_installed(base, spec):
397 settings = get_resolve_spec_settings()
398
399 installed_query = libdnf5.rpm.PackageQuery(base)
400 installed_query.filter_installed()
401 match, nevra = installed_query.resolve_pkg_spec(spec, settings, True)
402 return match
403
404
405 def is_newer_version_installed(base, spec):
406 # expects a versioned package spec
407 if "/" in spec:
408 spec = spec.split("/")[-1]
409 if spec.endswith(".rpm"):
410 spec = spec[:-4]
411
412 settings = get_resolve_spec_settings()
413 match, spec_nevra = libdnf5.rpm.PackageQuery(base).resolve_pkg_spec(spec, settings, True)
414 if not match or spec_nevra.has_just_name():
415 return False
416 spec_name = spec_nevra.get_name()
417
418 installed = libdnf5.rpm.PackageQuery(base)
419 installed.filter_installed()
420 installed.filter_name([spec_name])
421 installed.filter_latest_evr()
422 try:
423 installed_package = list(installed)[-1]
424 except IndexError:
425 return False
426
427 target = libdnf5.rpm.PackageQuery(base)
428 target.filter_name([spec_name])
429 target.filter_version([spec_nevra.get_version()])
430 spec_release = spec_nevra.get_release()
431 if spec_release:
432 target.filter_release([spec_release])
433 spec_epoch = spec_nevra.get_epoch()
434 if spec_epoch:
435 target.filter_epoch([spec_epoch])
436 target.filter_latest_evr()
437 try:
438 target_package = list(target)[-1]
439 except IndexError:
440 return False
441
442 # FIXME https://github.com/rpm-software-management/dnf5/issues/1104
443 return libdnf5.rpm.rpmvercmp(installed_package.get_evr(), target_package.get_evr()) == 1
444
445
446 def package_to_dict(package):
447 return {
448 "nevra": package.get_nevra(),
449 "envra": package.get_nevra(), # dnf module compat
450 "name": package.get_name(),
451 "arch": package.get_arch(),
452 "epoch": str(package.get_epoch()),
453 "release": package.get_release(),
454 "version": package.get_version(),
455 "repo": package.get_repo_id(),
456 "yumstate": "installed" if package.is_installed() else "available",
457 }
458
459
460 def get_unneeded_pkgs(base):
461 query = libdnf5.rpm.PackageQuery(base)
462 query.filter_installed()
463 query.filter_unneeded()
464 yield from query
465
466
467 class Dnf5Module(YumDnf):
468 def __init__(self, module):
469 super(Dnf5Module, self).__init__(module)
470 self.auto_install_module_deps = self.module.params["auto_install_module_deps"]
471
472 self._ensure_dnf()
473
474 self.pkg_mgr_name = "dnf5"
475
476 def fail_on_non_existing_plugins(self, base):
477 # https://github.com/rpm-software-management/dnf5/issues/1460
478 try:
479 plugin_names = [p.get_name() for p in base.get_plugins_info()]
480 except AttributeError:
481 # plugins functionality requires python3-libdnf5 5.2.0.0+
482 # silently ignore here, the module will fail later when
483 # base.enable_disable_plugins is attempted to be used if
484 # user specifies enable_plugin/disable_plugin
485 return
486
487 msg = []
488 if enable_unmatched := set(self.enable_plugin).difference(plugin_names):
489 msg.append(
490 f"No matches were found for the following plugin name patterns while enabling libdnf5 plugins: {', '.join(enable_unmatched)}."
491 )
492 if disable_unmatched := set(self.disable_plugin).difference(plugin_names):
493 msg.append(
494 f"No matches were found for the following plugin name patterns while disabling libdnf5 plugins: {', '.join(disable_unmatched)}."
495 )
496 if msg:
497 self.module.fail_json(msg=" ".join(msg))
498
499 def _ensure_dnf(self):
500 locale = get_best_parsable_locale(self.module)
501 os.environ["LC_ALL"] = os.environ["LC_MESSAGES"] = locale
502 os.environ["LANGUAGE"] = os.environ["LANG"] = locale
503
504 global libdnf5
505 global LIBDNF5_ERRORS
506 has_dnf = True
507 try:
508 import libdnf5 # type: ignore[import]
509 except ImportError:
510 has_dnf = False
511
512 try:
513 import libdnf5.exception # type: ignore[import-not-found]
514 LIBDNF5_ERRORS = (libdnf5.exception.Error, libdnf5.exception.NonLibdnf5Exception)
515 except (ImportError, AttributeError):
516 pass
517
518 if has_dnf:
519 return
520
521 system_interpreters = [
522 "/usr/libexec/platform-python",
523 "/usr/bin/python3",
524 "/usr/bin/python",
525 ]
526
527 if not has_respawned():
528 for attempt in (1, 2):
529 # probe well-known system Python locations for accessible bindings
530 interpreter = probe_interpreters_for_module(system_interpreters, "libdnf5")
531 if interpreter:
532 # respawn under the interpreter where the bindings should be found
533 respawn_module(interpreter)
534 # end of the line for this module, the process will exit here once the respawned module completes
535 if attempt == 1:
536 if self.module.check_mode:
537 self.module.fail_json(
538 msg="python3-libdnf5 must be installed to use check mode. "
539 "If run normally this module can auto-install it, "
540 "see the auto_install_module_deps option.",
541 )
542 elif self.auto_install_module_deps:
543 self.module.run_command(["dnf", "install", "-y", "python3-libdnf5"], check_rc=True)
544 else:
545 break
546
547 py_version = sys.version.replace("\n", "")
548 self.module.fail_json(
549 msg=f"Could not import the libdnf5 python module using {sys.executable} ({py_version}). "
550 "Ensure python3-libdnf5 package is installed (either manually or via the auto_install_module_deps option) "
551 f"or that you have specified the correct ansible_python_interpreter. (attempted {system_interpreters}).",
552 failures=[],
553 )
554
555 def run(self):
556 if not self.list and not self.download_only and os.geteuid() != 0:
557 self.module.fail_json(
558 msg="This command has to be run under the root user.",
559 failures=[],
560 rc=1,
561 )
562
563 base = libdnf5.base.Base()
564 conf = base.get_config()
565
566 if self.conf_file:
567 conf.config_file_path = self.conf_file
568
569 base.load_config()
570
571 if self.releasever is not None:
572 variables = base.get_vars()
573 variables.set("releasever", self.releasever)
574 if self.exclude:
575 conf.excludepkgs = self.exclude
576 if self.disable_excludes:
577 if self.disable_excludes == "all":
578 self.disable_excludes = "*"
579 conf.disable_excludes = self.disable_excludes
580 conf.skip_broken = self.skip_broken
581 # best and nobest are mutually exclusive
582 if self.nobest is not None:
583 conf.best = not self.nobest
584 elif self.best is not None:
585 conf.best = self.best
586 conf.install_weak_deps = self.install_weak_deps
587 try:
588 # raises AttributeError only on getter if not available
589 conf.pkg_gpgcheck # pylint: disable=pointless-statement
590 except AttributeError:
591 # dnf5 < 5.2.7.0
592 conf.gpgcheck = not self.disable_gpg_check
593 else:
594 conf.pkg_gpgcheck = not self.disable_gpg_check
595 conf.localpkg_gpgcheck = not self.disable_gpg_check
596 conf.sslverify = self.sslverify
597 conf.clean_requirements_on_remove = self.autoremove
598
599 if not os.path.isdir(self.installroot):
600 self.module.fail_json(msg=f"Installroot {self.installroot} must be a directory")
601
602 conf.installroot = self.installroot
603 conf.use_host_config = True # needed for installroot
604 conf.cacheonly = "all" if self.cacheonly else "none"
605 if self.download_only and self.download_dir:
606 conf.destdir = self.download_dir
607
608 if self.enable_plugin:
609 try:
610 base.enable_disable_plugins(self.enable_plugin, True)
611 except AttributeError:
612 self.module.fail_json(msg="'enable_plugin' requires python3-libdnf5 5.2.0.0+")
613
614 if self.disable_plugin:
615 try:
616 base.enable_disable_plugins(self.disable_plugin, False)
617 except AttributeError:
618 self.module.fail_json(msg="'disable_plugin' requires python3-libdnf5 5.2.0.0+")
619
620 base.setup()
621
622 # https://github.com/rpm-software-management/dnf5/issues/1460
623 self.fail_on_non_existing_plugins(base)
624
625 log_router = base.get_logger()
626 global_logger = libdnf5.logger.GlobalLogger()
627 global_logger.set(log_router.get(), libdnf5.logger.Logger.Level_DEBUG)
628 # FIXME hardcoding the filename does not seem right, should libdnf5 expose the default file name?
629 logger = libdnf5.logger.create_file_logger(base, "dnf5.log")
630 log_router.add_logger(logger)
631
632 if self.update_cache:
633 repo_query = libdnf5.repo.RepoQuery(base)
634 repo_query.filter_type(libdnf5.repo.Repo.Type_AVAILABLE)
635 for repo in repo_query:
636 repo_dir = repo.get_cachedir()
637 if os.path.exists(repo_dir):
638 repo_cache = libdnf5.repo.RepoCache(base, repo_dir)
639 repo_cache.write_attribute(libdnf5.repo.RepoCache.ATTRIBUTE_EXPIRED)
640
641 sack = base.get_repo_sack()
642 sack.create_repos_from_system_configuration()
643
644 repo_query = libdnf5.repo.RepoQuery(base)
645 if self.disablerepo:
646 repo_query.filter_id(self.disablerepo, libdnf5.common.QueryCmp_IGLOB)
647 for repo in repo_query:
648 repo.disable()
649 if self.enablerepo:
650 repo_query.filter_id(self.enablerepo, libdnf5.common.QueryCmp_IGLOB)
651 for repo in repo_query:
652 repo.enable()
653
654 try:
655 sack.load_repos()
656 except AttributeError:
657 # dnf5 < 5.2.0.0
658 sack.update_and_load_enabled_repos(True)
659
660 if self.update_cache and not self.names and not self.list:
661 self.module.exit_json(
662 msg="Cache updated",
663 changed=False,
664 results=[],
665 rc=0
666 )
667
668 if self.list:
669 command = self.list
670 if command == "updates":
671 command = "upgrades"
672
673 if command in {"installed", "upgrades", "available"}:
674 query = libdnf5.rpm.PackageQuery(base)
675 getattr(query, "filter_{}".format(command))()
676 results = [package_to_dict(package) for package in query]
677 elif command in {"repos", "repositories"}:
678 query = libdnf5.repo.RepoQuery(base)
679 query.filter_enabled(True)
680 results = [{"repoid": repo.get_id(), "state": "enabled"} for repo in query]
681 else:
682 resolve_spec_settings = libdnf5.base.ResolveSpecSettings()
683 query = libdnf5.rpm.PackageQuery(base)
684 query.resolve_pkg_spec(command, resolve_spec_settings, True)
685 results = [package_to_dict(package) for package in query]
686
687 self.module.exit_json(msg="", results=results, rc=0)
688
689 settings = libdnf5.base.GoalJobSettings()
690 try:
691 settings.set_group_with_name(True)
692 settings.set_with_binaries(False)
693 except AttributeError:
694 # dnf5 < 5.2.0.0
695 settings.group_with_name = True
696 settings.with_binaries = False
697
698 if self.bugfix or self.security:
699 advisory_query = libdnf5.advisory.AdvisoryQuery(base)
700 types = []
701 if self.bugfix:
702 types.append("bugfix")
703 if self.security:
704 types.append("security")
705 advisory_query.filter_type(types)
706 conf.skip_unavailable = True # ignore packages that are of a different type, for backwards compat
707 settings.set_advisory_filter(advisory_query)
708
709 goal = libdnf5.base.Goal(base)
710 results = []
711 if self.names == ["*"] and self.state == "latest":
712 goal.add_rpm_upgrade(settings)
713 elif self.state in {"installed", "present", "latest"}:
714 upgrade = self.state == "latest"
715 # FIXME use `is_glob_pattern` function when available:
716 # https://github.com/rpm-software-management/dnf5/issues/1563
717 glob_patterns = set("*[?")
718 for spec in self.names:
719 if any(set(char) & glob_patterns for char in spec):
720 # Special case for package specs that contain glob characters.
721 # For these we skip `is_installed` and `is_newer_version_installed` tests that allow for the
722 # allow_downgrade feature and pass the package specs to dnf.
723 # Since allow_downgrade is not available in dnf and while it is relatively easy to implement it for
724 # package specs that evaluate to a single package, trying to mimic what would the dnf machinery do
725 # for glob package specs and then filtering those for allow_downgrade appears to always
726 # result in naive/inferior solution.
727 # TODO research how feasible it is to implement the above
728 if upgrade:
729 # for upgrade we pass the spec to both upgrade and install, to satisfy both available and installed
730 # packages evaluated from the glob spec
731 goal.add_upgrade(spec, settings)
732 if not self.update_only:
733 goal.add_install(spec, settings)
734 elif is_newer_version_installed(base, spec):
735 if self.allow_downgrade:
736 goal.add_install(spec, settings)
737 elif is_installed(base, spec):
738 if upgrade:
739 goal.add_upgrade(spec, settings)
740 else:
741 if self.update_only:
742 results.append("Packages providing {} not installed due to update_only specified".format(spec))
743 else:
744 goal.add_install(spec, settings)
745 elif self.state in {"absent", "removed"}:
746 for spec in self.names:
747 goal.add_remove(spec, settings)
748 if self.autoremove:
749 for pkg in get_unneeded_pkgs(base):
750 goal.add_rpm_remove(pkg, settings)
751
752 goal.set_allow_erasing(self.allowerasing)
753 transaction = goal.resolve()
754
755 if transaction.get_problems():
756 failures = []
757 for log_event in transaction.get_resolve_logs():
758 if log_event.get_problem() == libdnf5.base.GoalProblem_NOT_FOUND and self.state in {"installed", "present", "latest"}:
759 # NOTE dnf module compat
760 failures.append("No package {} available.".format(log_event.get_spec()))
761 else:
762 failures.append(log_event.to_string())
763
764 if transaction.get_problems() & libdnf5.base.GoalProblem_SOLVER_ERROR != 0:
765 msg = "Depsolve Error occurred"
766 else:
767 msg = "Failed to install some of the specified packages"
768 self.module.fail_json(
769 msg=msg,
770 failures=failures,
771 rc=1,
772 )
773
774 # NOTE dnf module compat
775 actions_compat_map = {
776 "Install": "Installed",
777 "Remove": "Removed",
778 "Replace": "Installed",
779 "Upgrade": "Installed",
780 "Replaced": "Removed",
781 }
782 changed = bool(transaction.get_transaction_packages())
783 for pkg in transaction.get_transaction_packages():
784 if self.download_only:
785 action = "Downloaded"
786 else:
787 action = libdnf5.base.transaction.transaction_item_action_to_string(pkg.get_action())
788 results.append("{}: {}".format(actions_compat_map.get(action, action), pkg.get_package().get_nevra()))
789
790 msg = ""
791 if self.module.check_mode:
792 if results:
793 msg = "Check mode: No changes made, but would have if not in check mode"
794 elif changed:
795 transaction.download()
796 if not self.download_only:
797 transaction.set_description("ansible dnf5 module")
798 result = transaction.run()
799 if result == libdnf5.base.Transaction.TransactionRunResult_ERROR_GPG_CHECK:
800 self.module.fail_json(
801 msg="Failed to validate GPG signatures: {}".format(",".join(transaction.get_gpg_signature_problems())),
802 failures=[],
803 rc=1,
804 )
805 elif result != libdnf5.base.Transaction.TransactionRunResult_SUCCESS:
806 failures = []
807 if result == libdnf5.base.Transaction.TransactionRunResult_ERROR_RPM_RUN:
808 try:
809 failures = list(transaction.get_rpm_messages())
810 except AttributeError:
811 # get_rpm_messages is not available in dnf5 < 5.2.7.0
812 pass
813 # Add the transaction problems to the failures
814 failures.extend(["{}: {}".format(transaction.transaction_result_to_string(result), log) for log in transaction.get_transaction_problems()])
815
816 self.module.fail_json(
817 msg="Failed to install some of the specified packages",
818 failures=failures,
819 rc=1,
820 )
821
822 if not msg and not results:
823 msg = "Nothing to do"
824
825 self.module.exit_json(
826 results=results,
827 changed=changed,
828 msg=msg,
829 rc=0,
830 )
831
832
833 def main():
834 yumdnf_argument_spec["argument_spec"].update(
835 dict(
836 auto_install_module_deps=dict(type="bool", default=True),
837 )
838 )
839 module = AnsibleModule(**yumdnf_argument_spec)
840 try:
841 Dnf5Module(module).run()
842 except LIBDNF5_ERRORS as e:
843 module.fail_json(msg=str(e), failures=[], rc=1)
844
845
846 if __name__ == "__main__":
847 main()