-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
yumpkg.py
3550 lines (2856 loc) · 116 KB
/
yumpkg.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Support for YUM/DNF
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. note::
DNF is fully supported as of version 2015.5.10 and 2015.8.4 (partial
support for DNF was initially added in 2015.8.0), and DNF is used
automatically in place of YUM in Fedora 22 and newer.
.. versionadded:: 3003
Support for ``tdnf`` on Photon OS.
.. versionadded:: 3007.0
Support for ``dnf5``` on Fedora 39
"""
import configparser
import contextlib
import datetime
import fnmatch
import itertools
import logging
import os
import re
import string
import salt.utils.args
import salt.utils.data
import salt.utils.environment
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.lazy
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.rpm
import salt.utils.systemd
import salt.utils.versions
from salt.exceptions import CommandExecutionError, MinionError, SaltInvocationError
from salt.utils.versions import LooseVersion
log = logging.getLogger(__name__)
__HOLD_PATTERN = r"[\w+]+(?:[.-][^-]+)*"
PKG_ARCH_SEPARATOR = "."
# Define the module's virtual name
__virtualname__ = "pkg"
def __virtual__():
"""
Confine this module to yum based systems
"""
if __opts__.get("yum_provider") == "yumpkg_api":
return (False, "Module yumpkg: yumpkg_api provider not available")
try:
os_grain = __grains__["os"].lower()
os_family = __grains__["os_family"].lower()
except Exception: # pylint: disable=broad-except
return (False, "Module yumpkg: no yum based system detected")
enabled = (
"amazon",
"xcp",
"xenserver",
"virtuozzolinux",
"virtuozzo",
"issabel pbx",
"openeuler",
)
if os_family == "redhat" or os_grain in enabled:
if _yum() is None:
return (False, "DNF nor YUM found")
return __virtualname__
return (False, "Module yumpkg: no yum based system detected")
def _strip_headers(output, *args):
if not args:
args_lc = (
"installed packages",
"available packages",
"available upgrades",
"updated packages",
"upgraded packages",
)
else:
args_lc = [x.lower() for x in args]
ret = ""
for line in salt.utils.itertools.split(output, "\n"):
if line.lower() not in args_lc:
ret += line + "\n"
return ret
def _get_copr_repo(copr):
copr = copr.split(":", 1)[1]
copr = copr.split("/", 1)
return f"copr:copr.fedorainfracloud.org:{copr[0]}:{copr[1]}"
def _get_hold(line, pattern=__HOLD_PATTERN, full=True):
"""
Resolve a package name from a line containing the hold expression. If the
regex is not matched, None is returned.
yum ==> 2:vim-enhanced-7.4.629-5.el6.*
dnf ==> vim-enhanced-2:7.4.827-1.fc22.*
"""
if full:
if _yum() in ("dnf", "dnf5"):
lock_re = rf"({pattern}-\S+)"
else:
lock_re = rf"(\d+:{pattern}-\S+)"
else:
if _yum() in ("dnf", "dnf5"):
lock_re = rf"({pattern}-\S+)"
else:
lock_re = rf"\d+:({pattern}-\S+)"
match = re.search(lock_re, line)
if match:
if not full:
woarch = match.group(1).rsplit(".", 1)[0]
worel = woarch.rsplit("-", 1)[0]
return worel.rsplit("-", 1)[0]
else:
return match.group(1)
return None
def _yum():
"""
Determine package manager name (yum or dnf[5]),
depending on the executable existence in $PATH.
"""
# Do import due to function clonning to kernelpkg_linux_yum mod
import os
def _check(file):
return (
os.path.exists(file)
and os.access(file, os.F_OK | os.X_OK)
and not os.path.isdir(file)
)
# allow calling function outside execution module
try:
context = __context__
except NameError:
context = {}
contextkey = "yum_bin"
if contextkey not in context:
for dir in os.environ.get("PATH", os.defpath).split(os.pathsep):
if _check(os.path.join(dir, "dnf5")):
context[contextkey] = "dnf5"
break
elif _check(os.path.join(dir, "dnf")):
context[contextkey] = "dnf"
break
elif _check(os.path.join(dir, "tdnf")):
context[contextkey] = "tdnf"
break
elif _check(os.path.join(dir, "yum")):
context[contextkey] = "yum"
break
return context.get(contextkey)
def _call_yum(args, **kwargs):
"""
Call yum/dnf.
"""
params = {
"output_loglevel": "trace",
"python_shell": False,
"env": salt.utils.environment.get_module_environment(globals()),
}
params.update(kwargs)
cmd = []
if salt.utils.systemd.has_scope(__context__) and __salt__["config.get"](
"systemd.scope", True
):
cmd.extend(["systemd-run", "--scope"])
cmd.append(_yum())
cmd.extend(args)
return __salt__["cmd.run_all"](cmd, **params)
def _yum_pkginfo(output):
"""
Parse yum/dnf output (which could contain irregular line breaks if package
names are long) retrieving the name, version, etc., and return a list of
pkginfo namedtuples.
"""
cur = {}
keys = itertools.cycle(("name", "version", "repoid"))
values = salt.utils.itertools.split(_strip_headers(output))
osarch = __grains__["osarch"]
for key, value in zip(keys, values):
if key == "name":
try:
cur["name"], cur["arch"] = value.rsplit(".", 1)
except ValueError:
cur["name"] = value
cur["arch"] = osarch
cur["name"] = salt.utils.pkg.rpm.resolve_name(
cur["name"], cur["arch"], osarch
)
else:
if key == "version":
# Suppport packages with no 'Release' parameter
value = value.rstrip("-")
elif key == "repoid":
# Installed packages show a '@' at the beginning
value = value.lstrip("@")
cur[key] = value
if key == "repoid":
# We're done with this package, create the pkginfo namedtuple
pkginfo = salt.utils.pkg.rpm.pkginfo(**cur)
# Clear the dict for the next package
cur = {}
# Yield the namedtuple
if pkginfo is not None:
yield pkginfo
def _versionlock_pkg(grains=None):
"""
Determine versionlock plugin package name
"""
if grains is None:
grains = __grains__
if _yum() in ("dnf", "dnf5"):
if grains["os"].lower() == "fedora":
return (
"python3-dnf-plugin-versionlock"
if int(grains.get("osrelease")) >= 26
else "python3-dnf-plugins-extras-versionlock"
)
if int(grains.get("osmajorrelease")) >= 8:
return "python3-dnf-plugin-versionlock"
return "python2-dnf-plugin-versionlock"
elif _yum() == "tdnf":
raise SaltInvocationError("Cannot proceed, no versionlock for tdnf")
else:
return "yum-plugin-versionlock"
def _check_versionlock():
"""
Ensure that the appropriate versionlock plugin is present
"""
vl_plugin = _versionlock_pkg()
if vl_plugin not in list_pkgs():
raise SaltInvocationError(f"Cannot proceed, {vl_plugin} is not installed.")
def _get_options(**kwargs):
"""
Returns a list of options to be used in the yum/dnf[5] command, based on the
kwargs passed.
"""
# Get repo options from the kwargs
# dnf5 aliases dnf options, so no need to change
fromrepo = kwargs.pop("fromrepo", "")
repo = kwargs.pop("repo", "")
disablerepo = kwargs.pop("disablerepo", "")
enablerepo = kwargs.pop("enablerepo", "")
disableexcludes = kwargs.pop("disableexcludes", "")
branch = kwargs.pop("branch", "")
setopt = kwargs.pop("setopt", None)
if setopt is None:
setopt = []
else:
setopt = salt.utils.args.split_input(setopt)
get_extra_options = kwargs.pop("get_extra_options", False)
# Support old 'repo' argument
if repo and not fromrepo:
fromrepo = repo
ret = []
if fromrepo:
log.info("Restricting to repo '%s'", fromrepo)
ret.extend(["--disablerepo=*", f"--enablerepo={fromrepo}"])
else:
if disablerepo:
targets = (
[disablerepo] if not isinstance(disablerepo, list) else disablerepo
)
log.info("Disabling repo(s): %s", ", ".join(targets))
ret.extend([f"--disablerepo={x}" for x in targets])
if enablerepo:
targets = [enablerepo] if not isinstance(enablerepo, list) else enablerepo
log.info("Enabling repo(s): %s", ", ".join(targets))
ret.extend([f"--enablerepo={x}" for x in targets])
if disableexcludes:
log.info("Disabling excludes for '%s'", disableexcludes)
ret.append(f"--disableexcludes={disableexcludes}")
if branch:
log.info("Adding branch '%s'", branch)
ret.append(f"--branch={branch}")
for item in setopt:
ret.extend(["--setopt", str(item)])
if get_extra_options:
# sorting here to make order uniform, makes unit testing more reliable
for key in sorted(kwargs):
if key.startswith("__"):
continue
value = kwargs[key]
if isinstance(value, str):
log.info("Found extra option --%s=%s", key, value)
ret.append(f"--{key}={value}")
elif value is True:
log.info("Found extra option --%s", key)
ret.append(f"--{key}")
if ret:
log.info("Adding extra options: %s", ret)
return ret
def _get_yum_config(strict_parser=True):
"""
Returns a dict representing the yum config options and values.
We try to pull all of the yum config options into a standard dict object.
This is currently only used to get the reposdir settings, but could be used
for other things if needed.
We try to read the yum.conf directly ourselves with a minimal set of
"defaults".
"""
# in case of any non-fatal failures, these defaults will be used
conf = {
"reposdir": ["/etc/yum/repos.d", "/etc/yum.repos.d"],
}
# fall back to parsing the config ourselves
# Look for the config the same order yum does
fn = None
paths = (
"/etc/yum/yum.conf",
"/etc/yum.conf",
"/etc/dnf/dnf.conf",
"/etc/tdnf/tdnf.conf",
)
for path in paths:
if os.path.exists(path):
fn = path
break
if not fn:
raise CommandExecutionError(f"No suitable yum config file found in: {paths}")
cp = configparser.ConfigParser(strict=strict_parser)
try:
cp.read(fn)
except OSError as exc:
raise CommandExecutionError(f"Unable to read from {fn}: {exc}")
if cp.has_section("main"):
for opt in cp.options("main"):
if opt in ("reposdir", "commands", "excludes"):
# these options are expected to be lists
conf[opt] = [x.strip() for x in cp.get("main", opt).split(",")]
else:
conf[opt] = cp.get("main", opt)
else:
log.warning("Could not find [main] section in %s, using internal defaults", fn)
return conf
def _get_yum_config_value(name, strict_config=True):
"""
Look for a specific config variable and return its value
"""
conf = _get_yum_config(strict_config)
if name in conf:
return conf.get(name)
return None
def _normalize_basedir(basedir=None, strict_config=True):
"""
Takes a basedir argument as a string or a list. If the string or list is
empty, then look up the default from the 'reposdir' option in the yum
config.
Returns a list of directories.
"""
# if we are passed a string (for backward compatibility), convert to a list
if isinstance(basedir, str):
basedir = [x.strip() for x in basedir.split(",")]
if basedir is None:
basedir = []
# nothing specified, so use the reposdir option as the default
if not basedir:
basedir = _get_yum_config_value("reposdir", strict_config)
if not isinstance(basedir, list) or not basedir:
raise SaltInvocationError("Could not determine any repo directories")
return basedir
def normalize_name(name):
"""
Strips the architecture from the specified package name, if necessary.
Circumstances where this would be done include:
* If the arch is 32 bit and the package name ends in a 32-bit arch.
* If the arch matches the OS arch, or is ``noarch``.
CLI Example:
.. code-block:: bash
salt '*' pkg.normalize_name zsh.x86_64
"""
try:
arch = name.rsplit(PKG_ARCH_SEPARATOR, 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES + ("noarch",):
return name
except ValueError:
return name
if arch in (__grains__["osarch"], "noarch") or salt.utils.pkg.rpm.check_32(
arch, osarch=__grains__["osarch"]
):
return name[: -(len(arch) + 1)]
return name
def parse_arch(name):
"""
Parse name and architecture from the specified package name.
CLI Example:
.. code-block:: bash
salt '*' pkg.parse_arch zsh.x86_64
"""
_name, _arch = None, None
try:
_name, _arch = name.rsplit(PKG_ARCH_SEPARATOR, 1)
except ValueError:
pass
if _arch not in salt.utils.pkg.rpm.ARCHES + ("noarch",):
_name = name
_arch = None
return {"name": _name, "arch": _arch}
def latest_version(*names, **kwargs):
"""
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument,
and the ``disableexcludes`` option is also supported.
.. versionadded:: 2014.7.0
Support for the ``disableexcludes`` option
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=epel-testing
salt '*' pkg.latest_version <package name> disableexcludes=main
salt '*' pkg.latest_version <package1> <package2> <package3> ...
"""
refresh = salt.utils.data.is_true(kwargs.pop("refresh", True))
if not names:
return ""
options = _get_options(**kwargs)
# Refresh before looking for the latest version available
if refresh:
refresh_db(**kwargs)
cur_pkgs = list_pkgs(versions_as_list=True)
# Get available versions for specified package(s)
cmd = ["--quiet"]
cmd.extend(options)
cmd.extend(["list", "available"])
cmd.extend(names)
out = _call_yum(cmd, ignore_retcode=True)
if out["retcode"] != 0:
if out["stderr"]:
# Check first if this is just a matter of the packages being
# up-to-date.
if not all([x in cur_pkgs for x in names]):
log.error(
"Problem encountered getting latest version for the "
"following package(s): %s. Stderr follows: \n%s",
", ".join(names),
out["stderr"],
)
updates = []
else:
# Sort by version number (highest to lowest) for loop below
updates = sorted(
_yum_pkginfo(out["stdout"]),
key=lambda pkginfo: LooseVersion(pkginfo.version),
reverse=True,
)
def _check_cur(pkg):
if pkg.name in cur_pkgs:
for installed_version in cur_pkgs[pkg.name]:
# If any installed version is greater than (or equal to) the
# one found by yum/dnf list available, then it is not an
# upgrade.
if salt.utils.versions.compare(
ver1=installed_version,
oper=">=",
ver2=pkg.version,
cmp_func=version_cmp,
):
return False
# pkg.version is greater than all installed versions
return True
else:
# Package is not installed
return True
ret = {}
for name in names:
# Derive desired pkg arch (for arch-specific packages) based on the
# package name(s) passed to the function. On a 64-bit OS, "pkgame"
# would be assumed to match the osarch, while "pkgname.i686" would
# have an arch of "i686". This desired arch is then compared against
# the updates derived from _yum_pkginfo() above, so that we can
# distinguish an update for a 32-bit version of a package from its
# 64-bit counterpart.
try:
arch = name.rsplit(".", 1)[-1]
if arch not in salt.utils.pkg.rpm.ARCHES:
arch = __grains__["osarch"]
except ValueError:
arch = __grains__["osarch"]
# This loop will iterate over the updates derived by _yum_pkginfo()
# above, which have been sorted descendingly by version number,
# ensuring that the latest available version for the named package is
# examined first. The call to _check_cur() will ensure that a package
# seen by yum as "available" will only be detected as an upgrade if it
# has a version higher than all currently-installed versions of the
# package.
for pkg in (x for x in updates if x.name == name):
# This if/or statement makes sure that we account for noarch
# packages as well as arch-specific packages.
if (
pkg.arch == "noarch"
or pkg.arch == arch
or salt.utils.pkg.rpm.check_32(pkg.arch)
):
if _check_cur(pkg):
ret[name] = pkg.version
# no need to check another match, if there was one
break
else:
ret[name] = ""
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(
latest_version, "available_version"
)
def upgrade_available(name, **kwargs):
"""
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
"""
return latest_version(name, **kwargs) != ""
def version(*names, **kwargs):
"""
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
"""
return __salt__["pkg_resource.version"](*names, **kwargs)
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs):
"""
.. versionadded:: 2015.5.4
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2015.8.10,2016.3.2
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2-001' '0.2.0.1-002'
"""
return __salt__["lowpkg.version_cmp"](pkg1, pkg2, ignore_epoch=ignore_epoch)
def _list_pkgs_from_context(versions_as_list, contextkey, attr):
"""
Use pkg list from __context__
"""
return __salt__["pkg_resource.format_pkg_list"](
__context__[contextkey], versions_as_list, attr
)
def list_pkgs(versions_as_list=False, **kwargs):
"""
List the packages currently installed as a dict. By default, the dict
contains versions as a comma separated string::
{'<package_name>': '<version>[,<version>...]'}
versions_as_list:
If set to true, the versions are provided as a list
{'<package_name>': ['<version>', '<version>']}
attr:
If a list of package attributes is specified, returned value will
contain them in addition to version, eg.::
{'<package_name>': [{'version' : 'version', 'arch' : 'arch'}]}
Valid attributes are: ``epoch``, ``version``, ``release``, ``arch``,
``install_date``, ``install_date_time_t``.
If ``all`` is specified, all valid attributes will be returned.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs attr=version,arch
salt '*' pkg.list_pkgs attr='["version", "arch"]'
"""
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any(
[salt.utils.data.is_true(kwargs.get(x)) for x in ("removed", "purge_desired")]
):
return {}
attr = kwargs.get("attr")
if attr is not None and attr != "all":
attr = salt.utils.args.split_input(attr)
contextkey = "pkg.list_pkgs"
if contextkey in __context__ and kwargs.get("use_context", True):
return _list_pkgs_from_context(versions_as_list, contextkey, attr)
ret = {}
cmd = [
"rpm",
"-qa",
"--nodigest",
"--nosignature",
"--queryformat",
salt.utils.pkg.rpm.QUERYFORMAT.replace("%{REPOID}", "(none)") + "\n",
]
output = __salt__["cmd.run"](cmd, python_shell=False, output_loglevel="trace")
for line in output.splitlines():
pkginfo = salt.utils.pkg.rpm.parse_pkginfo(line, osarch=__grains__["osarch"])
if pkginfo is not None:
# see rpm version string rules available at https://goo.gl/UGKPNd
pkgver = pkginfo.version
epoch = None
release = None
if ":" in pkgver:
epoch, pkgver = pkgver.split(":", 1)
if "-" in pkgver:
pkgver, release = pkgver.split("-", 1)
all_attr = {
"epoch": epoch,
"version": pkgver,
"release": release,
"arch": pkginfo.arch,
"install_date": pkginfo.install_date,
"install_date_time_t": pkginfo.install_date_time_t,
}
__salt__["pkg_resource.add_pkg"](ret, pkginfo.name, all_attr)
for pkgname in ret:
ret[pkgname] = sorted(ret[pkgname], key=lambda d: d["version"])
__context__[contextkey] = ret
return __salt__["pkg_resource.format_pkg_list"](
__context__[contextkey], versions_as_list, attr
)
def list_repo_pkgs(*args, **kwargs):
"""
.. versionadded:: 2014.1.0
.. versionchanged:: 2014.7.0
All available versions of each package are now returned. This required
a slight modification to the structure of the return dict. The return
data shown below reflects the updated return dict structure. Note that
packages which are version-locked using :py:mod:`pkg.hold
<salt.modules.yumpkg.hold>` will only show the currently-installed
version, as locking a package will make other versions appear
unavailable to yum/dnf.
.. versionchanged:: 2017.7.0
By default, the versions for each package are no longer organized by
repository. To get results organized by repository, use
``byrepo=True``.
Returns all available packages. Optionally, package names (and name globs)
can be passed and the results will be filtered to packages matching those
names. This is recommended as it speeds up the function considerably.
.. warning::
Running this function on RHEL/CentOS 6 and earlier will be more
resource-intensive, as the version of yum that ships with older
RHEL/CentOS has no yum subcommand for listing packages from a
repository. Thus, a ``yum list installed`` and ``yum list available``
are run, which generates a lot of output, which must then be analyzed
to determine which package information to include in the return data.
This function can be helpful in discovering the version or repo to specify
in a :mod:`pkg.installed <salt.states.pkg.installed>` state.
The return data will be a dictionary mapping package names to a list of
version numbers, ordered from newest to oldest. If ``byrepo`` is set to
``True``, then the return dictionary will contain repository names at the
top level, and each repository will map packages to lists of version
numbers. For example:
.. code-block:: python
# With byrepo=False (default)
{
'bash': ['4.1.2-15.el6_5.2',
'4.1.2-15.el6_5.1',
'4.1.2-15.el6_4'],
'kernel': ['2.6.32-431.29.2.el6',
'2.6.32-431.23.3.el6',
'2.6.32-431.20.5.el6',
'2.6.32-431.20.3.el6',
'2.6.32-431.17.1.el6',
'2.6.32-431.11.2.el6',
'2.6.32-431.5.1.el6',
'2.6.32-431.3.1.el6',
'2.6.32-431.1.2.0.1.el6',
'2.6.32-431.el6']
}
# With byrepo=True
{
'base': {
'bash': ['4.1.2-15.el6_4'],
'kernel': ['2.6.32-431.el6']
},
'updates': {
'bash': ['4.1.2-15.el6_5.2', '4.1.2-15.el6_5.1'],
'kernel': ['2.6.32-431.29.2.el6',
'2.6.32-431.23.3.el6',
'2.6.32-431.20.5.el6',
'2.6.32-431.20.3.el6',
'2.6.32-431.17.1.el6',
'2.6.32-431.11.2.el6',
'2.6.32-431.5.1.el6',
'2.6.32-431.3.1.el6',
'2.6.32-431.1.2.0.1.el6']
}
}
fromrepo : None
Only include results from the specified repo(s). Multiple repos can be
specified, comma-separated.
enablerepo (ignored if ``fromrepo`` is specified)
Specify a disabled package repository (or repositories) to enable.
(e.g., ``yum --enablerepo='somerepo'``)
.. versionadded:: 2017.7.0
disablerepo (ignored if ``fromrepo`` is specified)
Specify an enabled package repository (or repositories) to disable.
(e.g., ``yum --disablerepo='somerepo'``)
.. versionadded:: 2017.7.0
byrepo : False
When ``True``, the return data for each package will be organized by
repository.
.. versionadded:: 2017.7.0
cacheonly : False
When ``True``, the repo information will be retrieved from the cached
repo metadata. This is equivalent to passing the ``-C`` option to
yum/dnf.
.. versionadded:: 2017.7.0
setopt
A comma-separated or Python list of key=value options. This list will
be expanded and ``--setopt`` prepended to each in the yum/dnf command
that is run.
.. versionadded:: 2019.2.0
CLI Examples:
.. code-block:: bash
salt '*' pkg.list_repo_pkgs
salt '*' pkg.list_repo_pkgs foo bar baz
salt '*' pkg.list_repo_pkgs 'samba4*' fromrepo=base,updates
salt '*' pkg.list_repo_pkgs 'python2-*' byrepo=True
"""
byrepo = kwargs.pop("byrepo", False)
cacheonly = kwargs.pop("cacheonly", False)
fromrepo = kwargs.pop("fromrepo", "") or ""
disablerepo = kwargs.pop("disablerepo", "") or ""
enablerepo = kwargs.pop("enablerepo", "") or ""
repo_arg = _get_options(fromrepo=fromrepo, **kwargs)
if fromrepo and not isinstance(fromrepo, list):
try:
fromrepo = [x.strip() for x in fromrepo.split(",")]
except AttributeError:
fromrepo = [x.strip() for x in str(fromrepo).split(",")]
if disablerepo and not isinstance(disablerepo, list):
try:
disablerepo = [x.strip() for x in disablerepo.split(",") if x != "*"]
except AttributeError:
disablerepo = [x.strip() for x in str(disablerepo).split(",") if x != "*"]
if enablerepo and not isinstance(enablerepo, list):
try:
enablerepo = [x.strip() for x in enablerepo.split(",") if x != "*"]
except AttributeError:
enablerepo = [x.strip() for x in str(enablerepo).split(",") if x != "*"]
if fromrepo:
repos = fromrepo
else:
repos = [
repo_name
for repo_name, repo_info in list_repos(**kwargs).items()
if repo_name in enablerepo
or (
repo_name not in disablerepo
and str(repo_info.get("enabled", "1")) == "1"
)
]
ret = {}
def _check_args(args, name):
"""
Do glob matching on args and return True if a match was found.
Otherwise, return False
"""
for arg in args:
if fnmatch.fnmatch(name, arg):
return True
return False
def _parse_output(output, strict=False):
for pkg in _yum_pkginfo(output):
if strict and (pkg.repoid not in repos or not _check_args(args, pkg.name)):
continue
repo_dict = ret.setdefault(pkg.repoid, {})
version_list = repo_dict.setdefault(pkg.name, set())
version_list.add(pkg.version)
yum_version = (
None
if _yum() != "yum"
else LooseVersion(
__salt__["cmd.run"](["yum", "--version"], python_shell=False)
.splitlines()[0]
.strip()
)
)
# Really old version of yum; does not even have --showduplicates option
if yum_version and yum_version < LooseVersion("3.2.13"):
cmd_prefix = ["--quiet"]
if cacheonly:
cmd_prefix.append("-C")
cmd_prefix.append("list")
for pkg_src in ("installed", "available"):
# Check installed packages first
out = _call_yum(cmd_prefix + [pkg_src], ignore_retcode=True)
if out["retcode"] == 0:
_parse_output(out["stdout"], strict=True)
# The --showduplicates option is added in 3.2.13, but the
# repository-packages subcommand is only in 3.4.3 and newer
elif yum_version and yum_version < LooseVersion("3.4.3"):
cmd_prefix = ["--quiet", "--showduplicates"]
if cacheonly:
cmd_prefix.append("-C")
cmd_prefix.append("list")
for pkg_src in ("installed", "available"):
# Check installed packages first
out = _call_yum(cmd_prefix + [pkg_src], ignore_retcode=True)
if out["retcode"] == 0:
_parse_output(out["stdout"], strict=True)
else:
for repo in repos:
if _yum() == "tdnf":
cmd = ["--quiet", f"--enablerepo={repo}", "list"]
else:
cmd = [
"--quiet",
"--showduplicates",
"repository-packages",
repo,
"list",
]
if cacheonly:
cmd.append("-C")
# Can't concatenate because args is a tuple, using list.extend()
cmd.extend(args)
out = _call_yum(cmd, ignore_retcode=True)
if out["retcode"] != 0 and "Error:" in out["stdout"]:
continue
_parse_output(out["stdout"])
if byrepo:
for reponame in ret:
# Sort versions newest to oldest
for pkgname in ret[reponame]:
sorted_versions = sorted(
(LooseVersion(x) for x in ret[reponame][pkgname]), reverse=True
)
ret[reponame][pkgname] = [x.vstring for x in sorted_versions]
return ret
else:
byrepo_ret = {}