-
Notifications
You must be signed in to change notification settings - Fork 82
/
__init__.py
7244 lines (6290 loc) · 302 KB
/
__init__.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
#!/usr/bin/python -tt
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# Copyright 2005 Duke University
"""
The Yum RPM software updater.
"""
import os
import os.path
import rpm
import sys
def _rpm_ver_atleast(vertup):
""" Check if rpm is at least the current vertup. Can return False/True/None
as rpm hasn't had version info for a long time. """
if not hasattr(rpm, '__version_info__'):
return None
try:
# 4.8.x rpm used strings for the tuple members, so convert.
vi = tuple([ int(num) for num in rpm.__version_info__])
return vi >= vertup
except:
return None # Something went wrong...
import re
import types
import errno
import time
import glob
import fnmatch
import logging
import logging.config
import operator
import tempfile
import shutil
import yum.i18n
# This is required to make gaftonmode work...
_wrap_yum_i18n__ = yum.i18n._
def _(*args, **kwargs):
return _wrap_yum_i18n__(*args, **kwargs)
_wrap_yum_i18n_P_ = yum.i18n.P_
def P_(*args, **kwargs):
return _wrap_yum_i18n_P_(*args, **kwargs)
import config
from config import ParsingError, ConfigParser
import Errors
import rpmsack
import rpmUtils.updates
from rpmUtils.arch import archDifference, canCoinstall, ArchStorage, isMultiLibArch
from rpmUtils.miscutils import compareEVR
import rpmUtils.transaction
import comps
import pkgtag_db
from repos import RepoStorage
import misc
from parser import ConfigPreProcessor, varReplace
import transactioninfo
import urlgrabber
from urlgrabber.grabber import URLGrabber, URLGrabError
from urlgrabber.progress import format_number
from packageSack import packagesNewestByName, packagesNewestByNameArch, ListPackageSack
import depsolve
import plugins
import logginglevels
import yumRepo
import callbacks
import yum.history
import yum.fssnapshots
from yum.fssnapshots import LibLVMError, lvmerr2str
import yum.igroups
import update_md
import warnings
warnings.simplefilter("ignore", Errors.YumFutureDeprecationWarning)
from packages import parsePackages, comparePoEVR
from packages import YumAvailablePackage, YumLocalPackage, YumInstalledPackage
from packages import YumUrlPackage, YumNotFoundPackage
from constants import *
from yum.rpmtrans import RPMTransaction,SimpleCliCallBack
from yum.i18n import to_unicode, to_str, exception2msg
from yum.drpm import DeltaInfo, DeltaPackage
import StringIO
from weakref import proxy as weakref
from urlgrabber.grabber import default_grabber
try:
import cashe
except ImportError:
cashe = None
__version__ = '3.4.3'
__version_info__ = tuple([ int(num) for num in __version__.split('.')])
# Setup a default_grabber UA here that says we are yum, done using the global
# so that other API users can easily add to it if they want.
# Don't do it at init time, or we'll get multiple additions if you create
# multiple YumBase() objects.
default_grabber.opts.user_agent += " yum/" + __version__
class _YumPreBaseConf:
"""This is the configuration interface for the :class:`YumBase`
configuration. To change configuration settings such as whether
plugins are on or off, or the value of debuglevel, change the
values here. Later, when :func:`YumBase.conf` is first called, all
of the options will be automatically configured.
"""
def __init__(self):
self.fn = '/etc/yum/yum.conf'
self.root = '/'
self.init_plugins = True
self.plugin_types = (plugins.TYPE_CORE,)
self.optparser = None
self.debuglevel = None
self.errorlevel = None
self.disabled_plugins = None
self.enabled_plugins = None
self.syslog_ident = None
self.syslog_facility = None
self.syslog_device = None
self.arch = None
self.releasever = None
self.uuid = None
class _YumPreRepoConf:
"""This is the configuration interface for the repos configuration
configuration. To change configuration settings such what
callbacks are used, change the values here. Later, when
:func:`YumBase.repos` is first called, all of the options will be
automatically configured.
"""
def __init__(self):
self.progressbar = None
self.multi_progressbar = None
self.callback = None
self.failure_callback = None
self.interrupt_callback = None
self.confirm_func = None
self.gpg_import_func = None
self.gpgca_import_func = None
self.cachedir = None
self.cache = None
class _YumCostExclude:
""" This excludes packages that are in repos. of lower cost than the passed
repo. """
def __init__(self, repo, repos):
self.repo = weakref(repo)
self._repos = weakref(repos)
def __contains__(self, pkgtup):
# (n, a, e, v, r) = pkgtup
for repo in self._repos.listEnabled():
if repo.cost >= self.repo.cost:
break
# searchNevra is a bit slower, although more generic for repos.
# that don't use sqlitesack as the backend ... although they are
# probably screwed anyway.
#
# if repo.sack.searchNevra(n, e, v, r, a):
if pkgtup in repo.sack._pkgtup2pkgs:
return True
return False
class YumBase(depsolve.Depsolve):
"""This is a primary structure and base class. It houses the
objects and methods needed to perform most things in yum. It is
almost an abstract class in that you will need to add your own
class above it for most real use.
"""
def __init__(self):
depsolve.Depsolve.__init__(self)
self._conf = None
self._tsInfo = None
self._rpmdb = None
self._up = None
self._comps = None
self._history = None
self._igroups = None
self._pkgSack = None
self._lockfile = None
self._tags = None
self._upinfo = None
self._fssnap = None
self._ts_save_file = None
self.skipped_packages = [] # packages skip by the skip-broken code
self._not_found_a = {}
self._not_found_i = {}
self.logger = logging.getLogger("yum.YumBase")
self.verbose_logger = logging.getLogger("yum.verbose.YumBase")
self.file_logger = logging.getLogger("yum.filelogging.YumBase")
self._override_sigchecks = False
self._repos = RepoStorage(self)
self.repo_setopts = {} # since we have to use repo_setopts in base and
# not in cli - set it up as empty so no one
# trips over it later
# Start with plugins disabled
self.disablePlugins()
self.localPackages = [] # for local package handling
self.mediagrabber = None
self.arch = ArchStorage()
self.preconf = _YumPreBaseConf()
self.prerepoconf = _YumPreRepoConf()
self.run_with_package_names = set()
self._cleanup = []
self.exit_code = 0
self.updateinfo_filters = {}
def __del__(self):
try:
self.close()
self.closeRpmDB()
self.doUnlock()
# call cleanup callbacks
for cb in self._cleanup: cb()
except Errors.RepoError, e:
self.verbose_logger.debug("Exception %s %s in %s ignored" % (repr(e), str(e), self.__del__))
def close(self):
"""Close the history and repo objects."""
# We don't want to create the object, so we test if it's been created
if self._history is not None:
self.history.close()
if self._igroups is not None:
self.igroups.close()
if self._repos:
self._repos.close()
def _transactionDataFactory(self):
"""Factory method returning TransactionData object"""
return transactioninfo.TransactionData()
def doGenericSetup(self, cache=0):
"""Do a default setup for all the normal or necessary yum
components. This function is really just a shorthand for
testing purposes.
:param cache: whether to run in cache only mode, which will
run only from the system cache
"""
self.preconf.init_plugins = False
self.conf.cache = cache
def doConfigSetup(self, fn='/etc/yum/yum.conf', root='/', init_plugins=True,
plugin_types=(plugins.TYPE_CORE,), optparser=None, debuglevel=None,
errorlevel=None):
"""Deprecated. Perform configuration setup.
:param fn: the name of the configuration file to use
:param root: the root directory to use
:param init_plugins: whether to initialize plugins before
running yum
:param plugin_types: a tuple containing the types to plugins
to load
:param optparser: the option parser to use for configuration
:param debuglevel: the minimum debug logging level to output
messages from
:param errorlevel: the minimum error logging level to output
messages from
"""
warnings.warn(_('doConfigSetup() will go away in a future version of Yum.\n'),
Errors.YumFutureDeprecationWarning, stacklevel=2)
if hasattr(self, 'preconf'):
self.preconf.fn = fn
self.preconf.root = root
self.preconf.init_plugins = init_plugins
self.preconf.plugin_types = plugin_types
self.preconf.optparser = optparser
self.preconf.debuglevel = debuglevel
self.preconf.errorlevel = errorlevel
return self.conf
def _getConfig(self, **kwargs):
'''
Parse and load Yum's configuration files and call hooks initialise
plugins and logging. Uses self.preconf for pre-configuration,
configuration. '''
# ' xemacs syntax hack
if kwargs:
warnings.warn('Use .preconf instead of passing args to _getConfig')
if self._conf:
return self._conf
conf_st = time.time()
if kwargs:
for arg in ('fn', 'root', 'init_plugins', 'plugin_types',
'optparser', 'debuglevel', 'errorlevel',
'disabled_plugins', 'enabled_plugins'):
if arg in kwargs:
setattr(self.preconf, arg, kwargs[arg])
fn = self.preconf.fn
root = self.preconf.root
init_plugins = self.preconf.init_plugins
plugin_types = self.preconf.plugin_types
optparser = self.preconf.optparser
debuglevel = self.preconf.debuglevel
errorlevel = self.preconf.errorlevel
disabled_plugins = self.preconf.disabled_plugins
enabled_plugins = self.preconf.enabled_plugins
syslog_ident = self.preconf.syslog_ident
syslog_facility = self.preconf.syslog_facility
syslog_device = self.preconf.syslog_device
releasever = self.preconf.releasever
arch = self.preconf.arch
uuid = self.preconf.uuid
if arch: # if preconf is setting an arch we need to pass that up
self.arch.setup_arch(arch)
else:
arch = self.arch.canonarch
# TODO: Remove this block when we no longer support configs outside
# of /etc/yum/
if fn == '/etc/yum/yum.conf' and not os.path.exists(fn):
# Try the old default
fn = '/etc/yum.conf'
startupconf = config.readStartupConfig(fn, root, releasever)
startupconf.arch = arch
startupconf.basearch = self.arch.basearch
if uuid:
startupconf.uuid = uuid
if startupconf.gaftonmode:
global _wrap_yum_i18n__
_wrap_yum_i18n__ = yum.i18n.dummy_wrapper
global _wrap_yum_i18n_P_
_wrap_yum_i18n_P_ = yum.i18n.dummyP_wrapper
if debuglevel != None:
startupconf.debuglevel = debuglevel
if errorlevel != None:
startupconf.errorlevel = errorlevel
if syslog_ident != None:
startupconf.syslog_ident = syslog_ident
if syslog_facility != None:
startupconf.syslog_facility = syslog_facility
if syslog_device != None:
startupconf.syslog_device = syslog_device
if releasever == '/':
if startupconf.installroot == '/':
releasever = None
else:
releasever = yum.config._getsysver("/",startupconf.distroverpkg)
if releasever != None:
startupconf.releasever = releasever
self.doLoggingSetup(startupconf.debuglevel, startupconf.errorlevel,
startupconf.syslog_ident,
startupconf.syslog_facility,
startupconf.syslog_device)
if init_plugins and startupconf.plugins:
self.doPluginSetup(optparser, plugin_types, startupconf.pluginpath,
startupconf.pluginconfpath,disabled_plugins,enabled_plugins)
self._conf = config.readMainConfig(startupconf)
# update urlgrabber defaults
mc = self._conf.max_connections
if mc > 0:
default_grabber.opts.max_connections = mc
default_grabber.opts.timedhosts = self._conf.cachedir + '/timedhosts'
# We don't want people accessing/altering preconf after it becomes
# worthless. So we delete it, and thus. it'll raise AttributeError
del self.preconf
# Packages used to run yum...
for pkgname in self.conf.history_record_packages:
self.run_with_package_names.add(pkgname)
self._cashe = None
if cashe is not None:
self._cashe = cashe.CAShe(self.conf.cashe_root_dir)
# run the postconfig plugin hook
self.plugins.run('postconfig')
# Note that Pungi has historically replaced _getConfig(), and it sets
# up self.conf.yumvar but not self.yumvar ... and AFAIK nothing needs
# to use YumBase.yumvar, so it's probably easier to just semi-deprecate
# this (core now only uses YumBase.conf.yumvar).
self.yumvar = self.conf.yumvar
# who are we:
self.conf.uid = os.geteuid()
# repos are ver/arch specific so add $basearch/$releasever
self.conf._repos_persistdir = os.path.normpath('%s/repos/%s/%s/'
% (self.conf.persistdir, self.yumvar.get('basearch', '$basearch'),
self.yumvar.get('releasever', '$releasever')))
self.doFileLogSetup(self.conf.uid, self.conf.logfile)
self.verbose_logger.debug('Config time: %0.3f' % (time.time() - conf_st))
self.plugins.run('init')
return self._conf
def doLoggingSetup(self, debuglevel, errorlevel,
syslog_ident=None, syslog_facility=None,
syslog_device='/dev/log'):
"""Perform logging related setup.
:param debuglevel: the minimum debug logging level to output
messages from
:param errorlevel: the minimum error logging level to output
messages from
:param syslog_ident: the ident of the syslog to use
:param syslog_facility: the name of the syslog facility to use
:param syslog_device: the syslog device to use
"""
logginglevels.doLoggingSetup(debuglevel, errorlevel,
syslog_ident, syslog_facility,
syslog_device)
def doFileLogSetup(self, uid, logfile):
"""Set up the logging file.
:param uid: the user id of the current user
:param logfile: the name of the file to use for logging
"""
logginglevels.setFileLog(uid, logfile, self._cleanup)
def getReposFromConfigFile(self, repofn, repo_age=None, validate=None):
"""Read in repositories from a config .repo file.
:param repofn: a string specifying the path of the .repo file
to read
:param repo_age: the last time that the .repo file was
modified, in seconds since the epoch
"""
if repo_age is None:
repo_age = os.stat(repofn)[8]
confpp_obj = ConfigPreProcessor(repofn, vars=self.conf.yumvar)
parser = ConfigParser()
try:
parser.readfp(confpp_obj)
except ParsingError, e:
raise Errors.ConfigError(exception2msg(e))
# Check sections in the .repo file that was just slurped up
for section in parser.sections():
if section in ['main', 'installed']:
continue
# Check the repo.id against the valid chars
bad = misc.validate_repoid(section)
if bad:
self.logger.warning("Bad id for repo: %s, byte = %s %d" %
(section, bad, section.find(bad)))
continue
try:
thisrepo = self.readRepoConfig(parser, section)
except (Errors.RepoError, Errors.ConfigError), e:
self.logger.warning(e)
continue
else:
thisrepo.repo_config_age = repo_age
thisrepo.repofile = repofn
thisrepo.base_persistdir = self.conf._repos_persistdir
# do the wildcard ones first
# The keys are in indeterminate order at this point, *sigh*.
for i in sorted(self.repo_setopts):
# Skip normal names, as we want to do wildcard matches first
# and then override with specific id stuff.
if not misc.re_glob(i):
continue
if fnmatch.fnmatch(thisrepo.id, i):
for opt in self.repo_setopts[i].items:
self._checkOption(opt, thisrepo)
setattr(thisrepo, opt, getattr(self.repo_setopts[i], opt))
if thisrepo.id in self.repo_setopts:
for opt in self.repo_setopts[thisrepo.id].items:
self._checkOption(opt, thisrepo)
setattr(thisrepo, opt, getattr(self.repo_setopts[thisrepo.id], opt))
if validate and not validate(thisrepo):
continue
if thisrepo.ssl_check_cert_permissions:
for fn in (thisrepo.sslcacert,
thisrepo.sslclientcert, thisrepo.sslclientkey):
if not fn:
continue
# If we can't read the SSL certs. we need to skip the repo.
# if we don't have all the data.
if not os.access(fn, os.R_OK):
msg="Repo %s forced skip_if_unavailable=True due to: %s"
if thisrepo.enabled:
# Don't spam messages for disabled repos.
self.logger.warning(msg % (thisrepo.id, fn))
thisrepo.skip_if_unavailable = True
# Got our list of repo objects, add them to the repos
# collection
try:
self._repos.add(thisrepo)
except Errors.RepoError, e:
self.logger.warning(e)
def _checkOption(self, opt, thisrepo):
"""Quit if the option is invalid"""
if not hasattr(thisrepo, opt):
msg = "Invalid option: %s"
raise Errors.ConfigError(msg % opt)
def getReposFromConfig(self):
"""Read in repositories from the main yum conf file, and from
.repo files. The location of the main yum conf file is given
by self.conf.config_file_path, and the location of the
directory of .repo files is given by self.conf.reposdir.
"""
# Read .repo files from directories specified by the reposdir option
# (typically /etc/yum/repos.d)
repo_config_age = self.conf.config_file_age
# Get the repos from the main yum.conf file
self.getReposFromConfigFile(self.conf.config_file_path, repo_config_age)
for reposdir in self.conf.reposdir:
# this check makes sure that our dirs exist properly.
# if they aren't in the installroot then don't prepend the installroot path
# if we don't do this then anaconda likes to not work.
if os.path.exists(self.conf.installroot+'/'+reposdir):
reposdir = self.conf.installroot + '/' + reposdir
reposdir = os.path.normpath(reposdir)
if os.path.isdir(reposdir):
for repofn in sorted(glob.glob('%s/*.repo' % reposdir)):
if not os.access(repofn, os.R_OK):
self.logger.warning(_("Skipping unreadable repository %s"), repr(repofn))
continue
thisrepo_age = os.stat(repofn)[8]
if thisrepo_age < repo_config_age:
thisrepo_age = repo_config_age
self.getReposFromConfigFile(repofn, repo_age=thisrepo_age)
def readRepoConfig(self, parser, section):
"""Parse an INI file section for a repository.
:param parser: :class:`ConfigParser` or similar object to read
INI file values from
:param section: INI file section to read
:return: :class:`yum.yumRepo.YumRepository` instance
"""
repo = yumRepo.YumRepository(section)
try:
repo.populate(parser, section, self.conf)
except ValueError, e:
msg = _('Repository %r: Error parsing config: %s' % (section,e))
raise Errors.ConfigError, msg
# Ensure that the repo name is set
if not repo.name:
repo.name = section
self.logger.error(_('Repository %r is missing name in configuration, '
'using id') % section)
repo.name = to_unicode(repo.name)
# Set attributes not from the config file
repo.old_base_cache_dir = getattr(self, '_old_cachedir', '')
repo.basecachedir = self.conf.cachedir
repo.yumvar.update(self.conf.yumvar)
repo._cashe = self._cashe
repo.cfg = parser
# Enable parallel downloading
repo._async = repo.async
# Allow caching local repos
if repo.keepcache and any(u.startswith('file:') for u in repo.baseurl):
repo.copy_local = True
return repo
def disablePlugins(self):
"""Disable yum plugins."""
self.plugins = plugins.DummyYumPlugins()
def doPluginSetup(self, optparser=None, plugin_types=None, searchpath=None,
confpath=None,disabled_plugins=None,enabled_plugins=None):
"""Initialise and enable yum plugins.
Note: _getConfig() will also initialise plugins if instructed
to. Only call this method directly if not calling _getConfig()
or calling doConfigSetup(init_plugins=False).
:param optparser: the :class:`OptionParser` instance to use
for this run
:param plugin_types: a sequence specifying the types of plugins to load.
This should be a sequence containing one or more of the
yum.plugins.TYPE_... constants. If None (the default), all plugins
will be loaded
:param searchpath: a list of directories to look in for plugins. A
default will be used if no value is specified
:param confpath: a list of directories to look in for plugin
configuration files. A default will be used if no value is
specified
:param disabled_plugins: a list of plugins to be disabled
:param enabled_plugins: a list plugins to be enabled
"""
if isinstance(self.plugins, plugins.YumPlugins):
raise RuntimeError(_("plugins already initialised"))
self.plugins = plugins.YumPlugins(self, searchpath, optparser,
plugin_types, confpath, disabled_plugins, enabled_plugins)
def doRpmDBSetup(self):
"""Deprecated. Set up the rpm database."""
warnings.warn(_('doRpmDBSetup() will go away in a future version of Yum.\n'),
Errors.YumFutureDeprecationWarning, stacklevel=2)
return self._getRpmDB()
def _getRpmDB(self):
"""sets up a holder object for important information from the rpmdb"""
if self._rpmdb is None:
rpmdb_st = time.time()
self.verbose_logger.log(logginglevels.DEBUG_4,
_('Reading Local RPMDB'))
self._rpmdb = rpmsack.RPMDBPackageSack(root=self.conf.installroot,
releasever=self.conf.yumvar['releasever'],
persistdir=self.conf.persistdir)
self.verbose_logger.debug('rpmdb time: %0.3f' % (time.time() - rpmdb_st))
return self._rpmdb
def closeRpmDB(self):
"""Closes down the instances of rpmdb that could be open."""
if self._rpmdb is not None:
self._rpmdb.ts = None
self._rpmdb.dropCachedData()
self._rpmdb = None
self._ts = None
self._tsInfo = None
self._up = None
self.comps = None
self.igroups = None
def _deleteTs(self):
del self._ts
self._ts = None
def doRepoSetup(self, thisrepo=None):
"""Deprecated. Set up the yum repositories.
:param thisrepo: the repository to set up. If None, all
repositories will be set up
:return: the set up repos
"""
warnings.warn(_('doRepoSetup() will go away in a future version of Yum.\n'),
Errors.YumFutureDeprecationWarning, stacklevel=2)
return self._getRepos(thisrepo, True)
def _getRepos(self, thisrepo=None, doSetup = False):
""" For each enabled repository set up the basics of the repository. """
if hasattr(self, 'prerepoconf'):
self.conf # touch the config class first
if (self.conf.installroot != '/' and
not hasattr(self, '_old_cachedir')):
# Try loading cache from outside...
ir = len(self.conf.installroot)
self._old_cachedir = self.conf.cachedir[ir:]
self.getReposFromConfig()
# For rhnplugin, and in theory other stuff, calling
# .getReposFromConfig() recurses back into this function but only once.
# This means that we have two points on the stack leaving the above call
# but only one of them can do the repos setup. BZ 678043.
if hasattr(self, 'prerepoconf'):
# Recursion
prerepoconf = self.prerepoconf
del self.prerepoconf
self.repos.setProgressBar(prerepoconf.progressbar,
prerepoconf.multi_progressbar)
self.repos.callback = prerepoconf.callback
self.repos.setFailureCallback(prerepoconf.failure_callback)
self.repos.setInterruptCallback(prerepoconf.interrupt_callback)
self.repos.confirm_func = prerepoconf.confirm_func
self.repos.gpg_import_func = prerepoconf.gpg_import_func
self.repos.gpgca_import_func = prerepoconf.gpgca_import_func
if prerepoconf.cachedir is not None:
self.repos.setCacheDir(prerepoconf.cachedir)
if prerepoconf.cache is not None:
self.repos.setCache(prerepoconf.cache)
if doSetup:
repo_st = time.time()
self._repos.doSetup(thisrepo)
self.verbose_logger.debug('repo time: %0.3f' % (time.time() - repo_st))
return self._repos
def _delRepos(self):
del self._repos
self._repos = RepoStorage(self)
def doSackSetup(self, archlist=None, thisrepo=None):
"""Deprecated. Populate the package sacks with information
from our repositories.
:param archlist: a list of the names of archs to include. If
None, all arches are set up
:param thisrepo: the repository to use. If None, all enabled
repositories are used
"""
warnings.warn(_('doSackSetup() will go away in a future version of Yum.\n'),
Errors.YumFutureDeprecationWarning, stacklevel=2)
return self._getSacks(archlist=archlist, thisrepo=thisrepo)
def _getSacks(self, archlist=None, thisrepo=None):
"""populates the package sacks for information from our repositories,
takes optional archlist for archs to include"""
# FIXME: Fist of death ... normally we'd do either:
#
# 1. use self._pkgSack is not None, and only init. once.
# 2. auto. correctly re-init each time a repo is added/removed
#
# ...we should probably just smeg it and do #2, but it's hard and will
# probably break something (but it'll "fix" excludes).
# #1 can't be done atm. because we did self._pkgSack and external
# tools now rely on being able to create an empty sack and then have it
# auto. re-init when they add some stuff. So we add a bit more "clever"
# and don't setup the pkgSack to not be None when it's empty. This means
# we skip excludes/includes/etc. ... but there's no packages, so
# hopefully that's ok.
if self._pkgSack is not None and thisrepo is None:
return self._pkgSack
if thisrepo is None:
repos = 'enabled'
else:
repos = self.repos.findRepos(thisrepo)
self.verbose_logger.debug(_('Setting up Package Sacks'))
sack_st = time.time()
if not archlist:
archlist = self.arch.archlist
archdict = {}
for arch in archlist:
archdict[arch] = 1
self.repos.getPackageSack().setCompatArchs(archdict)
self.repos.populateSack(which=repos)
if not self.repos.getPackageSack():
return self.repos.getPackageSack() # ha ha, see above
self._pkgSack = self.repos.getPackageSack()
self.excludePackages()
self._pkgSack.excludeArchs(archlist)
#FIXME - this could be faster, too.
if repos == 'enabled':
repos = self.repos.listEnabled()
for repo in repos:
self.includePackages(repo)
self.excludePackages(repo)
self.plugins.run('exclude')
self._pkgSack.buildIndexes()
# now go through and kill pkgs based on pkg.repo.cost()
self.costExcludePackages()
self.verbose_logger.debug('pkgsack time: %0.3f' % (time.time() - sack_st))
return self._pkgSack
def _delSacks(self):
"""reset the package sacks back to zero - making sure to nuke the ones
in the repo objects, too - where it matters"""
# nuke the top layer
self._pkgSack = None
for repo in self.repos.repos.values():
if hasattr(repo, '_resetSack'):
repo._resetSack()
else:
warnings.warn(_('repo object for repo %s lacks a _resetSack method\n') +
_('therefore this repo cannot be reset.\n'),
Errors.YumFutureDeprecationWarning, stacklevel=2)
def doUpdateSetup(self):
"""Deprecated. Set up the update object in the base class and populate the
updates, obsoletes, and other lists.
"""
warnings.warn(_('doUpdateSetup() will go away in a future version of Yum.\n'),
Errors.YumFutureDeprecationWarning, stacklevel=2)
return self._getUpdates()
def _getUpdates(self):
"""setups up the update object in the base class and fills out the
updates, obsoletes and others lists"""
if self._up:
return self._up
self.verbose_logger.debug(_('Building updates object'))
up_st = time.time()
self._up = rpmUtils.updates.Updates(self.rpmdb.simplePkgList(), self.pkgSack.simplePkgList())
if self.conf.debuglevel >= 7:
self._up.debug = 1
if hasattr(self, '_up_obs_hack'):
self._up.rawobsoletes = self._up_obs_hack.rawobsoletes
del self._up_obs_hack
elif self.conf.obsoletes:
obs_init = time.time()
# Note: newest=True here is semi-required for repos. with multiple
# versions. The problem is that if pkgA-2 _accidentally_ obsoletes
# pkgB-1, and we keep all versions, we want to release a pkgA-3
# that doesn't do the obsoletes ... and thus. not obsolete pkgB-1.
self._up.rawobsoletes = self.pkgSack.returnObsoletes(newest=True)
self.verbose_logger.debug('up:Obs Init time: %0.3f' % (time.time() - obs_init))
self._up.myarch = self.arch.canonarch
self._up._is_multilib = self.arch.multilib
self._up._archlist = self.arch.archlist
self._up._multilib_compat_arches = self.arch.compatarches
self._up.exactarch = self.conf.exactarch
self._up.exactarchlist = self.conf.exactarchlist
up_pr_st = time.time()
self._up.doUpdates()
self.verbose_logger.debug('up:simple updates time: %0.3f' % (time.time() - up_pr_st))
if self.conf.obsoletes:
obs_st = time.time()
self._up.doObsoletes()
self.verbose_logger.debug('up:obs time: %0.3f' % (time.time() - obs_st))
cond_up_st = time.time()
self._up.condenseUpdates()
self.verbose_logger.debug('up:condense time: %0.3f' % (time.time() - cond_up_st))
self.verbose_logger.debug('updates time: %0.3f' % (time.time() - up_st))
return self._up
def doGroupSetup(self):
"""Deprecated. Create and populate the groups object."""
warnings.warn(_('doGroupSetup() will go away in a future version of Yum.\n'),
Errors.YumFutureDeprecationWarning, stacklevel=2)
self.comps = None
return self._getGroups()
def _setGroups(self, val):
if val is None:
# if we unset the comps object, we need to undo which repos have
# been added to the group file as well
if self._repos:
# Used to do listGroupsEnabled(), which seems fine but requires
# calling .listEnalbed() ... which doesn't work on __del__ path
# if we haven't already called that (due to
# "prelistenabledrepos" plugins). So just blank it for
# all repos.
for repo in self._repos.sort():
repo.groups_added = False
self._comps = val
def _getGroups(self):
"""create the groups object that will store the comps metadata
finds the repos with groups, gets their comps data and merge it
into the group object"""
if self._comps:
return self._comps
group_st = time.time()
self.verbose_logger.log(logginglevels.DEBUG_4,
_('Getting group metadata'))
reposWithGroups = []
# Need to make sure the groups data is ready to read. Really we'd want
# to add groups to the mdpolicy list of the repo. but we don't atm.
self.pkgSack
for repo in self.repos.listGroupsEnabled():
if repo.groups_added: # already added the groups from this repo
reposWithGroups.append(repo)
continue
if not repo.ready():
raise Errors.RepoError("Repository '%s' not yet setup" % repo,
repo=repo)
try:
groupremote = repo.getGroupLocation()
except Errors.RepoMDError, e:
pass
else:
reposWithGroups.append(repo)
# now we know which repos actually have groups files.
overwrite = self.conf.overwrite_groups
self._comps = comps.Comps(overwrite_groups = overwrite)
if self.conf.group_command == 'objects':
# Add the ids for installed groups/envs as though sys is a repo.
# makes everything easier (comps.return_groups() etc. works)...
self._comps.compscount += 1
for gid in self.igroups.groups:
grp = comps.Group()
grp.name = grp.groupid = gid
grp._weak = True
self._comps.add_group(grp)
for evgid in self.igroups.environments:
env = comps.Environment()
env.name = env.environmentid = evgid
env._weak = True
self._comps.add_environment(env)
for repo in reposWithGroups:
if repo.groups_added: # already added the groups from this repo
continue
self.verbose_logger.log(logginglevels.DEBUG_4,
_('Adding group file from repository: %s'), repo)
groupfile = repo.getGroups()
if not groupfile:
msg = _('Failed to retrieve group file for repository: %s') % repo
self.logger.critical(msg)
continue
try:
self._comps.add(groupfile)
except (Errors.GroupsError,Errors.CompsException), e:
msg = _('Failed to add groups file for repository: %s - %s') % (repo, exception2msg(e))
self.logger.critical(msg)
else:
repo.groups_added = True
if self._comps.compscount == 0:
raise Errors.GroupsError, _('No Groups Available in any repository')
# Note that this means that grp.installed is not usable, when using
# groups as objects ... but that's GOOD.
if self.conf.group_command != 'objects':
self._comps.compile(self.rpmdb.simplePkgList())
self.verbose_logger.debug('group time: %0.3f' % (time.time() - group_st))
return self._comps
def _getTags(self):
""" create the tags object used to search/report from the pkgtags
metadata"""
tag_st = time.time()
self.verbose_logger.log(logginglevels.DEBUG_4,
_('Getting pkgtags metadata'))
if self._tags is None:
self._tags = yum.pkgtag_db.PackageTags()