| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2012, Afterburn <https://github.com/afterburn> |
| 4 |
# Copyright (c) 2013, Aaron Bull Schaefer <[email protected]> |
| 5 |
# Copyright (c) 2015, Indrajit Raychaudhuri <[email protected]> |
| 6 |
# Copyright (c) 2022, Jean Raby <[email protected]> |
| 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: pacman |
| 14 |
short_description: Manage packages with I(pacman) |
| 15 |
description: |
| 16 |
- Manage packages with the I(pacman) package manager, which is used by Arch Linux and its variants. |
| 17 |
author: |
| 18 |
- Indrajit Raychaudhuri (@indrajitr) |
| 19 |
- Aaron Bull Schaefer (@elasticdog) <[email protected]> |
| 20 |
- Maxime de Roucy (@tchernomax) |
| 21 |
- Jean Raby (@jraby) |
| 22 |
extends_documentation_fragment: |
| 23 |
- community.general._attributes |
| 24 |
attributes: |
| 25 |
check_mode: |
| 26 |
support: full |
| 27 |
diff_mode: |
| 28 |
support: full |
| 29 |
options: |
| 30 |
name: |
| 31 |
description: |
| 32 |
- Name or list of names of the package(s) or file(s) to install, upgrade, or remove. Cannot be used in combination with |
| 33 |
O(upgrade). |
| 34 |
aliases: [package, pkg] |
| 35 |
type: list |
| 36 |
elements: str |
| 37 |
|
| 38 |
state: |
| 39 |
description: |
| 40 |
- Whether to install (V(present) or V(installed), V(latest)), or remove (V(absent) or V(removed)) a package. |
| 41 |
- V(present) and V(installed) simply ensure that a desired package is installed. |
| 42 |
- V(latest) updates the specified package if it is not of the latest available version. |
| 43 |
- V(absent) and V(removed) remove the specified package. |
| 44 |
default: present |
| 45 |
choices: [absent, installed, latest, present, removed] |
| 46 |
type: str |
| 47 |
|
| 48 |
force: |
| 49 |
description: |
| 50 |
- When removing packages, forcefully remove them, without any checks. Same as O(extra_args="--nodeps --nodeps"). |
| 51 |
- When combined with O(update_cache), force a refresh of all package databases. Same as O(update_cache_extra_args="--refresh |
| 52 |
--refresh"). |
| 53 |
default: false |
| 54 |
type: bool |
| 55 |
|
| 56 |
remove_nosave: |
| 57 |
description: |
| 58 |
- When removing packages, do not save modified configuration files as C(.pacsave) files. (passes C(--nosave) to pacman). |
| 59 |
version_added: 4.6.0 |
| 60 |
default: false |
| 61 |
type: bool |
| 62 |
|
| 63 |
executable: |
| 64 |
description: |
| 65 |
- Path of the binary to use. This can either be C(pacman) or a pacman compatible AUR helper. |
| 66 |
- Pacman compatibility is unfortunately ill defined, in particular, this modules makes extensive use of the C(--print-format) |
| 67 |
directive which is known not to be implemented by some AUR helpers (notably, C(yay)). |
| 68 |
- Beware that AUR helpers might behave unexpectedly and are therefore not recommended. |
| 69 |
default: pacman |
| 70 |
type: str |
| 71 |
version_added: 3.1.0 |
| 72 |
|
| 73 |
extra_args: |
| 74 |
description: |
| 75 |
- Additional option to pass to pacman when enforcing O(state). |
| 76 |
default: '' |
| 77 |
type: str |
| 78 |
|
| 79 |
root: |
| 80 |
description: |
| 81 |
- An alternative installation root directory, passed as C(--root) to all pacman commands. |
| 82 |
- Useful for installing packages into a chroot or a new system root, similarly to how C(pacstrap) works. |
| 83 |
type: path |
| 84 |
version_added: 12.6.0 |
| 85 |
|
| 86 |
cachedir: |
| 87 |
description: |
| 88 |
- An alternative package cache directory, passed as C(--cachedir) to all pacman commands. |
| 89 |
- Only used when O(root) is also specified. |
| 90 |
type: path |
| 91 |
version_added: 12.6.0 |
| 92 |
|
| 93 |
config: |
| 94 |
description: |
| 95 |
- Path to an alternative pacman configuration file, passed as C(--config) to all pacman commands. |
| 96 |
type: path |
| 97 |
version_added: 12.6.0 |
| 98 |
|
| 99 |
update_cache: |
| 100 |
description: |
| 101 |
- Whether or not to refresh the master package lists. |
| 102 |
- This can be run as part of a package installation or as a separate step. |
| 103 |
- If not specified, it defaults to V(false). |
| 104 |
- Please note that this option only had an influence on the module's RV(ignore:changed) state if O(name) and O(upgrade) are |
| 105 |
not specified before community.general 5.0.0. See the examples for how to keep the old behavior. |
| 106 |
type: bool |
| 107 |
|
| 108 |
update_cache_extra_args: |
| 109 |
description: |
| 110 |
- Additional option to pass to pacman when enforcing O(update_cache). |
| 111 |
default: '' |
| 112 |
type: str |
| 113 |
|
| 114 |
upgrade: |
| 115 |
description: |
| 116 |
- Whether or not to upgrade the whole system. Cannot be used in combination with O(name). |
| 117 |
- If not specified, it defaults to V(false). |
| 118 |
type: bool |
| 119 |
|
| 120 |
upgrade_extra_args: |
| 121 |
description: |
| 122 |
- Additional option to pass to pacman when enforcing O(upgrade). |
| 123 |
default: '' |
| 124 |
type: str |
| 125 |
|
| 126 |
reason: |
| 127 |
description: |
| 128 |
- The install reason to set for the packages. |
| 129 |
choices: [dependency, explicit] |
| 130 |
type: str |
| 131 |
version_added: 5.4.0 |
| 132 |
|
| 133 |
reason_for: |
| 134 |
description: |
| 135 |
- Set the install reason for V(all) packages or only for V(new) packages. |
| 136 |
- In case of O(state=latest) already installed packages which are updated to a newer version are not counted as V(new). |
| 137 |
default: new |
| 138 |
choices: [all, new] |
| 139 |
type: str |
| 140 |
version_added: 5.4.0 |
| 141 |
|
| 142 |
notes: |
| 143 |
- When used with a C(loop:) each package is processed individually, it is much more efficient to pass the list directly |
| 144 |
to the O(name) option. |
| 145 |
- To use an AUR helper (O(executable) option), a few extra setup steps might be required beforehand. For example, a dedicated |
| 146 |
build user with permissions to install packages could be necessary. |
| 147 |
- 'In the tests, while using C(yay) as the O(executable) option, the module failed to install AUR packages with the error: |
| 148 |
C(error: target not found: <pkg>). This is caused by an incompatibility of yay with the arguments passed by this module. |
| 149 |
See L(yay bug #1744 report for details, https://github.com/Jguer/yay/issues/1744).' |
| 150 |
- The common return values RV(ignore:stdout) and RV(ignore:stderr) are returned upon success, when needed, since community.general 4.1.0. |
| 151 |
""" |
| 152 |
|
| 153 |
RETURN = r""" |
| 154 |
packages: |
| 155 |
description: |
| 156 |
- A list of packages that have been changed. |
| 157 |
- Before community.general 4.5.0 this was only returned when O(upgrade=true). In community.general 4.5.0, it was sometimes |
| 158 |
omitted when the package list is empty, but since community.general 4.6.0 it is always returned when O(name) is specified |
| 159 |
or O(upgrade=true). |
| 160 |
returned: success and O(name) is specified or O(upgrade=true) |
| 161 |
type: list |
| 162 |
elements: str |
| 163 |
sample: ["package", "other-package"] |
| 164 |
|
| 165 |
cache_updated: |
| 166 |
description: |
| 167 |
- The changed status of C(pacman -Sy). |
| 168 |
- Useful when O(name) or O(upgrade=true) are specified next to O(update_cache=true). |
| 169 |
returned: success, when O(update_cache=true) |
| 170 |
type: bool |
| 171 |
sample: false |
| 172 |
version_added: 4.6.0 |
| 173 |
""" |
| 174 |
|
| 175 |
EXAMPLES = r""" |
| 176 |
- name: Install package foo from repo |
| 177 |
community.general.pacman: |
| 178 |
name: foo |
| 179 |
state: present |
| 180 |
|
| 181 |
- name: Install package bar from file |
| 182 |
community.general.pacman: |
| 183 |
name: ~/bar-1.0-1-any.pkg.tar.xz |
| 184 |
state: present |
| 185 |
|
| 186 |
- name: Install package foo from repo and bar from file |
| 187 |
community.general.pacman: |
| 188 |
name: |
| 189 |
- foo |
| 190 |
- ~/bar-1.0-1-any.pkg.tar.xz |
| 191 |
state: present |
| 192 |
|
| 193 |
- name: Install package from AUR using a Pacman compatible AUR helper |
| 194 |
community.general.pacman: |
| 195 |
name: foo |
| 196 |
state: present |
| 197 |
executable: yay |
| 198 |
extra_args: --builddir /var/cache/yay |
| 199 |
|
| 200 |
- name: Upgrade package foo |
| 201 |
# The 'changed' state of this call will indicate whether the cache was |
| 202 |
# updated *or* whether foo was installed/upgraded. |
| 203 |
community.general.pacman: |
| 204 |
name: foo |
| 205 |
state: latest |
| 206 |
update_cache: true |
| 207 |
|
| 208 |
- name: Remove packages foo and bar |
| 209 |
community.general.pacman: |
| 210 |
name: |
| 211 |
- foo |
| 212 |
- bar |
| 213 |
state: absent |
| 214 |
|
| 215 |
- name: Recursively remove package baz |
| 216 |
community.general.pacman: |
| 217 |
name: baz |
| 218 |
state: absent |
| 219 |
extra_args: --recursive |
| 220 |
|
| 221 |
- name: Run the equivalent of "pacman -Sy" as a separate step |
| 222 |
community.general.pacman: |
| 223 |
update_cache: true |
| 224 |
|
| 225 |
- name: Run the equivalent of "pacman -Su" as a separate step |
| 226 |
community.general.pacman: |
| 227 |
upgrade: true |
| 228 |
|
| 229 |
- name: Run the equivalent of "pacman -Syu" as a separate step |
| 230 |
# Since community.general 5.0.0 the 'changed' state of this call |
| 231 |
# will be 'true' in case the cache was updated, or when a package |
| 232 |
# was updated. |
| 233 |
# |
| 234 |
# The previous behavior was to only indicate whether something was |
| 235 |
# upgraded. To keep the old behavior, add the following to the task: |
| 236 |
# |
| 237 |
# register: result |
| 238 |
# changed_when: result.packages | length > 0 |
| 239 |
community.general.pacman: |
| 240 |
update_cache: true |
| 241 |
upgrade: true |
| 242 |
|
| 243 |
- name: Run the equivalent of "pacman -Rdd", force remove package baz |
| 244 |
community.general.pacman: |
| 245 |
name: baz |
| 246 |
state: absent |
| 247 |
force: true |
| 248 |
|
| 249 |
- name: Install foo as dependency and leave reason untouched if already installed |
| 250 |
community.general.pacman: |
| 251 |
name: foo |
| 252 |
state: present |
| 253 |
reason: dependency |
| 254 |
reason_for: new |
| 255 |
|
| 256 |
- name: Run the equivalent of "pacman -S --asexplicit", mark foo as explicit and install it if not present |
| 257 |
community.general.pacman: |
| 258 |
name: foo |
| 259 |
state: present |
| 260 |
reason: explicit |
| 261 |
reason_for: all |
| 262 |
|
| 263 |
- name: Install packages into a new root (similar to pacstrap) |
| 264 |
community.general.pacman: |
| 265 |
name: |
| 266 |
- base |
| 267 |
- base-devel |
| 268 |
- python |
| 269 |
state: present |
| 270 |
root: /mnt |
| 271 |
cachedir: /mnt/var/cache/pacman/pkg |
| 272 |
config: /path/to/another/pacman.conf |
| 273 |
update_cache: true |
| 274 |
""" |
| 275 |
|
| 276 |
import re |
| 277 |
import shlex |
| 278 |
from collections import defaultdict |
| 279 |
from dataclasses import dataclass |
| 280 |
|
| 281 |
from ansible.module_utils.basic import AnsibleModule |
| 282 |
|
| 283 |
|
| 284 |
class Package: |
| 285 |
def __init__(self, name, source, source_is_URL=False): |
| 286 |
self.name = name |
| 287 |
self.source = source |
| 288 |
self.source_is_URL = source_is_URL |
| 289 |
|
| 290 |
def __eq__(self, o): |
| 291 |
return self.name == o.name and self.source == o.source and self.source_is_URL == o.source_is_URL |
| 292 |
|
| 293 |
def __lt__(self, o): |
| 294 |
return self.name < o.name |
| 295 |
|
| 296 |
def __repr__(self): |
| 297 |
return f'Package("{self.name}", "{self.source}", {self.source_is_URL})' |
| 298 |
|
| 299 |
|
| 300 |
@dataclass |
| 301 |
class VersionTuple: |
| 302 |
current: str |
| 303 |
latest: str |
| 304 |
|
| 305 |
|
| 306 |
class Pacman: |
| 307 |
def __init__(self, module): |
| 308 |
self.m = module |
| 309 |
|
| 310 |
self.m.run_command_environ_update = dict(LANGUAGE="C", LC_ALL="C") |
| 311 |
p = self.m.params |
| 312 |
|
| 313 |
self._msgs = [] |
| 314 |
self._stdouts = [] |
| 315 |
self._stderrs = [] |
| 316 |
self.changed = False |
| 317 |
self.exit_params = {} |
| 318 |
|
| 319 |
self.pacman_path = self.m.get_bin_path(p["executable"], True) |
| 320 |
|
| 321 |
self.pacman_cmd = [self.pacman_path] |
| 322 |
if p["config"]: |
| 323 |
self.pacman_cmd += ["--config", p["config"]] |
| 324 |
if p["root"]: |
| 325 |
self.pacman_cmd += ["--root", p["root"]] |
| 326 |
if p["cachedir"]: |
| 327 |
self.pacman_cmd += ["--cachedir", p["cachedir"]] |
| 328 |
|
| 329 |
self._cached_database = None |
| 330 |
|
| 331 |
# Normalize for old configs |
| 332 |
if p["state"] == "installed": |
| 333 |
self.target_state = "present" |
| 334 |
elif p["state"] == "removed": |
| 335 |
self.target_state = "absent" |
| 336 |
else: |
| 337 |
self.target_state = p["state"] |
| 338 |
|
| 339 |
def add_exit_infos(self, msg=None, stdout=None, stderr=None): |
| 340 |
if msg: |
| 341 |
self._msgs.append(msg) |
| 342 |
if stdout: |
| 343 |
self._stdouts.append(stdout) |
| 344 |
if stderr: |
| 345 |
self._stderrs.append(stderr) |
| 346 |
|
| 347 |
def _set_mandatory_exit_params(self): |
| 348 |
msg = "\n".join(self._msgs) |
| 349 |
stdouts = "\n".join(self._stdouts) |
| 350 |
stderrs = "\n".join(self._stderrs) |
| 351 |
if stdouts: |
| 352 |
self.exit_params["stdout"] = stdouts |
| 353 |
if stderrs: |
| 354 |
self.exit_params["stderr"] = stderrs |
| 355 |
self.exit_params["msg"] = msg # mandatory, but might be empty |
| 356 |
|
| 357 |
def fail(self, msg=None, stdout=None, stderr=None, **kwargs): |
| 358 |
self.add_exit_infos(msg, stdout, stderr) |
| 359 |
self._set_mandatory_exit_params() |
| 360 |
if kwargs: |
| 361 |
self.exit_params.update(**kwargs) |
| 362 |
self.m.fail_json(**self.exit_params) |
| 363 |
|
| 364 |
def success(self): |
| 365 |
self._set_mandatory_exit_params() |
| 366 |
self.m.exit_json(changed=self.changed, **self.exit_params) |
| 367 |
|
| 368 |
def run(self): |
| 369 |
if self.m.params["update_cache"]: |
| 370 |
self.update_package_db() |
| 371 |
|
| 372 |
if not (self.m.params["name"] or self.m.params["upgrade"]): |
| 373 |
self.success() |
| 374 |
|
| 375 |
self.inventory = self._build_inventory() |
| 376 |
if self.m.params["upgrade"]: |
| 377 |
self.upgrade() |
| 378 |
self.success() |
| 379 |
|
| 380 |
if self.m.params["name"]: |
| 381 |
pkgs = self.package_list() |
| 382 |
|
| 383 |
if self.target_state == "absent": |
| 384 |
self.remove_packages(pkgs) |
| 385 |
self.success() |
| 386 |
else: |
| 387 |
self.install_packages(pkgs) |
| 388 |
self.success() |
| 389 |
|
| 390 |
# This happens if an empty list has been provided for name |
| 391 |
self.add_exit_infos(msg="Nothing to do") |
| 392 |
self.success() |
| 393 |
|
| 394 |
def install_packages(self, pkgs): |
| 395 |
pkgs_to_install = [] |
| 396 |
pkgs_to_install_from_url = [] |
| 397 |
pkgs_to_set_reason = [] |
| 398 |
for p in pkgs: |
| 399 |
if self.m.params["reason"] and ( |
| 400 |
p.name not in self.inventory["pkg_reasons"] |
| 401 |
or self.m.params["reason_for"] == "all" |
| 402 |
and self.inventory["pkg_reasons"][p.name] != self.m.params["reason"] |
| 403 |
): |
| 404 |
pkgs_to_set_reason.append(p.name) |
| 405 |
if p.source_is_URL: |
| 406 |
# URL packages bypass the latest / upgradable_pkgs test |
| 407 |
# They go through the dry-run to let pacman decide if they will be installed |
| 408 |
pkgs_to_install_from_url.append(p) |
| 409 |
continue |
| 410 |
if ( |
| 411 |
p.name not in self.inventory["installed_pkgs"] |
| 412 |
or self.target_state == "latest" |
| 413 |
and p.name in self.inventory["upgradable_pkgs"] |
| 414 |
): |
| 415 |
pkgs_to_install.append(p) |
| 416 |
|
| 417 |
if len(pkgs_to_install) == 0 and len(pkgs_to_install_from_url) == 0 and len(pkgs_to_set_reason) == 0: |
| 418 |
self.exit_params["packages"] = [] |
| 419 |
self.add_exit_infos("package(s) already installed") |
| 420 |
return |
| 421 |
|
| 422 |
cmd_base = self.pacman_cmd + [ |
| 423 |
"--noconfirm", |
| 424 |
"--noprogressbar", |
| 425 |
"--needed", |
| 426 |
] |
| 427 |
if self.m.params["extra_args"]: |
| 428 |
cmd_base.extend(self.m.params["extra_args"]) |
| 429 |
|
| 430 |
def _build_install_diff(pacman_verb, pkglist): |
| 431 |
# Dry run to build the installation diff |
| 432 |
|
| 433 |
cmd = cmd_base + [pacman_verb, "--print-format", "%n %v"] + [p.source for p in pkglist] |
| 434 |
rc, stdout, stderr = self.m.run_command(cmd, check_rc=False) |
| 435 |
if rc != 0: |
| 436 |
self.fail("Failed to list package(s) to install", cmd=cmd, stdout=stdout, stderr=stderr) |
| 437 |
|
| 438 |
name_ver = [l.strip() for l in stdout.splitlines()] |
| 439 |
before = [] |
| 440 |
after = [] |
| 441 |
to_be_installed = [] |
| 442 |
for p in name_ver: |
| 443 |
# With Pacman v6.0.1 - libalpm v13.0.1, --upgrade outputs "loading packages..." on stdout. strip that. |
| 444 |
# When installing from URLs, pacman can also output a 'nothing to do' message. strip that too. |
| 445 |
if "loading packages" in p or "there is nothing to do" in p or "Avoid running" in p: |
| 446 |
continue |
| 447 |
name, version = p.split() |
| 448 |
if name in self.inventory["installed_pkgs"]: |
| 449 |
before.append( |
| 450 |
f"{name}-{self.inventory['installed_pkgs'][name]}-{self.inventory['pkg_reasons'][name]}" |
| 451 |
) |
| 452 |
if name in pkgs_to_set_reason: |
| 453 |
after.append(f"{name}-{version}-{self.m.params['reason']}") |
| 454 |
elif name in self.inventory["pkg_reasons"]: |
| 455 |
after.append(f"{name}-{version}-{self.inventory['pkg_reasons'][name]}") |
| 456 |
else: |
| 457 |
after.append(f"{name}-{version}") |
| 458 |
to_be_installed.append(name) |
| 459 |
|
| 460 |
return (to_be_installed, before, after) |
| 461 |
|
| 462 |
before = [] |
| 463 |
after = [] |
| 464 |
installed_pkgs = [] |
| 465 |
|
| 466 |
if pkgs_to_install: |
| 467 |
p, b, a = _build_install_diff("--sync", pkgs_to_install) |
| 468 |
installed_pkgs.extend(p) |
| 469 |
before.extend(b) |
| 470 |
after.extend(a) |
| 471 |
if pkgs_to_install_from_url: |
| 472 |
p, b, a = _build_install_diff("--upgrade", pkgs_to_install_from_url) |
| 473 |
installed_pkgs.extend(p) |
| 474 |
before.extend(b) |
| 475 |
after.extend(a) |
| 476 |
|
| 477 |
if len(installed_pkgs) == 0 and len(pkgs_to_set_reason) == 0: |
| 478 |
# This can happen with URL packages if pacman decides there's nothing to do |
| 479 |
self.exit_params["packages"] = [] |
| 480 |
self.add_exit_infos("package(s) already installed") |
| 481 |
return |
| 482 |
|
| 483 |
self.changed = True |
| 484 |
|
| 485 |
_before_joined = "\n".join(sorted(before)) |
| 486 |
_after_joined = "\n".join(sorted(after)) |
| 487 |
self.exit_params["diff"] = { |
| 488 |
"before": f"{_before_joined}\n" if before else "", |
| 489 |
"after": f"{_after_joined}\n" if after else "", |
| 490 |
} |
| 491 |
|
| 492 |
changed_reason_pkgs = [p for p in pkgs_to_set_reason if p not in installed_pkgs] |
| 493 |
|
| 494 |
if self.m.check_mode: |
| 495 |
self.add_exit_infos(f"Would have installed {len(installed_pkgs) + len(changed_reason_pkgs)} packages") |
| 496 |
self.exit_params["packages"] = sorted(installed_pkgs + changed_reason_pkgs) |
| 497 |
return |
| 498 |
|
| 499 |
# actually do it |
| 500 |
def _install_packages_for_real(pacman_verb, pkglist): |
| 501 |
cmd = cmd_base + [pacman_verb] + [p.source for p in pkglist] |
| 502 |
rc, stdout, stderr = self.m.run_command(cmd, check_rc=False) |
| 503 |
if rc != 0: |
| 504 |
self.fail("Failed to install package(s)", cmd=cmd, stdout=stdout, stderr=stderr) |
| 505 |
self.add_exit_infos(stdout=stdout, stderr=stderr) |
| 506 |
self._invalidate_database() |
| 507 |
|
| 508 |
if pkgs_to_install: |
| 509 |
_install_packages_for_real("--sync", pkgs_to_install) |
| 510 |
if pkgs_to_install_from_url: |
| 511 |
_install_packages_for_real("--upgrade", pkgs_to_install_from_url) |
| 512 |
|
| 513 |
# set reason |
| 514 |
if pkgs_to_set_reason: |
| 515 |
cmd = self.pacman_cmd + ["--noconfirm", "--database"] |
| 516 |
if self.m.params["reason"] == "dependency": |
| 517 |
cmd.append("--asdeps") |
| 518 |
else: |
| 519 |
cmd.append("--asexplicit") |
| 520 |
cmd.extend(pkgs_to_set_reason) |
| 521 |
|
| 522 |
rc, stdout, stderr = self.m.run_command(cmd, check_rc=False) |
| 523 |
if rc != 0: |
| 524 |
self.fail("Failed to install package(s)", cmd=cmd, stdout=stdout, stderr=stderr) |
| 525 |
self.add_exit_infos(stdout=stdout, stderr=stderr) |
| 526 |
|
| 527 |
self.exit_params["packages"] = sorted(installed_pkgs + changed_reason_pkgs) |
| 528 |
self.add_exit_infos(f"Installed {len(installed_pkgs) + len(changed_reason_pkgs)} package(s)") |
| 529 |
|
| 530 |
def remove_packages(self, pkgs): |
| 531 |
# filter out pkgs that are already absent |
| 532 |
pkg_names_to_remove = [p.name for p in pkgs if p.name in self.inventory["installed_pkgs"]] |
| 533 |
|
| 534 |
if len(pkg_names_to_remove) == 0: |
| 535 |
self.exit_params["packages"] = [] |
| 536 |
self.add_exit_infos("package(s) already absent") |
| 537 |
return |
| 538 |
|
| 539 |
# There's something to do, set this in advance |
| 540 |
self.changed = True |
| 541 |
|
| 542 |
cmd_base = self.pacman_cmd + ["--remove", "--noconfirm", "--noprogressbar"] |
| 543 |
cmd_base += self.m.params["extra_args"] |
| 544 |
cmd_base += ["--nodeps", "--nodeps"] if self.m.params["force"] else [] |
| 545 |
# nosave_args conflicts with --print-format. Added later. |
| 546 |
# https://github.com/ansible-collections/community.general/issues/4315 |
| 547 |
|
| 548 |
# This is a bit of a TOCTOU but it is better than parsing the output of |
| 549 |
# pacman -R, which is different depending on the user config (VerbosePkgLists) |
| 550 |
# Start by gathering what would be removed |
| 551 |
cmd = cmd_base + ["--print-format", "%n-%v"] + pkg_names_to_remove |
| 552 |
|
| 553 |
rc, stdout, stderr = self.m.run_command(cmd, check_rc=False) |
| 554 |
if rc != 0: |
| 555 |
self.fail("failed to list package(s) to remove", cmd=cmd, stdout=stdout, stderr=stderr) |
| 556 |
|
| 557 |
removed_pkgs = stdout.split() |
| 558 |
self.exit_params["packages"] = removed_pkgs |
| 559 |
_remove_pkgs_joined = "\n".join(removed_pkgs) |
| 560 |
self.exit_params["diff"] = { |
| 561 |
"before": f"{_remove_pkgs_joined}\n", # trailing \n to avoid diff complaints |
| 562 |
"after": "", |
| 563 |
} |
| 564 |
|
| 565 |
if self.m.check_mode: |
| 566 |
self.exit_params["packages"] = removed_pkgs |
| 567 |
self.add_exit_infos(f"Would have removed {len(removed_pkgs)} packages") |
| 568 |
return |
| 569 |
|
| 570 |
nosave_args = ["--nosave"] if self.m.params["remove_nosave"] else [] |
| 571 |
cmd = cmd_base + nosave_args + pkg_names_to_remove |
| 572 |
|
| 573 |
rc, stdout, stderr = self.m.run_command(cmd, check_rc=False) |
| 574 |
if rc != 0: |
| 575 |
self.fail("failed to remove package(s)", cmd=cmd, stdout=stdout, stderr=stderr) |
| 576 |
self._invalidate_database() |
| 577 |
self.exit_params["packages"] = removed_pkgs |
| 578 |
self.add_exit_infos(f"Removed {len(removed_pkgs)} package(s)", stdout=stdout, stderr=stderr) |
| 579 |
|
| 580 |
def upgrade(self): |
| 581 |
"""Runs pacman --sync --sysupgrade if there are upgradable packages""" |
| 582 |
|
| 583 |
if len(self.inventory["upgradable_pkgs"]) == 0: |
| 584 |
self.add_exit_infos("Nothing to upgrade") |
| 585 |
return |
| 586 |
|
| 587 |
self.changed = True # there are upgrades, so there will be changes |
| 588 |
|
| 589 |
# Build diff based on inventory first. |
| 590 |
diff = {"before": "", "after": ""} |
| 591 |
for pkg, versions in self.inventory["upgradable_pkgs"].items(): |
| 592 |
diff["before"] += f"{pkg}-{versions.current}\n" |
| 593 |
diff["after"] += f"{pkg}-{versions.latest}\n" |
| 594 |
self.exit_params["diff"] = diff |
| 595 |
self.exit_params["packages"] = self.inventory["upgradable_pkgs"].keys() |
| 596 |
|
| 597 |
if self.m.check_mode: |
| 598 |
self.add_exit_infos(f"{len(self.inventory['upgradable_pkgs'])} packages would have been upgraded") |
| 599 |
else: |
| 600 |
cmd = self.pacman_cmd + [ |
| 601 |
"--sync", |
| 602 |
"--sysupgrade", |
| 603 |
"--quiet", |
| 604 |
"--noconfirm", |
| 605 |
] |
| 606 |
if self.m.params["upgrade_extra_args"]: |
| 607 |
cmd += self.m.params["upgrade_extra_args"] |
| 608 |
rc, stdout, stderr = self.m.run_command(cmd, check_rc=False) |
| 609 |
self._invalidate_database() |
| 610 |
if rc == 0: |
| 611 |
self.add_exit_infos("System upgraded", stdout=stdout, stderr=stderr) |
| 612 |
else: |
| 613 |
self.fail("Could not upgrade", cmd=cmd, stdout=stdout, stderr=stderr) |
| 614 |
|
| 615 |
def _list_database(self): |
| 616 |
"""runs pacman --sync --list with some caching""" |
| 617 |
if self._cached_database is None: |
| 618 |
dummy, packages, dummy = self.m.run_command(self.pacman_cmd + ["--sync", "--list"], check_rc=True) |
| 619 |
self._cached_database = packages.splitlines() |
| 620 |
return self._cached_database |
| 621 |
|
| 622 |
def _invalidate_database(self): |
| 623 |
"""invalidates the pacman --sync --list cache""" |
| 624 |
self._cached_database = None |
| 625 |
|
| 626 |
def update_package_db(self): |
| 627 |
"""runs pacman --sync --refresh""" |
| 628 |
if self.m.check_mode: |
| 629 |
self.add_exit_infos("Would have updated the package db") |
| 630 |
self.changed = True |
| 631 |
self.exit_params["cache_updated"] = True |
| 632 |
return |
| 633 |
|
| 634 |
cmd = self.pacman_cmd + [ |
| 635 |
"--sync", |
| 636 |
"--refresh", |
| 637 |
] |
| 638 |
if self.m.params["update_cache_extra_args"]: |
| 639 |
cmd += self.m.params["update_cache_extra_args"] |
| 640 |
if self.m.params["force"]: |
| 641 |
cmd += ["--refresh"] |
| 642 |
else: |
| 643 |
# Dump package database to get contents before update |
| 644 |
pre_state = sorted(self._list_database()) |
| 645 |
|
| 646 |
rc, stdout, stderr = self.m.run_command(cmd, check_rc=False) |
| 647 |
self._invalidate_database() |
| 648 |
|
| 649 |
if self.m.params["force"]: |
| 650 |
# Always changed when force=true |
| 651 |
self.exit_params["cache_updated"] = True |
| 652 |
else: |
| 653 |
# Dump package database to get contents after update |
| 654 |
post_state = sorted(self._list_database()) |
| 655 |
# If contents changed, set changed=true |
| 656 |
self.exit_params["cache_updated"] = pre_state != post_state |
| 657 |
if self.exit_params["cache_updated"]: |
| 658 |
self.changed = True |
| 659 |
|
| 660 |
if rc == 0: |
| 661 |
self.add_exit_infos("Updated package db", stdout=stdout, stderr=stderr) |
| 662 |
else: |
| 663 |
self.fail("could not update package db", cmd=cmd, stdout=stdout, stderr=stderr) |
| 664 |
|
| 665 |
def package_list(self): |
| 666 |
"""Takes the input package list and resolves packages groups to their package list using the inventory, |
| 667 |
extracts package names from packages given as files or URLs using calls to pacman |
| 668 |
|
| 669 |
Returns the expanded/resolved list as a list of Package |
| 670 |
""" |
| 671 |
pkg_list = [] |
| 672 |
for pkg in self.m.params["name"]: |
| 673 |
if not pkg: |
| 674 |
continue |
| 675 |
|
| 676 |
is_URL = False |
| 677 |
if pkg in self.inventory["available_groups"]: |
| 678 |
# Expand group members |
| 679 |
for group_member in self.inventory["available_groups"][pkg]: |
| 680 |
pkg_list.append(Package(name=group_member, source=group_member)) |
| 681 |
elif pkg in self.inventory["available_pkgs"] or pkg in self.inventory["installed_pkgs"]: |
| 682 |
# Just a regular pkg, either available in the repositories, |
| 683 |
# or locally installed, which we need to know for absent state |
| 684 |
pkg_list.append(Package(name=pkg, source=pkg)) |
| 685 |
else: |
| 686 |
# Last resort, call out to pacman to extract the info, |
| 687 |
# pkg is possibly in the <repo>/<pkgname> format, or a filename or a URL |
| 688 |
|
| 689 |
# Start with <repo>/<pkgname> case |
| 690 |
cmd = self.pacman_cmd + ["--sync", "--print-format", "%n", pkg] |
| 691 |
rc, stdout, stderr = self.m.run_command(cmd, check_rc=False) |
| 692 |
if rc != 0: |
| 693 |
# fallback to filename / URL |
| 694 |
cmd = self.pacman_cmd + ["--upgrade", "--print-format", "%n", pkg] |
| 695 |
rc, stdout, stderr = self.m.run_command(cmd, check_rc=False) |
| 696 |
if rc != 0: |
| 697 |
if self.target_state == "absent": |
| 698 |
continue # Don't bark for unavailable packages when trying to remove them |
| 699 |
else: |
| 700 |
self.fail( |
| 701 |
msg=f"Failed to list package {pkg}", |
| 702 |
cmd=cmd, |
| 703 |
stdout=stdout, |
| 704 |
stderr=stderr, |
| 705 |
rc=rc, |
| 706 |
) |
| 707 |
# With Pacman v6.0.1 - libalpm v13.0.1, --upgrade outputs " filename_without_extension downloading..." if the URL is unseen. |
| 708 |
# In all cases, pacman outputs "loading packages..." on stdout. strip both |
| 709 |
stdout = stdout.splitlines()[-1] |
| 710 |
is_URL = True |
| 711 |
pkg_name = stdout.strip() |
| 712 |
pkg_list.append(Package(name=pkg_name, source=pkg, source_is_URL=is_URL)) |
| 713 |
|
| 714 |
return pkg_list |
| 715 |
|
| 716 |
def _build_inventory(self): |
| 717 |
"""Build a cache datastructure used for all pkg lookups |
| 718 |
Returns a dict: |
| 719 |
{ |
| 720 |
"installed_pkgs": {pkgname: version}, |
| 721 |
"installed_groups": {groupname: set(pkgnames)}, |
| 722 |
"available_pkgs": {pkgname: version}, |
| 723 |
"available_groups": {groupname: set(pkgnames)}, |
| 724 |
"upgradable_pkgs": {pkgname: VersionTuple}, |
| 725 |
"pkg_reasons": {pkgname: reason}, |
| 726 |
} |
| 727 |
|
| 728 |
Fails the module if a package requested for install cannot be found |
| 729 |
""" |
| 730 |
|
| 731 |
installed_pkgs = {} |
| 732 |
dummy, stdout, dummy = self.m.run_command(self.pacman_cmd + ["--query"], check_rc=True) |
| 733 |
# Format of a line: "pacman 6.0.1-2" |
| 734 |
query_re = re.compile(r"^\s*(?P<pkg>\S+)\s+(?P<ver>\S+)\s*$") |
| 735 |
for l in stdout.splitlines(): |
| 736 |
query_match = query_re.match(l) |
| 737 |
if not query_match: |
| 738 |
continue |
| 739 |
pkg, ver = query_match.groups() |
| 740 |
installed_pkgs[pkg] = ver |
| 741 |
|
| 742 |
installed_groups = defaultdict(set) |
| 743 |
dummy, stdout, dummy = self.m.run_command(self.pacman_cmd + ["--query", "--groups"], check_rc=True) |
| 744 |
# Format of lines: |
| 745 |
# base-devel file |
| 746 |
# base-devel findutils |
| 747 |
# ... |
| 748 |
query_groups_re = re.compile(r"^\s*(?P<group>\S+)\s+(?P<pkg>\S+)\s*$") |
| 749 |
for l in stdout.splitlines(): |
| 750 |
query_groups_match = query_groups_re.match(l) |
| 751 |
if not query_groups_match: |
| 752 |
continue |
| 753 |
group, pkgname = query_groups_match.groups() |
| 754 |
installed_groups[group].add(pkgname) |
| 755 |
|
| 756 |
available_pkgs = {} |
| 757 |
database = self._list_database() |
| 758 |
# Format of a line: "core pacman 6.0.1-2" |
| 759 |
for l in database: |
| 760 |
l = l.strip() |
| 761 |
if not l: |
| 762 |
continue |
| 763 |
repo, pkg, ver = l.split()[:3] |
| 764 |
available_pkgs[pkg] = ver |
| 765 |
|
| 766 |
available_groups = defaultdict(set) |
| 767 |
dummy, stdout, dummy = self.m.run_command(self.pacman_cmd + ["--sync", "--groups", "--groups"], check_rc=True) |
| 768 |
# Format of lines: |
| 769 |
# vim-plugins vim-airline |
| 770 |
# vim-plugins vim-airline-themes |
| 771 |
# vim-plugins vim-ale |
| 772 |
# ... |
| 773 |
sync_groups_re = re.compile(r"^\s*(?P<group>\S+)\s+(?P<pkg>\S+)\s*$") |
| 774 |
for l in stdout.splitlines(): |
| 775 |
sync_groups_match = sync_groups_re.match(l) |
| 776 |
if not sync_groups_match: |
| 777 |
continue |
| 778 |
group, pkg = sync_groups_match.groups() |
| 779 |
available_groups[group].add(pkg) |
| 780 |
|
| 781 |
upgradable_pkgs = {} |
| 782 |
rc, stdout, stderr = self.m.run_command(self.pacman_cmd + ["--query", "--upgrades"], check_rc=False) |
| 783 |
|
| 784 |
stdout = stdout.splitlines() |
| 785 |
if stdout and "Avoid running" in stdout[0]: |
| 786 |
stdout = stdout[1:] |
| 787 |
stdout = "\n".join(stdout) |
| 788 |
|
| 789 |
# non-zero exit with nothing in stdout -> nothing to upgrade, all good |
| 790 |
# stderr can have warnings, so not checked here |
| 791 |
if rc == 1 and not stdout: |
| 792 |
pass # nothing to upgrade |
| 793 |
elif rc == 0: |
| 794 |
# Format of lines: |
| 795 |
# strace 5.14-1 -> 5.15-1 |
| 796 |
# systemd 249.7-1 -> 249.7-2 [ignored] |
| 797 |
for l in stdout.splitlines(): |
| 798 |
l = l.strip() |
| 799 |
if not l: |
| 800 |
continue |
| 801 |
if "[ignored]" in l or "Avoid running" in l: |
| 802 |
continue |
| 803 |
s = l.split() |
| 804 |
if len(s) != 4: |
| 805 |
self.fail(msg=f"Invalid line: {l}") |
| 806 |
|
| 807 |
pkg = s[0] |
| 808 |
current = s[1] |
| 809 |
latest = s[3] |
| 810 |
upgradable_pkgs[pkg] = VersionTuple(current=current, latest=latest) |
| 811 |
else: |
| 812 |
# stuff in stdout but rc!=0, abort |
| 813 |
self.fail( |
| 814 |
"Couldn't get list of packages available for upgrade", |
| 815 |
stdout=stdout, |
| 816 |
stderr=stderr, |
| 817 |
rc=rc, |
| 818 |
) |
| 819 |
|
| 820 |
pkg_reasons = {} |
| 821 |
dummy, stdout, dummy = self.m.run_command(self.pacman_cmd + ["--query", "--explicit"], check_rc=True) |
| 822 |
# Format of a line: "pacman 6.0.1-2" |
| 823 |
for l in stdout.splitlines(): |
| 824 |
l = l.strip() |
| 825 |
if not l: |
| 826 |
continue |
| 827 |
pkg = l.split()[0] |
| 828 |
pkg_reasons[pkg] = "explicit" |
| 829 |
dummy, stdout, dummy = self.m.run_command(self.pacman_cmd + ["--query", "--deps"], check_rc=True) |
| 830 |
# Format of a line: "pacman 6.0.1-2" |
| 831 |
for l in stdout.splitlines(): |
| 832 |
l = l.strip() |
| 833 |
if not l: |
| 834 |
continue |
| 835 |
pkg = l.split()[0] |
| 836 |
pkg_reasons[pkg] = "dependency" |
| 837 |
|
| 838 |
return dict( |
| 839 |
installed_pkgs=installed_pkgs, |
| 840 |
installed_groups=installed_groups, |
| 841 |
available_pkgs=available_pkgs, |
| 842 |
available_groups=available_groups, |
| 843 |
upgradable_pkgs=upgradable_pkgs, |
| 844 |
pkg_reasons=pkg_reasons, |
| 845 |
) |
| 846 |
|
| 847 |
|
| 848 |
def setup_module(): |
| 849 |
module = AnsibleModule( |
| 850 |
argument_spec=dict( |
| 851 |
name=dict(type="list", elements="str", aliases=["pkg", "package"]), |
| 852 |
state=dict( |
| 853 |
type="str", |
| 854 |
default="present", |
| 855 |
choices=["present", "installed", "latest", "absent", "removed"], |
| 856 |
), |
| 857 |
force=dict(type="bool", default=False), |
| 858 |
remove_nosave=dict(type="bool", default=False), |
| 859 |
executable=dict(type="str", default="pacman"), |
| 860 |
extra_args=dict(type="str", default=""), |
| 861 |
root=dict(type="path"), |
| 862 |
cachedir=dict(type="path"), |
| 863 |
config=dict(type="path"), |
| 864 |
upgrade=dict(type="bool"), |
| 865 |
upgrade_extra_args=dict(type="str", default=""), |
| 866 |
update_cache=dict(type="bool"), |
| 867 |
update_cache_extra_args=dict(type="str", default=""), |
| 868 |
reason=dict(type="str", choices=["explicit", "dependency"]), |
| 869 |
reason_for=dict(type="str", default="new", choices=["new", "all"]), |
| 870 |
), |
| 871 |
required_one_of=[["name", "update_cache", "upgrade"]], |
| 872 |
mutually_exclusive=[["name", "upgrade"]], |
| 873 |
supports_check_mode=True, |
| 874 |
) |
| 875 |
|
| 876 |
# Split extra_args as the shell would for easier handling later |
| 877 |
for str_args in ["extra_args", "upgrade_extra_args", "update_cache_extra_args"]: |
| 878 |
module.params[str_args] = shlex.split(module.params[str_args]) |
| 879 |
|
| 880 |
return module |
| 881 |
|
| 882 |
|
| 883 |
def main(): |
| 884 |
Pacman(setup_module()).run() |
| 885 |
|
| 886 |
|
| 887 |
if __name__ == "__main__": |
| 888 |
main() |