| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# Copyright 2015 Cristian van Ee <cristian at cvee.org> |
| 3 |
# Copyright 2015 Igor Gnatenko <[email protected]> |
| 4 |
# Copyright 2018 Adam Miller <[email protected]> |
| 5 |
# Copyright: Contributors to the Ansible project |
| 6 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
|
| 8 |
# NOTE: This file intentionally supports a wider variety of python versions than does |
| 9 |
# ansible.module_utils.basic, specifically on the lower bounds. The intent is for this |
| 10 |
# to work against the system python where the dnf python bindings are supported. |
| 11 |
# |
| 12 |
# Requires-Python: ">=3.6" |
| 13 |
|
| 14 |
import json |
| 15 |
import os |
| 16 |
import sys |
| 17 |
|
| 18 |
try: |
| 19 |
import dnf |
| 20 |
import dnf.const |
| 21 |
import dnf.exceptions |
| 22 |
import dnf.module.module_base |
| 23 |
import dnf.package |
| 24 |
import dnf.subject |
| 25 |
import dnf.util |
| 26 |
|
| 27 |
HAS_DNF = True |
| 28 |
except ImportError: |
| 29 |
HAS_DNF = False |
| 30 |
|
| 31 |
|
| 32 |
class _DnfScriptError(Exception): |
| 33 |
"""Exception raised for DNF script errors with structured error information.""" |
| 34 |
|
| 35 |
def __init__(self, msg, failures=None, results=None, rc=1): |
| 36 |
"""Initialize DNF script error.""" |
| 37 |
self.msg = msg |
| 38 |
self.failures = failures or [] |
| 39 |
self.results = results or [] |
| 40 |
self.rc = rc |
| 41 |
super().__init__(msg) |
| 42 |
|
| 43 |
def to_dict(self): |
| 44 |
"""Convert exception to dict format for JSON response.""" |
| 45 |
return {'changed': False, 'msg': self.msg, 'failures': self.failures, 'results': self.results, 'rc': self.rc, 'failed': True} |
| 46 |
|
| 47 |
|
| 48 |
def _package_to_envra(package): |
| 49 |
"""Convert a dnf.package.Package object to ENVRA string (epoch always included).""" |
| 50 |
return f'{package.epoch}:{package.name}-{package.version}-{package.release}.{package.arch}' |
| 51 |
|
| 52 |
|
| 53 |
class _DnfJSONEncoder(json.JSONEncoder): |
| 54 |
"""Custom JSON encoder that handles dnf-specific objects.""" |
| 55 |
|
| 56 |
def default(self, o): |
| 57 |
if isinstance(o, dnf.package.Package): |
| 58 |
return self._package_to_dict(o) |
| 59 |
return super().default(o) |
| 60 |
|
| 61 |
@staticmethod |
| 62 |
def _package_to_dict(package): |
| 63 |
"""Convert a dnf.package.Package object to a dictionary.""" |
| 64 |
result = { |
| 65 |
'name': package.name, |
| 66 |
'arch': package.arch, |
| 67 |
'epoch': f'{package.epoch}', |
| 68 |
'release': package.release, |
| 69 |
'version': package.version, |
| 70 |
'repo': package.repoid, |
| 71 |
} |
| 72 |
|
| 73 |
result['envra'] = _package_to_envra(package) |
| 74 |
result['nevra'] = result['envra'] |
| 75 |
|
| 76 |
if package.installtime == 0: |
| 77 |
result['yumstate'] = 'available' |
| 78 |
else: |
| 79 |
result['yumstate'] = 'installed' |
| 80 |
|
| 81 |
return result |
| 82 |
|
| 83 |
|
| 84 |
def _exit_json(response): |
| 85 |
"""Output JSON response and exit with appropriate code.""" |
| 86 |
json.dump(response, sys.stdout, cls=_DnfJSONEncoder) |
| 87 |
sys.exit(1 if response.get('failed') else 0) # pylint: disable=ansible-bad-function |
| 88 |
|
| 89 |
|
| 90 |
def _configure_base(base, config_dict): |
| 91 |
"""Configure the dnf Base object. Returns list of warnings.""" |
| 92 |
warnings = [] |
| 93 |
conf = base.conf |
| 94 |
|
| 95 |
conf_file = config_dict.get('conf_file') |
| 96 |
if conf_file: |
| 97 |
if not os.access(conf_file, os.R_OK): |
| 98 |
raise _DnfScriptError(f'cannot read configuration file: {conf_file}') |
| 99 |
conf.config_file_path = conf_file |
| 100 |
|
| 101 |
conf.read() |
| 102 |
conf.debuglevel = 0 |
| 103 |
|
| 104 |
disable_gpg_check = config_dict.get('disable_gpg_check', False) |
| 105 |
conf.gpgcheck = not disable_gpg_check |
| 106 |
conf.localpkg_gpgcheck = not disable_gpg_check |
| 107 |
conf.assumeyes = True |
| 108 |
|
| 109 |
sslverify = config_dict.get('sslverify', True) |
| 110 |
conf.sslverify = sslverify |
| 111 |
|
| 112 |
installroot = config_dict.get('installroot', '/') |
| 113 |
if not os.path.isdir(installroot): |
| 114 |
raise _DnfScriptError(f'Installroot {installroot} must be a directory') |
| 115 |
|
| 116 |
conf.installroot = installroot |
| 117 |
conf.substitutions.update_from_etc(installroot) |
| 118 |
|
| 119 |
exclude = config_dict.get('exclude', []) |
| 120 |
if exclude: |
| 121 |
_excludes = list(conf.exclude) |
| 122 |
_excludes.extend(exclude) |
| 123 |
conf.exclude = _excludes |
| 124 |
|
| 125 |
disable_excludes = config_dict.get('disable_excludes') |
| 126 |
if disable_excludes: |
| 127 |
_disable_excludes = list(conf.disable_excludes) |
| 128 |
if disable_excludes not in _disable_excludes: |
| 129 |
_disable_excludes.append(disable_excludes) |
| 130 |
conf.disable_excludes = _disable_excludes |
| 131 |
|
| 132 |
releasever = config_dict.get('releasever') |
| 133 |
if releasever is not None: |
| 134 |
conf.substitutions['releasever'] = releasever |
| 135 |
|
| 136 |
if conf.substitutions.get('releasever') is None: |
| 137 |
warnings.append('Unable to detect release version (use "releasever" option to specify release version)') |
| 138 |
conf.substitutions['releasever'] = '' |
| 139 |
|
| 140 |
for opt in ('cachedir', 'logdir', 'persistdir'): |
| 141 |
conf.prepend_installroot(opt) |
| 142 |
|
| 143 |
skip_broken = config_dict.get('skip_broken', False) |
| 144 |
if skip_broken: |
| 145 |
conf.strict = 0 |
| 146 |
|
| 147 |
nobest = config_dict.get('nobest') |
| 148 |
best = config_dict.get('best') |
| 149 |
if nobest is not None: |
| 150 |
conf.best = not nobest |
| 151 |
elif best is not None: |
| 152 |
conf.best = best |
| 153 |
|
| 154 |
download_only = config_dict.get('download_only', False) |
| 155 |
if download_only: |
| 156 |
conf.downloadonly = True |
| 157 |
download_dir = config_dict.get('download_dir') |
| 158 |
if download_dir: |
| 159 |
conf.destdir = download_dir |
| 160 |
|
| 161 |
cacheonly = config_dict.get('cacheonly', False) |
| 162 |
if cacheonly: |
| 163 |
conf.cacheonly = True |
| 164 |
|
| 165 |
autoremove = config_dict.get('autoremove', False) |
| 166 |
conf.clean_requirements_on_remove = autoremove |
| 167 |
|
| 168 |
install_weak_deps = config_dict.get('install_weak_deps', True) |
| 169 |
conf.install_weak_deps = install_weak_deps |
| 170 |
|
| 171 |
return warnings |
| 172 |
|
| 173 |
|
| 174 |
def _configure_repos(base, disablerepo_list, enablerepo_list, disable_gpg_check): |
| 175 |
"""Enable and disable repositories matching the provided patterns.""" |
| 176 |
repos = base.repos |
| 177 |
|
| 178 |
for repo_pattern in disablerepo_list: |
| 179 |
if repo_pattern: |
| 180 |
for repo in repos.get_matching(repo_pattern): |
| 181 |
repo.disable() |
| 182 |
|
| 183 |
for repo_pattern in enablerepo_list: |
| 184 |
if repo_pattern: |
| 185 |
for repo in repos.get_matching(repo_pattern): |
| 186 |
repo.enable() |
| 187 |
|
| 188 |
if disable_gpg_check: |
| 189 |
for repo in base.repos.iter_enabled(): |
| 190 |
repo.gpgcheck = False |
| 191 |
repo.repo_gpgcheck = False |
| 192 |
|
| 193 |
|
| 194 |
def _init_plugins(base, disable_plugin_list, enable_plugin_list): |
| 195 |
"""Initialize and configure plugins.""" |
| 196 |
base.setup_loggers() |
| 197 |
base.init_plugins(set(disable_plugin_list), set(enable_plugin_list)) |
| 198 |
base.pre_configure_plugins() |
| 199 |
|
| 200 |
|
| 201 |
def _add_security_filters(base, bugfix, security): |
| 202 |
"""Add security and bugfix filters for package upgrades.""" |
| 203 |
add_security_filters_method = getattr(base, 'add_security_filters', None) |
| 204 |
if callable(add_security_filters_method): |
| 205 |
filters = {} |
| 206 |
if bugfix: |
| 207 |
filters.setdefault('types', []).append('bugfix') |
| 208 |
if security: |
| 209 |
filters.setdefault('types', []).append('security') |
| 210 |
if filters: |
| 211 |
add_security_filters_method('eq', **filters) |
| 212 |
else: |
| 213 |
# Fallback for older dnf versions |
| 214 |
filters = [] |
| 215 |
if bugfix: |
| 216 |
key = {'advisory_type__eq': 'bugfix'} |
| 217 |
filters.append(base.sack.query().upgrades().filter(**key)) |
| 218 |
if security: |
| 219 |
key = {'advisory_type__eq': 'security'} |
| 220 |
filters.append(base.sack.query().upgrades().filter(**key)) |
| 221 |
if filters: |
| 222 |
base._update_security_filters = filters |
| 223 |
|
| 224 |
return True |
| 225 |
|
| 226 |
|
| 227 |
def _is_package_installed(base, package_spec): |
| 228 |
"""Check if a package is installed.""" |
| 229 |
return bool(dnf.subject.Subject(package_spec).get_best_query(sack=base.sack).installed()) |
| 230 |
|
| 231 |
|
| 232 |
def _is_newer_version_installed(base, pkg_spec): |
| 233 |
"""Check if a newer version of the package is already installed.""" |
| 234 |
try: |
| 235 |
if isinstance(pkg_spec, dnf.package.Package): |
| 236 |
installed = sorted(base.sack.query().installed().filter(name=pkg_spec.name, arch=pkg_spec.arch))[-1] |
| 237 |
return installed.evr_gt(pkg_spec) |
| 238 |
else: |
| 239 |
solution = dnf.subject.Subject(pkg_spec).get_best_solution(base.sack) |
| 240 |
q = solution['query'] |
| 241 |
nevra = solution['nevra'] |
| 242 |
if not q or not nevra or nevra.has_just_name() or not nevra.version: |
| 243 |
return False |
| 244 |
|
| 245 |
# Filter by name and arch (if specified), but NOT by version |
| 246 |
# since we need to find installed packages to compare versions against |
| 247 |
filter_kwargs = {'name': nevra.name} |
| 248 |
if nevra.arch: |
| 249 |
filter_kwargs['arch'] = nevra.arch |
| 250 |
installed = base.sack.query().installed().filter(**filter_kwargs) |
| 251 |
if not installed: |
| 252 |
return False |
| 253 |
return installed[0].evr_gt(q[0]) |
| 254 |
except IndexError: |
| 255 |
return False |
| 256 |
|
| 257 |
|
| 258 |
def _get_modules(module_base, module_spec): |
| 259 |
"""Get module information for a module specification.""" |
| 260 |
module_spec = module_spec.strip() |
| 261 |
module_list, nsv = module_base._get_modules(module_spec) |
| 262 |
return { |
| 263 |
'module_list': module_list, |
| 264 |
'nsv': {'name': nsv.name if nsv else None, 'stream': nsv.stream if nsv else None, 'version': nsv.version if nsv and hasattr(nsv, 'version') else None}, |
| 265 |
} |
| 266 |
|
| 267 |
|
| 268 |
def _parse_spec_group_file(base, module_base, names, update_only, with_modules): |
| 269 |
"""Parse the names list into package specs, group specs, module specs, and filenames.""" |
| 270 |
pkg_specs, grp_specs, module_specs, filenames = [], [], [], [] |
| 271 |
already_loaded_comps = False |
| 272 |
|
| 273 |
for name in names: |
| 274 |
if '://' in name: |
| 275 |
filenames.append(name) |
| 276 |
elif name.endswith('.rpm'): |
| 277 |
filenames.append(name) |
| 278 |
elif name.startswith('/'): |
| 279 |
installed = base.sack.query().filter(provides=name, file=name).installed().run() |
| 280 |
if installed: |
| 281 |
pkg_specs.append(installed[0].name) |
| 282 |
elif not update_only: |
| 283 |
pkg_specs.append(name) |
| 284 |
elif name.startswith('@') or ('/' in name): |
| 285 |
if not already_loaded_comps: |
| 286 |
base.read_comps() |
| 287 |
already_loaded_comps = True |
| 288 |
|
| 289 |
grp_env_mdl_candidate = name[1:].strip() |
| 290 |
|
| 291 |
if with_modules and module_base: |
| 292 |
mdl_info = _get_modules(module_base, grp_env_mdl_candidate) |
| 293 |
if mdl_info['module_list'] and mdl_info['module_list'][0]: |
| 294 |
module_specs.append(grp_env_mdl_candidate) |
| 295 |
else: |
| 296 |
grp_specs.append(grp_env_mdl_candidate) |
| 297 |
else: |
| 298 |
grp_specs.append(grp_env_mdl_candidate) |
| 299 |
else: |
| 300 |
pkg_specs.append(name) |
| 301 |
|
| 302 |
return pkg_specs, grp_specs, module_specs, filenames |
| 303 |
|
| 304 |
|
| 305 |
def _update_only_helper(base, pkgs): |
| 306 |
"""Handle update_only logic for packages. Returns list of not installed packages.""" |
| 307 |
not_installed = [] |
| 308 |
for pkg in pkgs: |
| 309 |
if isinstance(pkg, dnf.package.Package): |
| 310 |
pkg_nevra = _package_to_envra(pkg) |
| 311 |
else: |
| 312 |
pkg_nevra = pkg |
| 313 |
|
| 314 |
if _is_package_installed(base, pkg_nevra): |
| 315 |
try: |
| 316 |
if isinstance(pkg, dnf.package.Package): |
| 317 |
base.package_upgrade(pkg) |
| 318 |
else: |
| 319 |
base.upgrade(pkg) |
| 320 |
except Exception as e: |
| 321 |
raise _DnfScriptError(f'Error occurred attempting update_only operation: {e}') |
| 322 |
else: |
| 323 |
not_installed.append(pkg) |
| 324 |
|
| 325 |
return not_installed |
| 326 |
|
| 327 |
|
| 328 |
def _install_remote_rpms_helper(base, filenames, update_only, allow_downgrade): |
| 329 |
"""Handle installation of remote RPM files.""" |
| 330 |
try: |
| 331 |
pkgs = base.add_remote_rpms(filenames) |
| 332 |
if update_only: |
| 333 |
_update_only_helper(base, pkgs) |
| 334 |
else: |
| 335 |
for pkg in pkgs: |
| 336 |
if not (_is_newer_version_installed(base, pkg) and not allow_downgrade): |
| 337 |
base.package_install(pkg, strict=base.conf.strict) |
| 338 |
except _DnfScriptError: |
| 339 |
raise |
| 340 |
except Exception as e: |
| 341 |
raise _DnfScriptError(f'Error occurred attempting remote rpm operation: {e}') |
| 342 |
|
| 343 |
|
| 344 |
def _is_module_installed(base, module_base, module_spec, with_modules): |
| 345 |
"""Check if a module is installed.""" |
| 346 |
if not with_modules: |
| 347 |
return False |
| 348 |
|
| 349 |
module_info = _get_modules(module_base, module_spec) |
| 350 |
enabled_streams = base._moduleContainer.getEnabledStream(module_info['nsv']['name']) |
| 351 |
|
| 352 |
if enabled_streams: |
| 353 |
if module_info['nsv']['stream']: |
| 354 |
if module_info['nsv']['stream'] in enabled_streams: |
| 355 |
return True |
| 356 |
else: |
| 357 |
return False |
| 358 |
else: |
| 359 |
return True |
| 360 |
|
| 361 |
return False |
| 362 |
|
| 363 |
|
| 364 |
def _mark_package_install(base, pkg_spec, upgrade, allow_downgrade): |
| 365 |
"""Mark a package for installation.""" |
| 366 |
msg = '' |
| 367 |
strict = base.conf.strict |
| 368 |
|
| 369 |
try: |
| 370 |
if dnf.util.is_glob_pattern(pkg_spec): |
| 371 |
if upgrade: |
| 372 |
try: |
| 373 |
base.upgrade(pkg_spec) |
| 374 |
except dnf.exceptions.PackagesNotInstalledError: |
| 375 |
pass |
| 376 |
|
| 377 |
try: |
| 378 |
base.install(pkg_spec, strict=strict) |
| 379 |
except dnf.exceptions.MarkingError as e: |
| 380 |
msg = f'No package {pkg_spec} available.' |
| 381 |
if strict: |
| 382 |
return {'failed': True, 'msg': msg, 'failure': f'{pkg_spec} {e}', 'rc': 1} |
| 383 |
except dnf.exceptions.DepsolveError as e: |
| 384 |
return {'failed': True, 'msg': f'Depsolve Error occurred for package {pkg_spec}.', 'failure': f'{pkg_spec} {e}', 'rc': 1} |
| 385 |
except dnf.exceptions.Error as e: |
| 386 |
return {'failed': True, 'msg': f'Unknown Error occurred for package {pkg_spec}.', 'failure': f'{pkg_spec} {e}', 'rc': 1} |
| 387 |
elif _is_newer_version_installed(base, pkg_spec): |
| 388 |
if allow_downgrade: |
| 389 |
try: |
| 390 |
base.install(pkg_spec, strict=strict) |
| 391 |
except dnf.exceptions.MarkingError as e: |
| 392 |
msg = f'No package {pkg_spec} available.' |
| 393 |
if strict: |
| 394 |
return {'failed': True, 'msg': msg, 'failure': f'{pkg_spec} {e}', 'rc': 1} |
| 395 |
elif _is_package_installed(base, pkg_spec): |
| 396 |
if upgrade: |
| 397 |
try: |
| 398 |
base.upgrade(pkg_spec) |
| 399 |
except dnf.exceptions.PackagesNotInstalledError: |
| 400 |
pass |
| 401 |
else: |
| 402 |
try: |
| 403 |
base.install(pkg_spec, strict=strict) |
| 404 |
except dnf.exceptions.MarkingError as e: |
| 405 |
msg = f'No package {pkg_spec} available.' |
| 406 |
if strict: |
| 407 |
return {'failed': True, 'msg': msg, 'failure': f'{pkg_spec} {e}', 'rc': 1} |
| 408 |
except dnf.exceptions.DepsolveError as e: |
| 409 |
return {'failed': True, 'msg': f'Depsolve Error occurred for package {pkg_spec}.', 'failure': f'{pkg_spec} {e}', 'rc': 1} |
| 410 |
except dnf.exceptions.Error as e: |
| 411 |
return {'failed': True, 'msg': f'Unknown Error occurred for package {pkg_spec}.', 'failure': f'{pkg_spec} {e}', 'rc': 1} |
| 412 |
except Exception as e: |
| 413 |
return {'failed': True, 'msg': f'Unknown Error occurred for package {pkg_spec}.', 'failure': f'{pkg_spec} {e}', 'rc': 1} |
| 414 |
|
| 415 |
return {'failed': False, 'msg': msg, 'failure': '', 'rc': 0} |
| 416 |
|
| 417 |
|
| 418 |
def _sanitize_install_error(spec, error): |
| 419 |
"""Sanitize DNF error messages for install operations.""" |
| 420 |
if 'no package matched' in str(error) or 'No match for argument:' in str(error): |
| 421 |
return f'No package {spec} available.' |
| 422 |
return error |
| 423 |
|
| 424 |
|
| 425 |
def _ensure_impl(base, module_base, params): |
| 426 |
"""Core implementation of ensure logic.""" |
| 427 |
response = {'msg': '', 'changed': False, 'results': [], 'rc': 0} |
| 428 |
|
| 429 |
failures = [] |
| 430 |
|
| 431 |
names = params.get('names', []) |
| 432 |
state = params.get('state') |
| 433 |
autoremove = params.get('autoremove', False) |
| 434 |
update_only = params.get('update_only', False) |
| 435 |
allow_downgrade = params.get('allow_downgrade', False) |
| 436 |
download_only = params.get('download_only', False) |
| 437 |
disable_gpg_check = params.get('disable_gpg_check', False) |
| 438 |
check_mode = params.get('check_mode', False) |
| 439 |
download_dir = params.get('download_dir') |
| 440 |
allowerasing = params.get('allowerasing', False) |
| 441 |
with_modules = dnf.base.WITH_MODULES and module_base is not None |
| 442 |
|
| 443 |
if not names and autoremove: |
| 444 |
names = [] |
| 445 |
state = 'absent' |
| 446 |
|
| 447 |
if names == ['*'] and state == 'latest': |
| 448 |
try: |
| 449 |
base.upgrade_all() |
| 450 |
except dnf.exceptions.DepsolveError as e: |
| 451 |
raise _DnfScriptError(msg=f'Depsolve Error occurred attempting to upgrade all packages: {e}', rc=1) |
| 452 |
else: |
| 453 |
pkg_specs, group_specs, module_specs, filenames = _parse_spec_group_file(base, module_base, names, update_only, with_modules) |
| 454 |
|
| 455 |
pkg_specs = [p.strip() for p in pkg_specs] |
| 456 |
filenames = [f.strip() for f in filenames] |
| 457 |
groups = [] |
| 458 |
environments = [] |
| 459 |
|
| 460 |
for group_spec in (g.strip() for g in group_specs): |
| 461 |
group = base.comps.group_by_pattern(group_spec) |
| 462 |
if group: |
| 463 |
groups.append(group.id) |
| 464 |
else: |
| 465 |
environment = base.comps.environment_by_pattern(group_spec) |
| 466 |
if environment: |
| 467 |
environments.append(environment.id) |
| 468 |
else: |
| 469 |
raise _DnfScriptError(f'No group {group_spec} available.') |
| 470 |
|
| 471 |
if state in ['installed', 'present']: |
| 472 |
if filenames: |
| 473 |
_install_remote_rpms_helper(base, filenames, update_only, allow_downgrade) |
| 474 |
for filename in filenames: |
| 475 |
response['results'].append(f'Installed {filename}') |
| 476 |
|
| 477 |
if module_specs and with_modules: |
| 478 |
for module in module_specs: |
| 479 |
if not _is_module_installed(base, module_base, module, with_modules): |
| 480 |
response['results'].append(f'Module {module} installed.') |
| 481 |
try: |
| 482 |
module_base.install([module]) |
| 483 |
module_base.enable([module]) |
| 484 |
except dnf.exceptions.MarkingErrors as e: |
| 485 |
failures.append(f'{module} {e}') |
| 486 |
|
| 487 |
for group in groups: |
| 488 |
try: |
| 489 |
count = base.group_install(group, dnf.const.GROUP_PACKAGE_TYPES) |
| 490 |
if count == 0: |
| 491 |
response['results'].append(f'Group {group} already installed.') |
| 492 |
else: |
| 493 |
response['results'].append(f'Group {group} installed.') |
| 494 |
except dnf.exceptions.DepsolveError: |
| 495 |
raise _DnfScriptError(msg=f'Depsolve Error occurred attempting to install group: {group}', failures=failures, results=response['results']) |
| 496 |
except dnf.exceptions.Error as e: |
| 497 |
failures.append(f'{group} {e}') |
| 498 |
|
| 499 |
for environment in environments: |
| 500 |
try: |
| 501 |
base.environment_install(environment, dnf.const.GROUP_PACKAGE_TYPES) |
| 502 |
except dnf.exceptions.DepsolveError: |
| 503 |
raise _DnfScriptError( |
| 504 |
msg=f'Depsolve Error occurred attempting to install environment: {environment}', failures=failures, results=response['results'] |
| 505 |
) |
| 506 |
except dnf.exceptions.Error as e: |
| 507 |
failures.append(f'{environment} {e}') |
| 508 |
|
| 509 |
if module_specs and not with_modules: |
| 510 |
raise _DnfScriptError(f'No group {module_specs[0]} available.') |
| 511 |
|
| 512 |
if update_only: |
| 513 |
not_installed = _update_only_helper(base, pkg_specs) |
| 514 |
for spec in not_installed: |
| 515 |
response['results'].append(f'Packages providing {spec} not installed due to update_only specified') |
| 516 |
else: |
| 517 |
for pkg_spec in pkg_specs: |
| 518 |
install_result = _mark_package_install(base, pkg_spec, False, allow_downgrade) |
| 519 |
if install_result['failed']: |
| 520 |
failures.append(_sanitize_install_error(pkg_spec, install_result['failure'])) |
| 521 |
else: |
| 522 |
if install_result['msg']: |
| 523 |
response['results'].append(install_result['msg']) |
| 524 |
|
| 525 |
elif state == 'latest': |
| 526 |
if filenames: |
| 527 |
_install_remote_rpms_helper(base, filenames, update_only, allow_downgrade) |
| 528 |
for filename in filenames: |
| 529 |
response['results'].append(f'Installed {filename}') |
| 530 |
|
| 531 |
if module_specs and with_modules: |
| 532 |
for module in module_specs: |
| 533 |
try: |
| 534 |
if _is_module_installed(base, module_base, module, with_modules): |
| 535 |
module_base.upgrade([module]) |
| 536 |
response['results'].append(f'Module {module} upgraded.') |
| 537 |
else: |
| 538 |
module_base.install([module]) |
| 539 |
module_base.enable([module]) |
| 540 |
response['results'].append("Module {0} installed.".format(module)) |
| 541 |
except dnf.exceptions.MarkingErrors as e: |
| 542 |
failures.append(f'{module} {e}') |
| 543 |
|
| 544 |
for group in groups: |
| 545 |
try: |
| 546 |
base.group_upgrade(group) |
| 547 |
response['results'].append(f'Group {group} upgraded.') |
| 548 |
except dnf.exceptions.CompsError: |
| 549 |
if not update_only: |
| 550 |
try: |
| 551 |
count = base.group_install(group, dnf.const.GROUP_PACKAGE_TYPES) |
| 552 |
if count == 0: |
| 553 |
response['results'].append(f'Group {group} already installed.') |
| 554 |
else: |
| 555 |
response['results'].append(f'Group {group} installed.') |
| 556 |
except dnf.exceptions.Error as e2: |
| 557 |
failures.append(f'{group} {e2}') |
| 558 |
except dnf.exceptions.Error as e: |
| 559 |
failures.append(f'{group} {e}') |
| 560 |
|
| 561 |
for environment in environments: |
| 562 |
try: |
| 563 |
base.environment_upgrade(environment) |
| 564 |
except dnf.exceptions.CompsError: |
| 565 |
try: |
| 566 |
base.environment_install(environment, dnf.const.GROUP_PACKAGE_TYPES) |
| 567 |
except dnf.exceptions.DepsolveError as e2: |
| 568 |
failures.append(f'{environment} {e2}') |
| 569 |
except dnf.exceptions.Error as e2: |
| 570 |
failures.append(f'{environment} {e2}') |
| 571 |
except dnf.exceptions.DepsolveError as e: |
| 572 |
failures.append(f'{environment} {e}') |
| 573 |
except dnf.exceptions.Error as e: |
| 574 |
failures.append(f'{environment} {e}') |
| 575 |
|
| 576 |
if update_only: |
| 577 |
not_installed = _update_only_helper(base, pkg_specs) |
| 578 |
for spec in not_installed: |
| 579 |
response['results'].append(f'Packages providing {spec} not installed due to update_only specified') |
| 580 |
else: |
| 581 |
for pkg_spec in pkg_specs: |
| 582 |
install_result = _mark_package_install(base, pkg_spec, True, allow_downgrade) |
| 583 |
if install_result['failed']: |
| 584 |
failures.append(_sanitize_install_error(pkg_spec, install_result['failure'])) |
| 585 |
else: |
| 586 |
if install_result['msg']: |
| 587 |
response['results'].append(install_result['msg']) |
| 588 |
|
| 589 |
else: |
| 590 |
if filenames: |
| 591 |
raise _DnfScriptError('Cannot remove paths -- please specify package name.') |
| 592 |
|
| 593 |
if module_specs and with_modules: |
| 594 |
for module in module_specs: |
| 595 |
if _is_module_installed(base, module_base, module, with_modules): |
| 596 |
response['results'].append(f'Module {module} removed.') |
| 597 |
try: |
| 598 |
module_base.remove([module]) |
| 599 |
except dnf.exceptions.MarkingErrors as e: |
| 600 |
failures.append(f'{module} {e}') |
| 601 |
try: |
| 602 |
module_base.disable([module]) |
| 603 |
except dnf.exceptions.MarkingErrors as e: |
| 604 |
failures.append(f'{module} {e}') |
| 605 |
try: |
| 606 |
module_base.reset([module]) |
| 607 |
except dnf.exceptions.MarkingErrors as e: |
| 608 |
failures.append(f'{module} {e}') |
| 609 |
|
| 610 |
for group in groups: |
| 611 |
try: |
| 612 |
base.group_remove(group) |
| 613 |
except dnf.exceptions.CompsError as e: |
| 614 |
response['results'].append(f'{group} {e}') |
| 615 |
|
| 616 |
for environment in environments: |
| 617 |
try: |
| 618 |
base.environment_remove(environment) |
| 619 |
except dnf.exceptions.CompsError as e: |
| 620 |
response['results'].append(f'{environment} {e}') |
| 621 |
|
| 622 |
for pkg_spec in pkg_specs: |
| 623 |
try: |
| 624 |
base.remove(pkg_spec) |
| 625 |
except dnf.exceptions.MarkingError as e: |
| 626 |
response['results'].append(f'{e.value}: {pkg_spec}') |
| 627 |
|
| 628 |
allowerasing = True |
| 629 |
|
| 630 |
if autoremove: |
| 631 |
base.autoremove() |
| 632 |
|
| 633 |
try: |
| 634 |
has_changes = base.resolve(allow_erasing=allowerasing) |
| 635 |
except dnf.exceptions.DepsolveError as e: |
| 636 |
raise _DnfScriptError(msg=f'Depsolve Error occurred: {e}', failures=failures, results=response['results']) |
| 637 |
except dnf.exceptions.Error as e: |
| 638 |
raise _DnfScriptError(msg=f'Unknown Error occurred: {e}', failures=failures, results=response['results']) |
| 639 |
|
| 640 |
if not has_changes: |
| 641 |
if failures: |
| 642 |
raise _DnfScriptError(msg='Failed to install some of the specified packages', failures=failures, results=response['results']) |
| 643 |
response['msg'] = 'Nothing to do' |
| 644 |
return response |
| 645 |
else: |
| 646 |
response['changed'] = True |
| 647 |
|
| 648 |
install_action = 'Downloaded' if download_only else 'Installed' |
| 649 |
for package in base.transaction.install_set: |
| 650 |
response['results'].append(f'{install_action}: {package}') |
| 651 |
for package in base.transaction.remove_set: |
| 652 |
response['results'].append(f'Removed: {package}') |
| 653 |
|
| 654 |
if failures: |
| 655 |
raise _DnfScriptError(msg='Failed to install some of the specified packages', failures=failures, results=response['results']) |
| 656 |
|
| 657 |
if check_mode: |
| 658 |
response['msg'] = 'Check mode: No changes made, but would have if not in check mode' |
| 659 |
return response |
| 660 |
|
| 661 |
if download_only and download_dir and base.conf.destdir: |
| 662 |
dnf.util.ensure_dir(base.conf.destdir) |
| 663 |
base.repos.all().pkgdir = base.conf.destdir |
| 664 |
|
| 665 |
try: |
| 666 |
base.download_packages(base.transaction.install_set) |
| 667 |
except dnf.exceptions.DownloadError as e: |
| 668 |
raise _DnfScriptError(msg=f'Failed to download packages: {e}', failures=failures, results=response['results']) |
| 669 |
|
| 670 |
if not disable_gpg_check: |
| 671 |
for package in base.transaction.install_set: |
| 672 |
gpgres, gpgerr = base._sig_check_pkg(package) |
| 673 |
if gpgres != 0: # Not validated successfully |
| 674 |
if gpgres == 1: # Need to install cert |
| 675 |
try: |
| 676 |
base._get_key_for_package(package) |
| 677 |
except dnf.exceptions.Error as e: |
| 678 |
raise _DnfScriptError(f'Failed to validate GPG signature for {package}: {e}') |
| 679 |
else: # Fatal error |
| 680 |
raise _DnfScriptError(f'Failed to validate GPG signature for {package}: {gpgerr}') |
| 681 |
|
| 682 |
if download_only: |
| 683 |
return response |
| 684 |
else: |
| 685 |
tid = base.do_transaction() |
| 686 |
if tid is not None: |
| 687 |
transaction = base.history.old([tid])[0] |
| 688 |
if transaction.return_code: |
| 689 |
failures.extend(transaction.output()) |
| 690 |
|
| 691 |
if failures: |
| 692 |
raise _DnfScriptError(msg='Failed to install some of the specified packages', failures=failures, results=response['results']) |
| 693 |
|
| 694 |
return response |
| 695 |
|
| 696 |
|
| 697 |
def _setup_base(config): |
| 698 |
"""Internal helper to set up and configure a dnf.Base object.""" |
| 699 |
base = dnf.Base() |
| 700 |
|
| 701 |
warnings = _configure_base(base, config) |
| 702 |
|
| 703 |
_init_plugins(base, config.get('disable_plugin', []), config.get('enable_plugin', [])) |
| 704 |
|
| 705 |
base.read_all_repos() |
| 706 |
_configure_repos(base, config.get('disablerepo', []), config.get('enablerepo', []), config.get('disable_gpg_check', False)) |
| 707 |
|
| 708 |
base.configure_plugins() |
| 709 |
|
| 710 |
try: |
| 711 |
if config.get('update_cache'): |
| 712 |
base.update_cache() |
| 713 |
|
| 714 |
base.fill_sack(load_system_repo='auto') |
| 715 |
except Exception: |
| 716 |
base.close() |
| 717 |
raise |
| 718 |
|
| 719 |
if config.get('bugfix') or config.get('security'): |
| 720 |
_add_security_filters(base, config.get('bugfix', False), config.get('security', False)) |
| 721 |
|
| 722 |
module_base = None |
| 723 |
if dnf.base.WITH_MODULES: |
| 724 |
module_base = dnf.module.module_base.ModuleBase(base) |
| 725 |
|
| 726 |
return base, module_base, warnings |
| 727 |
|
| 728 |
|
| 729 |
def list_items(config, command): |
| 730 |
"""List packages based on command.""" |
| 731 |
base = None |
| 732 |
try: |
| 733 |
base, module_base, warnings = _setup_base(config) |
| 734 |
|
| 735 |
if command == 'updates': |
| 736 |
command = 'upgrades' |
| 737 |
|
| 738 |
if command == 'installed': |
| 739 |
results = list(base.sack.query().installed()) |
| 740 |
elif command == 'upgrades': |
| 741 |
results = list(base.sack.query().upgrades()) |
| 742 |
elif command == 'available': |
| 743 |
results = list(base.sack.query().available()) |
| 744 |
elif command in ['repos', 'repositories']: |
| 745 |
results = [{'repoid': repo.id, 'state': 'enabled'} for repo in base.repos.iter_enabled()] |
| 746 |
else: |
| 747 |
results = list(dnf.subject.Subject(command).get_best_query(base.sack)) |
| 748 |
|
| 749 |
return {'results': results, 'warnings': warnings} |
| 750 |
except Exception as e: |
| 751 |
return {'results': [], 'warnings': [], 'failed': True, 'msg': f'{e}'} |
| 752 |
finally: |
| 753 |
if base: |
| 754 |
base.close() |
| 755 |
|
| 756 |
|
| 757 |
def update_cache_only(config): |
| 758 |
"""Update the cache only (no other operations).""" |
| 759 |
base = None |
| 760 |
try: |
| 761 |
base, module_base, warnings = _setup_base(config) |
| 762 |
return {'changed': False, 'warnings': warnings} |
| 763 |
except Exception as e: |
| 764 |
return {'changed': False, 'warnings': [], 'failed': True, 'msg': f'{e}'} |
| 765 |
finally: |
| 766 |
if base: |
| 767 |
base.close() |
| 768 |
|
| 769 |
|
| 770 |
def ensure(config, params): |
| 771 |
"""Main operation for installing, removing, or upgrading packages.""" |
| 772 |
base = None |
| 773 |
try: |
| 774 |
base, module_base, warnings = _setup_base(config) |
| 775 |
|
| 776 |
result = _ensure_impl(base, module_base, params) |
| 777 |
|
| 778 |
result['warnings'] = warnings |
| 779 |
result['failures'] = [] |
| 780 |
|
| 781 |
return result |
| 782 |
|
| 783 |
except _DnfScriptError as e: |
| 784 |
return e.to_dict() |
| 785 |
except Exception as e: |
| 786 |
return {'changed': False, 'results': [], 'warnings': [], 'failed': True, 'failures': [], 'rc': 1, 'msg': f'{e}'} |
| 787 |
finally: |
| 788 |
if base: |
| 789 |
base.close() |
| 790 |
|
| 791 |
|
| 792 |
def main(): |
| 793 |
"""Main entry point for standalone script execution.""" |
| 794 |
|
| 795 |
if not HAS_DNF: |
| 796 |
_exit_json({'failed': True, 'msg': 'python3-dnf not found'}) |
| 797 |
|
| 798 |
try: |
| 799 |
request = json.load(sys.stdin) |
| 800 |
except Exception as e: |
| 801 |
_exit_json({'failed': True, 'msg': f'Failed to read JSON input: {e}'}) |
| 802 |
|
| 803 |
command = request.get('command') |
| 804 |
if not command: |
| 805 |
_exit_json({'failed': True, 'msg': 'No command specified'}) |
| 806 |
|
| 807 |
config = request.get('config', {}) |
| 808 |
params = request.get('params', {}) |
| 809 |
|
| 810 |
if command == 'list': |
| 811 |
list_command = params.get('list_command') |
| 812 |
if not list_command: |
| 813 |
_exit_json({'failed': True, 'msg': 'No list_command specified for list operation'}) |
| 814 |
result = list_items(config, list_command) |
| 815 |
|
| 816 |
elif command == 'ensure': |
| 817 |
result = ensure(config, params) |
| 818 |
|
| 819 |
elif command == 'update-cache': |
| 820 |
result = update_cache_only(config) |
| 821 |
|
| 822 |
else: |
| 823 |
_exit_json({'failed': True, 'msg': f'Unknown command: {command}'}) |
| 824 |
|
| 825 |
_exit_json(result) |
| 826 |
|
| 827 |
|
| 828 |
if __name__ == '__main__': |
| 829 |
main() |