/
yumpkg.py
2199 lines (1742 loc) · 68 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
# -*- coding: utf-8 -*-
'''
Support for YUM
.. note::
This module makes heavy use of the **repoquery** utility, from the
yum-utils_ package. This package will be installed as a dependency if salt
is installed via EPEL. However, if salt has been installed using pip, or a
host is being managed using salt-ssh, then as of version 2014.7.0
yum-utils_ will be installed automatically to satisfy this dependency.
.. _yum-utils: http://yum.baseurl.org/wiki/YumUtils
'''
# Import python libs
from __future__ import absolute_import
import copy
import logging
import os
import re
from distutils.version import LooseVersion as _LooseVersion # pylint: disable=no-name-in-module,import-error
# Import 3rd-party libs
# pylint: disable=import-error,redefined-builtin
import salt.ext.six as six
from salt.ext.six import string_types
from salt.ext.six.moves import shlex_quote as _cmd_quote, range
try:
import yum
HAS_YUM = True
except ImportError:
from salt.ext.six.moves import configparser
HAS_YUM = False
# pylint: enable=import-error
# Import salt libs
import salt.utils
import salt.utils.decorators as decorators
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
log = logging.getLogger(__name__)
__QUERYFORMAT = '%{NAME}_|-%{VERSION}_|-%{RELEASE}_|-%{ARCH}_|-%{REPOID}'
# These arches compiled from the rpmUtils.arch python module source
__ARCHES_64 = ('x86_64', 'athlon', 'amd64', 'ia32e', 'ia64', 'geode')
__ARCHES_32 = ('i386', 'i486', 'i586', 'i686')
__ARCHES_PPC = ('ppc', 'ppc64', 'ppc64iseries', 'ppc64pseries')
__ARCHES_S390 = ('s390', 's390x')
__ARCHES_SPARC = (
'sparc', 'sparcv8', 'sparcv9', 'sparcv9v', 'sparc64', 'sparc64v'
)
__ARCHES_ALPHA = (
'alpha', 'alphaev4', 'alphaev45', 'alphaev5', 'alphaev56',
'alphapca56', 'alphaev6', 'alphaev67', 'alphaev68', 'alphaev7'
)
__ARCHES_ARM = ('armv5tel', 'armv5tejl', 'armv6l', 'armv7l')
__ARCHES_SH = ('sh3', 'sh4', 'sh4a')
__ARCHES = __ARCHES_64 + __ARCHES_32 + __ARCHES_PPC + __ARCHES_S390 + \
__ARCHES_ALPHA + __ARCHES_ARM + __ARCHES_SH
# 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
try:
os_grain = __grains__['os'].lower()
os_family = __grains__['os_family'].lower()
except Exception:
return False
enabled = ('amazon', 'xcp', 'xenserver')
if os_family == 'redhat' or os_grain in enabled:
return __virtualname__
return False
def _parse_pkginfo(line):
'''
A small helper to parse a repoquery; returns a namedtuple
'''
# Importing `collections` here since this function is re-namespaced into
# another module
import collections
pkginfo = collections.namedtuple(
'PkgInfo',
('name', 'version', 'arch', 'repoid')
)
try:
name, pkg_version, release, arch, repoid = line.split('_|-')
# Handle unpack errors (should never happen with the queryformat we are
# using, but can't hurt to be careful).
except ValueError:
return None
if not _check_32(arch):
if arch not in (__grains__['osarch'], 'noarch'):
name += '.{0}'.format(arch)
if release:
pkg_version += '-{0}'.format(release)
return pkginfo(name, pkg_version, arch, repoid)
def _repoquery_pkginfo(repoquery_args):
'''
Wrapper to call repoquery and parse out all the tuples
'''
ret = []
for line in _repoquery(repoquery_args):
pkginfo = _parse_pkginfo(line)
if pkginfo is not None:
ret.append(pkginfo)
return ret
def _check_repoquery():
'''
Check for existence of repoquery and install yum-utils if it is not
present.
'''
if not salt.utils.which('repoquery'):
__salt__['cmd.run'](
['yum', '-y', 'install', 'yum-utils'],
python_shell=False,
output_loglevel='trace'
)
# Check again now that we've installed yum-utils
if not salt.utils.which('repoquery'):
raise CommandExecutionError('Unable to install yum-utils')
def _repoquery(repoquery_args, query_format=__QUERYFORMAT):
'''
Runs a repoquery command and returns a list of namedtuples
'''
_check_repoquery()
cmd = 'repoquery --plugins --queryformat {0} {1}'.format(
_cmd_quote(query_format), repoquery_args
)
call = __salt__['cmd.run_all'](cmd, output_loglevel='trace')
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(
'{0}'.format(comment)
)
else:
out = call['stdout']
return out.splitlines()
def _get_repo_options(**kwargs):
'''
Returns a string of '--enablerepo' and '--disablerepo' options to be used
in the yum command, based on the kwargs.
'''
# Get repo options from the kwargs
fromrepo = kwargs.get('fromrepo', '')
repo = kwargs.get('repo', '')
disablerepo = kwargs.get('disablerepo', '')
enablerepo = kwargs.get('enablerepo', '')
# Support old 'repo' argument
if repo and not fromrepo:
fromrepo = repo
repo_arg = ''
if fromrepo:
log.info('Restricting to repo {0!r}'.format(fromrepo))
repo_arg = ('--disablerepo={0!r} --enablerepo={1!r}'
.format('*', fromrepo))
else:
repo_arg = ''
if disablerepo:
log.info('Disabling repo {0!r}'.format(disablerepo))
repo_arg += '--disablerepo={0!r}'.format(disablerepo)
if enablerepo:
log.info('Enabling repo {0!r}'.format(enablerepo))
repo_arg += '--enablerepo={0!r}'.format(enablerepo)
return repo_arg
def _get_excludes_option(**kwargs):
'''
Returns a string of '--disableexcludes' option to be used in the yum command,
based on the kwargs.
'''
disable_excludes_arg = ''
disable_excludes = kwargs.get('disableexcludes', '')
if disable_excludes:
log.info('Disabling excludes for {0!r}'.format(disable_excludes))
disable_excludes_arg = ('--disableexcludes={0!r}'.format(disable_excludes))
return disable_excludes_arg
def _get_branch_option(**kwargs):
'''
Returns a string of '--branch' option to be used in the yum command,
based on the kwargs. This feature requires 'branch' plugin for YUM.
'''
# Get branch option from the kwargs
branch = kwargs.get('branch', '')
branch_arg = ''
if branch:
log.info('Adding branch {0!r}'.format(branch))
branch_arg = ('--branch={0!r}'.format(branch))
return branch_arg
def _check_32(arch):
'''
Returns True if both the OS arch and the passed arch are 32-bit
'''
return all(x in __ARCHES_32 for x in (__grains__['osarch'], arch))
def _rpm_pkginfo(name):
'''
Parses RPM metadata and returns a pkginfo namedtuple
'''
# REPOID is not a valid tag for the rpm command. Remove it and replace it
# with 'none'
queryformat = __QUERYFORMAT.replace('%{REPOID}', 'none')
output = __salt__['cmd.run_stdout'](
'rpm -qp --queryformat {0!r} {1}'.format(_cmd_quote(queryformat), name),
output_loglevel='trace',
ignore_retcode=True
)
return _parse_pkginfo(output)
def _rpm_installed(name):
'''
Parses RPM metadata to determine if the RPM target is already installed.
Returns the name of the installed package if found, otherwise None.
'''
pkg = _rpm_pkginfo(name)
try:
return pkg.name if pkg.name in list_pkgs() else None
except AttributeError:
return None
def _get_yum_config():
'''
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.
If the yum python library is available, use that, which will give us
all of the options, including all of the defaults not specified in the
yum config. Additionally, they will all be of the correct object type.
If the yum library is not available, 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'],
}
if HAS_YUM:
try:
yb = yum.YumBase()
yb.preconf.init_plugins = False
for name, value in yb.conf.iteritems():
conf[name] = value
except (AttributeError, yum.Errors.ConfigError) as exc:
raise CommandExecutionError(
'Could not query yum config: {0}'.format(exc)
)
else:
# 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')
for path in paths:
if os.path.exists(path):
fn = path
break
if not fn:
raise CommandExecutionError(
'No suitable yum config file found in: {0}'.format(paths)
)
cp = configparser.ConfigParser()
try:
cp.read(fn)
except (IOError, OSError) as exc:
raise CommandExecutionError(
'Unable to read from {0}: {1}'.format(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 {0}, using internal defaults'.format(fn))
return conf
def _get_yum_config_value(name):
'''
Look for a specific config variable and return its value
'''
conf = _get_yum_config()
if name in conf.keys():
return conf.get(name)
return None
def _normalize_basedir(basedir=None):
'''
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 basedir is None:
basedir = []
# if we are passed a string (for backward compatibility), convert to a list
if isinstance(basedir, basestring):
basedir = [x.strip() for x in basedir.split(',')]
# nothing specified, so use the reposdir option as the default
if not basedir:
basedir = _get_yum_config_value('reposdir')
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('.', 1)[-1]
if arch not in __ARCHES + ('noarch',):
return name
except ValueError:
return name
if arch in (__grains__['osarch'], 'noarch') or _check_32(arch):
return name[:-(len(arch) + 1)]
return name
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.is_true(kwargs.pop('refresh', True))
if len(names) == 0:
return ''
# Initialize the return dict with empty strings, and populate namearch_map.
# namearch_map will provide a means of distinguishing between multiple
# matches for the same package name, for example a target of 'glibc' on an
# x86_64 arch would return both x86_64 and i686 versions when searched
# using repoquery:
#
# $ repoquery --all --pkgnarrow=available glibc
# glibc-0:2.12-1.132.el6.i686
# glibc-0:2.12-1.132.el6.x86_64
#
# Note that the logic in the for loop below would place the osarch into the
# map for noarch packages, but those cases are accounted for when iterating
# through the repoquery results later on. If the repoquery match for that
# package is a noarch, then the package is assumed to be noarch, and the
# namearch_map is ignored.
ret = {}
namearch_map = {}
for name in names:
ret[name] = ''
try:
arch = name.rsplit('.', 1)[-1]
if arch not in __ARCHES:
arch = __grains__['osarch']
except ValueError:
arch = __grains__['osarch']
namearch_map[name] = arch
repo_arg = _get_repo_options(**kwargs)
exclude_arg = _get_excludes_option(**kwargs)
# Refresh before looking for the latest version available
if refresh:
refresh_db(_get_branch_option(**kwargs), repo_arg, exclude_arg)
# Get updates for specified package(s)
updates = _repoquery_pkginfo(
'{0} {1} --pkgnarrow=available {2}'
.format(repo_arg, exclude_arg, ' '.join(names))
)
for name in names:
for pkg in (x for x in updates if x.name == name):
if pkg.arch == 'noarch' or pkg.arch == namearch_map[name] \
or _check_32(pkg.arch):
ret[name] = pkg.version
# no need to check another match, if there was one
break
# 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 = latest_version
def upgrade_available(name):
'''
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) != ''
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 list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {}
for pkginfo in _repoquery_pkginfo('--all --pkgnarrow=installed'):
if pkginfo is None:
continue
__salt__['pkg_resource.add_pkg'](ret, pkginfo.name, pkginfo.version)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret
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.
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.
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 is a dictionary of repo names, with each repo containing a
dictionary in which the keys are package names, and the values are a list
of version numbers. Here is an example of the return data:
.. code-block:: python
{
'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.
CLI Example:
.. 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
'''
try:
repos = tuple(x.strip() for x in kwargs.get('fromrepo').split(','))
except AttributeError:
# Search in all enabled repos
repos = tuple(
x for x, y in six.iteritems(list_repos())
if str(y.get('enabled', '1')) == '1'
)
ret = {}
for repo in repos:
repoquery_cmd = '--all --repoid="{0}" --show-duplicates'.format(repo)
for arg in args:
repoquery_cmd += ' "{0}"'.format(arg)
all_pkgs = _repoquery_pkginfo(repoquery_cmd)
for pkg in all_pkgs:
repo_dict = ret.setdefault(pkg.repoid, {})
version_list = repo_dict.setdefault(pkg.name, [])
version_list.append(pkg.version)
for reponame in ret:
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
def list_upgrades(refresh=True, **kwargs):
'''
Check whether or not an upgrade is available for all packages
The ``fromrepo``, ``enablerepo``, and ``disablerepo`` arguments are
supported, as used in pkg states, and the ``disableexcludes`` option is
also supported.
.. versionadded:: 2014.7.0
Support for the ``disableexcludes`` option
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
repo_arg = _get_repo_options(**kwargs)
exclude_arg = _get_excludes_option(**kwargs)
if salt.utils.is_true(refresh):
refresh_db(_get_branch_option(**kwargs), repo_arg, exclude_arg)
updates = _repoquery_pkginfo(
'{0} {1} --all --pkgnarrow=updates'.format(repo_arg, exclude_arg)
)
return dict([(x.name, x.version) for x in updates])
def check_db(*names, **kwargs):
'''
.. versionadded:: 0.17.0
Returns a dict containing the following information for each specified
package:
1. A key ``found``, which will be a boolean value denoting if a match was
found in the package database.
2. If ``found`` is ``False``, then a second key called ``suggestions`` will
be present, which will contain a list of possible matches.
The ``fromrepo``, ``enablerepo`` and ``disablerepo`` arguments are
supported, as used in pkg states, and the ``disableexcludes`` option is
also supported.
.. versionadded:: 2014.7.0
Support for the ``disableexcludes`` option
CLI Examples:
.. code-block:: bash
salt '*' pkg.check_db <package1> <package2> <package3>
salt '*' pkg.check_db <package1> <package2> <package3> fromrepo=epel-testing
salt '*' pkg.check_db <package1> <package2> <package3> disableexcludes=main
'''
normalize = kwargs.pop('normalize') if kwargs.get('normalize') else False
repo_arg = _get_repo_options(**kwargs)
exclude_arg = _get_excludes_option(**kwargs)
repoquery_base = \
'{0} {1} --all --quiet --whatprovides'.format(repo_arg, exclude_arg)
if 'pkg._avail' in __context__:
avail = __context__['pkg._avail']
else:
# get list of available packages
avail = []
lines = _repoquery(
'{0} --pkgnarrow=all --all'.format(repo_arg),
query_format='%{NAME}_|-%{ARCH}'
)
for line in lines:
try:
name, arch = line.split('_|-')
except ValueError:
continue
if normalize:
avail.append(normalize_name('.'.join((name, arch))))
else:
avail.append('.'.join((name, arch)))
__context__['pkg._avail'] = avail
ret = {}
for name in names:
ret.setdefault(name, {})['found'] = name in avail
if not ret[name]['found']:
repoquery_cmd = repoquery_base + ' {0}'.format(name)
provides = sorted(
set(x.name for x in _repoquery_pkginfo(repoquery_cmd))
)
if name in provides:
# Package was not in avail but was found by the repoquery_cmd
ret[name]['found'] = True
else:
ret[name]['suggestions'] = provides
return ret
def refresh_db(branch_arg=None, repo_arg=None, exclude_arg=None, branch=None, repo=None, exclude=None):
'''
Check the yum repos for updated packages
Returns:
- ``True``: Updates are available
- ``False``: An error occurred
- ``None``: No updates are available
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
def warn(old, new):
'''
warn about old arguments
'''
salt.utils.warn_until(
'Carbon',
'"{0}" is being deprecated in favor of "{1}"'.format(old, new)
)
if branch_arg:
warn(branch_arg, branch)
branch = branch_arg
if repo_arg:
warn(repo_arg, repo)
repo = repo_arg
if exclude_arg:
warn(exclude_arg, exclude)
exclude = exclude_arg
retcodes = {
100: True,
0: None,
1: False,
}
clean_cmd = ['yum', '-q', 'clean', 'expire-cache']
update_cmd = ['yum', '-q', 'check-update']
if repo:
clean_cmd.append(repo)
update_cmd.append(repo)
if exclude:
clean_cmd.append(exclude)
update_cmd.append(exclude)
if branch:
clean_cmd.append(branch)
update_cmd.append(branch)
__salt__['cmd.run'](clean_cmd, python_shell=False)
ret = __salt__['cmd.retcode'](update_cmd,
python_shell=False,
ignore_retcode=True)
return retcodes.get(ret, False)
def clean_metadata(**kwargs):
'''
.. versionadded:: 2014.1.0
Cleans local yum metadata. Functionally identical to :mod:`refresh_db()
<salt.modules.yumpkg.refresh_db>`.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_metadata
'''
return refresh_db(_get_branch_option(**kwargs), _get_repo_options(**kwargs), _get_excludes_option(**kwargs))
def group_install(name,
skip=(),
include=(),
**kwargs):
'''
.. versionadded:: 2014.1.0
Install the passed package group(s). This is basically a wrapper around
pkg.install, which performs package group resolution for the user. This
function is currently considered experimental, and should be expected to
undergo changes.
name
Package group to install. To install more than one group, either use a
comma-separated list or pass the value as a python list.
CLI Examples:
.. code-block:: bash
salt '*' pkg.group_install 'Group 1'
salt '*' pkg.group_install 'Group 1,Group 2'
salt '*' pkg.group_install '["Group 1", "Group 2"]'
skip
The name(s), in a list, of any packages that would normally be
installed by the package group ("default" packages), which should not
be installed. Can be passed either as a comma-separated list or a
python list.
CLI Examples:
.. code-block:: bash
salt '*' pkg.group_install 'My Group' skip='foo,bar'
salt '*' pkg.group_install 'My Group' skip='["foo", "bar"]'
include
The name(s), in a list, of any packages which are included in a group,
which would not normally be installed ("optional" packages). Note that
this will not enforce group membership; if you include packages which
are not members of the specified groups, they will still be installed.
Can be passed either as a comma-separated list or a python list.
CLI Examples:
.. code-block:: bash
salt '*' pkg.group_install 'My Group' include='foo,bar'
salt '*' pkg.group_install 'My Group' include='["foo", "bar"]'
.. note::
Because this is essentially a wrapper around pkg.install, any argument
which can be passed to pkg.install may also be included here, and it
will be passed along wholesale.
'''
groups = name.split(',') if isinstance(name, string_types) else name
if not groups:
raise SaltInvocationError('no groups specified')
elif not isinstance(groups, list):
raise SaltInvocationError('\'groups\' must be a list')
# pylint: disable=maybe-no-member
if isinstance(skip, string_types):
skip = skip.split(',')
if not isinstance(skip, (list, tuple)):
raise SaltInvocationError('\'skip\' must be a list')
if isinstance(include, string_types):
include = include.split(',')
if not isinstance(include, (list, tuple)):
raise SaltInvocationError('\'include\' must be a list')
# pylint: enable=maybe-no-member
targets = []
for group in groups:
group_detail = group_info(group)
targets.extend(group_detail.get('mandatory packages', []))
targets.extend(
[pkg for pkg in group_detail.get('default packages', [])
if pkg not in skip]
)
if include:
targets.extend(include)
# Don't install packages that are already installed, install() isn't smart
# enough to make this distinction.
pkgs = [x for x in targets if x not in list_pkgs()]
if not pkgs:
return {}
return install(pkgs=pkgs, **kwargs)
def install(name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
pkgs=None,
sources=None,
reinstall=False,
normalize=True,
**kwargs):
'''
Install the passed package(s), add refresh=True to clean the yum database
before package is installed.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``.i686``, ``.i586``, etc.) to the end of the
package name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to update the yum database before executing.
reinstall
Specifying reinstall=True will use ``yum reinstall`` rather than
``yum install`` for requested packages that are already installed.
If a version is specified with the requested package, then
``yum reinstall`` will only be used if the installed version
matches the requested version.
Works with sources when the package header of the source can be
matched to the name and version of an installed package.
.. versionadded:: 2014.7.0
skip_verify
Skip the GPG verification check (e.g., ``--nogpgcheck``)
version
Install a specific version of the package, e.g. 1.2.3-4.el5. Ignored
if "pkgs" or "sources" is passed.
Repository Options:
fromrepo
Specify a package repository (or repositories) from which to install.
(e.g., ``yum --disablerepo='*' --enablerepo='somerepo'``)
enablerepo (ignored if ``fromrepo`` is specified)
Specify a disabled package repository (or repositories) to enable.
(e.g., ``yum --enablerepo='somerepo'``)
disablerepo (ignored if ``fromrepo`` is specified)
Specify an enabled package repository (or repositories) to disable.
(e.g., ``yum --disablerepo='somerepo'``)
disableexcludes
Disable exclude from main, for a repo or for everything.
(e.g., ``yum --disableexcludes='main'``)
.. versionadded:: 2014.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list. A specific version number can be specified
by using a single-element dict representing the package and its
version.
CLI Examples:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-4.el5"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'
normalize