| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2013, bleader |
| 4 |
# Written by bleader <[email protected]> |
| 5 |
# Based on pkgin module written by Shaun Zinck <shaun.zinck at gmail.com> |
| 6 |
# that was based on pacman module written by Afterburn <https://github.com/afterburn> |
| 7 |
# that was based on apt module written by Matthew Williams <[email protected]> |
| 8 |
# |
| 9 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 10 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 11 |
|
| 12 |
from __future__ import annotations |
| 13 |
|
| 14 |
DOCUMENTATION = r""" |
| 15 |
module: pkgng |
| 16 |
short_description: Package manager for FreeBSD >= 9.0 |
| 17 |
description: |
| 18 |
- Manage binary packages for FreeBSD using C(pkgng) which is available in versions after 9.0. |
| 19 |
extends_documentation_fragment: |
| 20 |
- community.general._attributes |
| 21 |
attributes: |
| 22 |
check_mode: |
| 23 |
support: full |
| 24 |
diff_mode: |
| 25 |
support: none |
| 26 |
options: |
| 27 |
name: |
| 28 |
description: |
| 29 |
- Name or list of names of packages to install/remove. |
| 30 |
- With O(name=*), O(state=latest) operates, but O(state=present) and O(state=absent) are noops. |
| 31 |
required: true |
| 32 |
aliases: [pkg] |
| 33 |
type: list |
| 34 |
elements: str |
| 35 |
state: |
| 36 |
description: |
| 37 |
- State of the package. |
| 38 |
choices: ['present', 'latest', 'absent'] |
| 39 |
default: present |
| 40 |
type: str |
| 41 |
cached: |
| 42 |
description: |
| 43 |
- Use local package base instead of fetching an updated one. |
| 44 |
type: bool |
| 45 |
default: false |
| 46 |
annotation: |
| 47 |
description: |
| 48 |
- A list of keyvalue-pairs of the form C(<+/-/:><key>[=<value>]). A V(+) denotes adding an annotation, a V(-) denotes |
| 49 |
removing an annotation, and V(:) denotes modifying an annotation. If setting or modifying annotations, a value must |
| 50 |
be provided. |
| 51 |
type: list |
| 52 |
elements: str |
| 53 |
pkgsite: |
| 54 |
description: |
| 55 |
- For C(pkgng) versions before 1.1.4, specify C(packagesite) to use for downloading packages. If not specified, use |
| 56 |
settings from C(/usr/local/etc/pkg.conf). |
| 57 |
- For newer C(pkgng) versions, specify a the name of a repository configured in C(/usr/local/etc/pkg/repos). |
| 58 |
type: str |
| 59 |
rootdir: |
| 60 |
description: |
| 61 |
- For C(pkgng) versions 1.5 and later, pkg installs all packages within the specified root directory. |
| 62 |
- Can not be used together with O(chroot) or O(jail) options. |
| 63 |
type: path |
| 64 |
chroot: |
| 65 |
description: |
| 66 |
- Pkg chroots in the specified environment. |
| 67 |
- Can not be used together with O(rootdir) or O(jail) options. |
| 68 |
type: path |
| 69 |
jail: |
| 70 |
description: |
| 71 |
- Pkg executes in the given jail name or ID. |
| 72 |
- Can not be used together with O(chroot) or O(rootdir) options. |
| 73 |
type: str |
| 74 |
autoremove: |
| 75 |
description: |
| 76 |
- Remove automatically installed packages which are no longer needed. |
| 77 |
type: bool |
| 78 |
default: false |
| 79 |
ignore_osver: |
| 80 |
description: |
| 81 |
- Ignore FreeBSD OS version check, useful on C(-STABLE) and C(-CURRENT) branches. |
| 82 |
- Defines the E(IGNORE_OSVERSION) environment variable. |
| 83 |
type: bool |
| 84 |
default: false |
| 85 |
version_added: 1.3.0 |
| 86 |
use_globs: |
| 87 |
description: |
| 88 |
- Treat the package names as shell glob patterns. |
| 89 |
type: bool |
| 90 |
default: true |
| 91 |
version_added: 9.3.0 |
| 92 |
author: "bleader (@bleader)" |
| 93 |
notes: |
| 94 |
- When using pkgsite, be careful that already in cache packages are not downloaded again. |
| 95 |
- When used with a C(loop:) each package is processed individually, it is much more efficient to pass the list directly |
| 96 |
to the O(name) option. |
| 97 |
""" |
| 98 |
|
| 99 |
EXAMPLES = r""" |
| 100 |
- name: Install package foo |
| 101 |
community.general.pkgng: |
| 102 |
name: foo |
| 103 |
state: present |
| 104 |
|
| 105 |
- name: Annotate package foo and bar |
| 106 |
community.general.pkgng: |
| 107 |
name: |
| 108 |
- foo |
| 109 |
- bar |
| 110 |
annotation: '+test1=baz,-test2,:test3=foobar' |
| 111 |
|
| 112 |
- name: Remove packages foo and bar |
| 113 |
community.general.pkgng: |
| 114 |
name: |
| 115 |
- foo |
| 116 |
- bar |
| 117 |
state: absent |
| 118 |
|
| 119 |
- name: Upgrade package baz |
| 120 |
community.general.pkgng: |
| 121 |
name: baz |
| 122 |
state: latest |
| 123 |
|
| 124 |
- name: Upgrade all installed packages (see warning for the name option first!) |
| 125 |
community.general.pkgng: |
| 126 |
name: "*" |
| 127 |
state: latest |
| 128 |
|
| 129 |
- name: Upgrade foo/bar |
| 130 |
community.general.pkgng: |
| 131 |
name: foo/bar |
| 132 |
state: latest |
| 133 |
use_globs: false |
| 134 |
""" |
| 135 |
|
| 136 |
|
| 137 |
import re |
| 138 |
from collections import defaultdict |
| 139 |
|
| 140 |
from ansible.module_utils.basic import AnsibleModule |
| 141 |
|
| 142 |
|
| 143 |
def query_package(module, run_pkgng, name): |
| 144 |
rc, out, err = run_pkgng("info", "-e", name) |
| 145 |
|
| 146 |
return rc == 0 |
| 147 |
|
| 148 |
|
| 149 |
def query_update(module, run_pkgng, name): |
| 150 |
# Check to see if a package upgrade is available. |
| 151 |
# rc = 0, no updates available or package not installed |
| 152 |
# rc = 1, updates available |
| 153 |
rc, out, err = run_pkgng("upgrade", "-n", name) |
| 154 |
|
| 155 |
return rc == 1 |
| 156 |
|
| 157 |
|
| 158 |
def pkgng_older_than(module, pkgng_path, compare_version): |
| 159 |
rc, out, err = module.run_command([pkgng_path, "-v"], environ_update={"LANGUAGE": "C", "LC_ALL": "C"}) |
| 160 |
version = [int(x) for x in re.split(r"[\._]", out)] |
| 161 |
|
| 162 |
i = 0 |
| 163 |
new_pkgng = True |
| 164 |
while compare_version[i] == version[i]: |
| 165 |
i += 1 |
| 166 |
if i == min(len(compare_version), len(version)): |
| 167 |
break |
| 168 |
else: |
| 169 |
if compare_version[i] > version[i]: |
| 170 |
new_pkgng = False |
| 171 |
return not new_pkgng |
| 172 |
|
| 173 |
|
| 174 |
def upgrade_packages(module, run_pkgng): |
| 175 |
# Run a 'pkg upgrade', updating all packages. |
| 176 |
upgraded_c = 0 |
| 177 |
|
| 178 |
pkgng_args = ["upgrade"] |
| 179 |
pkgng_args.append("-n" if module.check_mode else "-y") |
| 180 |
rc, out, err = run_pkgng(*pkgng_args, check_rc=(not module.check_mode)) |
| 181 |
|
| 182 |
matches = re.findall("^Number of packages to be (?:upgraded|reinstalled): ([0-9]+)", out, re.MULTILINE) |
| 183 |
for match in matches: |
| 184 |
upgraded_c += int(match) |
| 185 |
|
| 186 |
if upgraded_c > 0: |
| 187 |
return (True, f"updated {upgraded_c} package(s)", out, err) |
| 188 |
return (False, "no packages need upgrades", out, err) |
| 189 |
|
| 190 |
|
| 191 |
def remove_packages(module, run_pkgng, packages): |
| 192 |
remove_c = 0 |
| 193 |
stdout = "" |
| 194 |
stderr = "" |
| 195 |
# Using a for loop in case of error, we can report the package that failed |
| 196 |
for package in packages: |
| 197 |
# Query the package first, to see if we even need to remove |
| 198 |
if not query_package(module, run_pkgng, package): |
| 199 |
continue |
| 200 |
|
| 201 |
if not module.check_mode: |
| 202 |
rc, out, err = run_pkgng("delete", "-y", package) |
| 203 |
stdout += out |
| 204 |
stderr += err |
| 205 |
|
| 206 |
if not module.check_mode and query_package(module, run_pkgng, package): |
| 207 |
module.fail_json(msg=f"failed to remove {package}: {out}", stdout=stdout, stderr=stderr) |
| 208 |
|
| 209 |
remove_c += 1 |
| 210 |
|
| 211 |
if remove_c > 0: |
| 212 |
return (True, f"removed {remove_c} package(s)", stdout, stderr) |
| 213 |
|
| 214 |
return (False, "package(s) already absent", stdout, stderr) |
| 215 |
|
| 216 |
|
| 217 |
def install_packages(module, run_pkgng, packages, cached, state): |
| 218 |
action_queue = defaultdict(list) |
| 219 |
action_count = defaultdict(int) |
| 220 |
stdout = "" |
| 221 |
stderr = "" |
| 222 |
|
| 223 |
if not module.check_mode and not cached: |
| 224 |
rc, out, err = run_pkgng("update") |
| 225 |
stdout += out |
| 226 |
stderr += err |
| 227 |
if rc != 0: |
| 228 |
module.fail_json(msg=f"Could not update catalogue [{rc}]: {out} {err}", stdout=stdout, stderr=stderr) |
| 229 |
|
| 230 |
for package in packages: |
| 231 |
already_installed = query_package(module, run_pkgng, package) |
| 232 |
if already_installed and state == "present": |
| 233 |
continue |
| 234 |
|
| 235 |
if already_installed and state == "latest" and not query_update(module, run_pkgng, package): |
| 236 |
continue |
| 237 |
|
| 238 |
if already_installed: |
| 239 |
action_queue["upgrade"].append(package) |
| 240 |
else: |
| 241 |
action_queue["install"].append(package) |
| 242 |
|
| 243 |
# install/upgrade all named packages with one pkg command |
| 244 |
for action, package_list in action_queue.items(): |
| 245 |
if module.check_mode: |
| 246 |
# Do nothing, but count up how many actions |
| 247 |
# would be performed so that the changed/msg |
| 248 |
# is correct. |
| 249 |
action_count[action] += len(package_list) |
| 250 |
continue |
| 251 |
|
| 252 |
pkgng_args = [action, "-U", "-y"] + package_list |
| 253 |
rc, out, err = run_pkgng(*pkgng_args) |
| 254 |
stdout += out |
| 255 |
stderr += err |
| 256 |
|
| 257 |
# individually verify packages are in requested state |
| 258 |
for package in package_list: |
| 259 |
verified = False |
| 260 |
if action == "install": |
| 261 |
verified = query_package(module, run_pkgng, package) |
| 262 |
elif action == "upgrade": |
| 263 |
verified = not query_update(module, run_pkgng, package) |
| 264 |
|
| 265 |
if verified: |
| 266 |
action_count[action] += 1 |
| 267 |
else: |
| 268 |
module.fail_json(msg=f"failed to {action} {package}", stdout=stdout, stderr=stderr) |
| 269 |
|
| 270 |
if sum(action_count.values()) > 0: |
| 271 |
past_tense = {"install": "installed", "upgrade": "upgraded"} |
| 272 |
messages = [] |
| 273 |
for action, count in action_count.items(): |
| 274 |
messages.append(f"{past_tense.get(action, action)} {count} package{'s' if count != 1 else ''}") |
| 275 |
|
| 276 |
return (True, "; ".join(messages), stdout, stderr) |
| 277 |
|
| 278 |
return (False, f"package(s) already {state}", stdout, stderr) |
| 279 |
|
| 280 |
|
| 281 |
def annotation_query(module, run_pkgng, package, tag): |
| 282 |
rc, out, err = run_pkgng("info", "-A", package) |
| 283 |
match = re.search(rf"^\s*(?P<tag>{tag})\s*:\s*(?P<value>\w+)", out, flags=re.MULTILINE) |
| 284 |
if match: |
| 285 |
return match.group("value") |
| 286 |
return False |
| 287 |
|
| 288 |
|
| 289 |
def annotation_add(module, run_pkgng, package, tag, value): |
| 290 |
_value = annotation_query(module, run_pkgng, package, tag) |
| 291 |
if not _value: |
| 292 |
# Annotation does not exist, add it. |
| 293 |
if not module.check_mode: |
| 294 |
rc, out, err = run_pkgng("annotate", "-y", "-A", package, tag, data=value, binary_data=True) |
| 295 |
if rc != 0: |
| 296 |
module.fail_json(msg=f"could not annotate {package}: {out}", stderr=err) |
| 297 |
return True |
| 298 |
elif _value != value: |
| 299 |
# Annotation exists, but value differs |
| 300 |
module.fail_json( |
| 301 |
msg=f"failed to annotate {package}, because {tag} is already set to {_value}, but should be set to {value}" |
| 302 |
) |
| 303 |
return False |
| 304 |
else: |
| 305 |
# Annotation exists, nothing to do |
| 306 |
return False |
| 307 |
|
| 308 |
|
| 309 |
def annotation_delete(module, run_pkgng, package, tag, value): |
| 310 |
_value = annotation_query(module, run_pkgng, package, tag) |
| 311 |
if _value: |
| 312 |
if not module.check_mode: |
| 313 |
rc, out, err = run_pkgng("annotate", "-y", "-D", package, tag) |
| 314 |
if rc != 0: |
| 315 |
module.fail_json(msg=f"could not delete annotation to {package}: {out}", stderr=err) |
| 316 |
return True |
| 317 |
return False |
| 318 |
|
| 319 |
|
| 320 |
def annotation_modify(module, run_pkgng, package, tag, value): |
| 321 |
_value = annotation_query(module, run_pkgng, package, tag) |
| 322 |
if not _value: |
| 323 |
# No such tag |
| 324 |
module.fail_json(msg=f"could not change annotation to {package}: tag {tag} does not exist") |
| 325 |
elif _value == value: |
| 326 |
# No change in value |
| 327 |
return False |
| 328 |
else: |
| 329 |
if not module.check_mode: |
| 330 |
rc, out, err = run_pkgng("annotate", "-y", "-M", package, tag, data=value, binary_data=True) |
| 331 |
|
| 332 |
# pkg sometimes exits with rc == 1, even though the modification succeeded |
| 333 |
# Check the output for a success message |
| 334 |
if ( |
| 335 |
rc != 0 |
| 336 |
and re.search(rf"^{package}-[^:]+: Modified annotation tagged: {tag}", out, flags=re.MULTILINE) is None |
| 337 |
): |
| 338 |
module.fail_json( |
| 339 |
msg=f"failed to annotate {package}, could not change annotation {tag} to {value}: {out}", stderr=err |
| 340 |
) |
| 341 |
return True |
| 342 |
|
| 343 |
|
| 344 |
def annotate_packages(module, run_pkgng, packages, annotations): |
| 345 |
annotate_c = 0 |
| 346 |
if len(annotations) == 1: |
| 347 |
# Split on commas with optional trailing whitespace, |
| 348 |
# to support the old style of multiple annotations |
| 349 |
# on a single line, rather than YAML list syntax |
| 350 |
annotations = re.split(r"\s*,\s*", annotations[0]) |
| 351 |
|
| 352 |
operation = {"+": annotation_add, "-": annotation_delete, ":": annotation_modify} |
| 353 |
|
| 354 |
for package in packages: |
| 355 |
for annotation_string in annotations: |
| 356 |
# Note to future maintainers: A dash (-) in a regex character class ([-+:] below) |
| 357 |
# must appear as the first character in the class, or it will be interpreted |
| 358 |
# as a range of characters. |
| 359 |
annotation = re.match(r"(?P<operation>[-+:])(?P<tag>[^=]+)(=(?P<value>.+))?", annotation_string) |
| 360 |
|
| 361 |
if annotation is None: |
| 362 |
module.fail_json(msg=f"failed to annotate {package}, invalid annotate string: {annotation_string}") |
| 363 |
|
| 364 |
annotation = annotation.groupdict() |
| 365 |
if operation[annotation["operation"]](module, run_pkgng, package, annotation["tag"], annotation["value"]): |
| 366 |
annotate_c += 1 |
| 367 |
|
| 368 |
if annotate_c > 0: |
| 369 |
return (True, f"added {annotate_c} annotations.") |
| 370 |
return (False, "changed no annotations") |
| 371 |
|
| 372 |
|
| 373 |
def autoremove_packages(module, run_pkgng): |
| 374 |
stdout = "" |
| 375 |
stderr = "" |
| 376 |
rc, out, err = run_pkgng("autoremove", "-n") |
| 377 |
|
| 378 |
autoremove_c = 0 |
| 379 |
|
| 380 |
match = re.search("^Deinstallation has been requested for the following ([0-9]+) packages", out, re.MULTILINE) |
| 381 |
if match: |
| 382 |
autoremove_c = int(match.group(1)) |
| 383 |
|
| 384 |
if autoremove_c == 0: |
| 385 |
return (False, "no package(s) to autoremove", stdout, stderr) |
| 386 |
|
| 387 |
if not module.check_mode: |
| 388 |
rc, out, err = run_pkgng("autoremove", "-y") |
| 389 |
stdout += out |
| 390 |
stderr += err |
| 391 |
|
| 392 |
return (True, f"autoremoved {autoremove_c} package(s)", stdout, stderr) |
| 393 |
|
| 394 |
|
| 395 |
def main(): |
| 396 |
module = AnsibleModule( |
| 397 |
argument_spec=dict( |
| 398 |
state=dict(default="present", choices=["present", "latest", "absent"]), |
| 399 |
name=dict(aliases=["pkg"], required=True, type="list", elements="str"), |
| 400 |
cached=dict(default=False, type="bool"), |
| 401 |
ignore_osver=dict(default=False, type="bool"), |
| 402 |
annotation=dict(type="list", elements="str"), |
| 403 |
pkgsite=dict(), |
| 404 |
rootdir=dict(type="path"), |
| 405 |
chroot=dict(type="path"), |
| 406 |
jail=dict(type="str"), |
| 407 |
autoremove=dict(default=False, type="bool"), |
| 408 |
use_globs=dict(default=True, type="bool"), |
| 409 |
), |
| 410 |
supports_check_mode=True, |
| 411 |
mutually_exclusive=[["rootdir", "chroot", "jail"]], |
| 412 |
) |
| 413 |
|
| 414 |
pkgng_path = module.get_bin_path("pkg", True) |
| 415 |
|
| 416 |
p = module.params |
| 417 |
|
| 418 |
pkgs = p["name"] |
| 419 |
|
| 420 |
changed = False |
| 421 |
msgs = [] |
| 422 |
stdout = "" |
| 423 |
stderr = "" |
| 424 |
dir_arg = None |
| 425 |
|
| 426 |
if p["rootdir"] is not None: |
| 427 |
rootdir_not_supported = pkgng_older_than(module, pkgng_path, [1, 5, 0]) |
| 428 |
if rootdir_not_supported: |
| 429 |
module.fail_json(msg="To use option 'rootdir' pkg version must be 1.5 or greater") |
| 430 |
else: |
| 431 |
dir_arg = f"--rootdir={p['rootdir']}" |
| 432 |
|
| 433 |
if p["ignore_osver"]: |
| 434 |
ignore_osver_not_supported = pkgng_older_than(module, pkgng_path, [1, 11, 0]) |
| 435 |
if ignore_osver_not_supported: |
| 436 |
module.fail_json(msg="To use option 'ignore_osver' pkg version must be 1.11 or greater") |
| 437 |
|
| 438 |
if p["chroot"] is not None: |
| 439 |
dir_arg = f"--chroot={p['chroot']}" |
| 440 |
|
| 441 |
if p["jail"] is not None: |
| 442 |
dir_arg = f"--jail={p['jail']}" |
| 443 |
|
| 444 |
# as of pkg-1.1.4, PACKAGESITE is deprecated in favor of repository definitions |
| 445 |
# in /usr/local/etc/pkg/repos |
| 446 |
repo_flag_not_supported = pkgng_older_than(module, pkgng_path, [1, 1, 4]) |
| 447 |
|
| 448 |
def run_pkgng(action, *args, **kwargs): |
| 449 |
cmd = [pkgng_path, dir_arg, action] |
| 450 |
|
| 451 |
if p["use_globs"] and action in ( |
| 452 |
"info", |
| 453 |
"install", |
| 454 |
"upgrade", |
| 455 |
): |
| 456 |
args = ("-g",) + args |
| 457 |
|
| 458 |
pkgng_env = {"BATCH": "yes", "LANGUAGE": "C", "LC_ALL": "C"} |
| 459 |
|
| 460 |
if p["ignore_osver"]: |
| 461 |
pkgng_env["IGNORE_OSVERSION"] = "yes" |
| 462 |
|
| 463 |
if p["pkgsite"] is not None and action in ( |
| 464 |
"update", |
| 465 |
"install", |
| 466 |
"upgrade", |
| 467 |
): |
| 468 |
if repo_flag_not_supported: |
| 469 |
pkgng_env["PACKAGESITE"] = p["pkgsite"] |
| 470 |
else: |
| 471 |
cmd.append(f"--repository={p['pkgsite']}") |
| 472 |
|
| 473 |
# If environ_update is specified to be "passed through" |
| 474 |
# to module.run_command, then merge its values into pkgng_env |
| 475 |
pkgng_env.update(kwargs.pop("environ_update", dict())) |
| 476 |
|
| 477 |
return module.run_command(cmd + list(args), environ_update=pkgng_env, **kwargs) |
| 478 |
|
| 479 |
if pkgs == ["*"] and p["state"] == "latest": |
| 480 |
# Operate on all installed packages. Only state: latest makes sense here. |
| 481 |
_changed, _msg, _stdout, _stderr = upgrade_packages(module, run_pkgng) |
| 482 |
changed = changed or _changed |
| 483 |
stdout += _stdout |
| 484 |
stderr += _stderr |
| 485 |
msgs.append(_msg) |
| 486 |
|
| 487 |
# Operate on named packages |
| 488 |
if len(pkgs) == 1: |
| 489 |
# The documentation used to show multiple packages specified in one line |
| 490 |
# with comma or space delimiters. That doesn't result in a YAML list, and |
| 491 |
# wrong actions (install vs upgrade) can be reported if those |
| 492 |
# comma- or space-delimited strings make it to the pkg command line. |
| 493 |
pkgs = re.split(r"[,\s]", pkgs[0]) |
| 494 |
named_packages = [pkg for pkg in pkgs if pkg != "*"] |
| 495 |
if p["state"] in ("present", "latest") and named_packages: |
| 496 |
_changed, _msg, _out, _err = install_packages(module, run_pkgng, named_packages, p["cached"], p["state"]) |
| 497 |
stdout += _out |
| 498 |
stderr += _err |
| 499 |
changed = changed or _changed |
| 500 |
msgs.append(_msg) |
| 501 |
|
| 502 |
elif p["state"] == "absent" and named_packages: |
| 503 |
_changed, _msg, _out, _err = remove_packages(module, run_pkgng, named_packages) |
| 504 |
stdout += _out |
| 505 |
stderr += _err |
| 506 |
changed = changed or _changed |
| 507 |
msgs.append(_msg) |
| 508 |
|
| 509 |
if p["autoremove"]: |
| 510 |
_changed, _msg, _stdout, _stderr = autoremove_packages(module, run_pkgng) |
| 511 |
changed = changed or _changed |
| 512 |
stdout += _stdout |
| 513 |
stderr += _stderr |
| 514 |
msgs.append(_msg) |
| 515 |
|
| 516 |
if p["annotation"] is not None: |
| 517 |
_changed, _msg = annotate_packages(module, run_pkgng, pkgs, p["annotation"]) |
| 518 |
changed = changed or _changed |
| 519 |
msgs.append(_msg) |
| 520 |
|
| 521 |
module.exit_json(changed=changed, msg=", ".join(msgs), stdout=stdout, stderr=stderr) |
| 522 |
|
| 523 |
|
| 524 |
if __name__ == "__main__": |
| 525 |
main() |