/
yumpayload.py
1579 lines (1311 loc) · 57.8 KB
/
yumpayload.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
# yumpayload.py
# Yum/rpm software payload management.
#
# Copyright (C) 2012 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): David Lehman <dlehman@redhat.com>
# Chris Lumens <clumens@redhat.com>
#
"""
TODO
- document all methods
- YumPayload
- write test cases
- more logging in key methods
- handling of proxy needs cleanup
- passed to anaconda as --proxy, --proxyUsername, and
--proxyPassword
- drop the use of a file for proxy and ftp auth info
- specified via KS as a URL
"""
import ConfigParser
import os
import shutil
import sys
import time
from pyanaconda.iutil import execReadlines
from pyanaconda.simpleconfig import simple_replace
from functools import wraps
import logging
log = logging.getLogger("packaging")
try:
import rpm
except ImportError:
log.error("import of rpm failed")
rpm = None
try:
import yum
# This is a bit of a hack to short circuit yum's internal logging
# handler setup. We already set one up so we don't need it to run.
# yum may give us an API to fiddle this at a later time.
yum.logginglevels._added_handlers = True
from yum.Errors import RepoError, RepoMDError, GroupsError
except ImportError:
log.error("import of yum failed")
yum = None
from pyanaconda.constants import BASE_REPO_NAME, DRACUT_ISODIR, INSTALL_TREE, ISO_DIR, MOUNT_DIR, \
LOGLVL_LOCK, IPMI_ABORTED
from pyanaconda.flags import flags
from pyanaconda import iutil
from pyanaconda.iutil import ProxyString, ProxyStringError, xprogressive_delay
from pyanaconda.i18n import _
from pyanaconda.nm import nm_is_connected
from pyanaconda.product import isFinal
from blivet.size import Size
import blivet.util
import blivet.arch
from pyanaconda.errors import ERROR_RAISE, errorHandler, CmdlineError
from pyanaconda.packaging import DependencyError, MetadataError, NoNetworkError, NoSuchGroup, \
NoSuchPackage, PackagePayload, PayloadError, PayloadInstallError, \
PayloadSetupError
from pyanaconda.progress import progressQ
from pyanaconda.localization import langcode_matches_locale
from pykickstart.constants import GROUP_ALL, GROUP_DEFAULT, KS_MISSING_IGNORE
YUM_PLUGINS = ["fastestmirror", "langpacks"]
YUM_REPOS_DIR = "/etc/yum.repos.d/"
BASE_REPO_NAMES = [BASE_REPO_NAME] + PackagePayload.DEFAULT_REPOS
MAX_METADATA_DOWNLOAD_RETRIES = 10
import inspect
import threading
_private_yum_lock = threading.RLock()
class YumLock(object):
def __enter__(self):
if isFinal:
_private_yum_lock.acquire()
return _private_yum_lock
frame = inspect.stack()[2]
threadName = threading.currentThread().name
log.log(LOGLVL_LOCK, "about to acquire _yum_lock for %s at %s:%s (%s)", threadName, frame[1], frame[2], frame[3])
_private_yum_lock.acquire()
log.log(LOGLVL_LOCK, "have _yum_lock for %s", threadName)
return _private_yum_lock
def __exit__(self, exc_type, exc_val, exc_tb):
_private_yum_lock.release()
if not isFinal:
log.log(LOGLVL_LOCK, "gave up _yum_lock for %s", threading.currentThread().name)
def refresh_base_repo(cond_fn=None):
"""
Function returning decorator for methods that invalidate base repo.
After the method has been run the base repo will be refreshed
:param cond_fn: condition function telling if base repo should be
invalidated or not (HAS TO TAKE THE SAME ARGUMENTS AS THE
DECORATED FUNCTION)
While the method runs the base_repo is set to None.
"""
def decorator(method):
"""
Decorator for methods that invalidate base repo cache.
:param method: decorated method of the YumPayload class
"""
@wraps(method)
def inner_method(yum_payload, *args, **kwargs):
if cond_fn is None or cond_fn(yum_payload, *args, **kwargs):
with yum_payload._base_repo_lock:
yum_payload._base_repo = None
ret = method(yum_payload, *args, **kwargs)
if cond_fn is None or cond_fn(yum_payload, *args, **kwargs):
yum_payload._refreshBaseRepo()
return ret
return inner_method
return decorator
_yum_lock = YumLock()
_yum_cache_dir = "/tmp/yum.cache"
_yum_installer_langpack_conf = "/tmp/yum.pluginconf.d/langpacks.conf"
_yum_target_langpack_conf = "/etc/yum/pluginconf.d/langpacks.conf"
class YumPayload(PackagePayload):
""" A YumPayload installs packages onto the target system using yum.
User-defined (aka: addon) repos exist both in ksdata and in yum. They
are the only repos in ksdata.repo. The repos we find in the yum config
only exist in yum. Lastly, the base repo exists in yum and in
ksdata.method.
"""
def __init__(self, data):
if rpm is None or yum is None:
raise PayloadError("unsupported payload type")
PackagePayload.__init__(self, data)
self._root_dir = "/tmp/yum.root"
self._repos_dir = "/etc/yum.repos.d,/etc/anaconda.repos.d,/tmp/updates/anaconda.repos.d,/tmp/product/anaconda.repos.d"
self._yum = None
self._setup = False
# base repo caching
self._base_repo = None
self._base_repo_lock = threading.RLock()
self.reset()
def reset(self, root=None, releasever=None):
""" Reset this instance to its initial (unconfigured) state. """
super(YumPayload, self).reset()
# This value comes from a default install of the x86_64 Fedora 18. It
# is meant as a best first guess only. Once package metadata is
# available we can use that as a better value.
self._space_required = Size("3000 MB")
self._groups = None
self._packages = []
self._resetYum(root=root, releasever=releasever)
def setup(self, storage, instClass):
super(YumPayload, self).setup(storage, instClass)
self._writeYumConfig()
self._setup = True
def unsetup(self):
super(YumPayload, self).unsetup()
self._setup = False
def _resetYum(self, root=None, keep_cache=False, releasever=None):
""" Delete and recreate the payload's YumBase instance.
Setup _yum.preconf -- DO NOT TOUCH IT OUTSIDE THIS METHOD
NOTE: This is enforced by tests/pylint/preconf.py. If the name
of this method changes, change it there too.
"""
if root is None:
root = self._root_dir
with _yum_lock:
if self._yum:
if not keep_cache:
for repo in self._yum.repos.listEnabled():
if repo.name == BASE_REPO_NAME and \
os.path.isdir(repo.cachedir):
shutil.rmtree(repo.cachedir)
del self._yum
self._writeYumConfig()
self._yum = yum.YumBase()
self._yum.use_txmbr_in_callback = True
# Set some configuration parameters that don't get set through a config
# file. yum will know what to do with these.
# Enable all types of yum plugins. We're somewhat careful about what
# plugins we put in the environment.
self._yum.preconf.plugin_types = yum.plugins.ALL_TYPES
self._yum.preconf.enabled_plugins = YUM_PLUGINS
self._yum.preconf.fn = "/tmp/anaconda-yum.conf"
self._yum.preconf.root = root
if releasever is None:
self._yum.preconf.releasever = self._getReleaseVersion(None)
else:
self._yum.preconf.releasever = releasever
self.txID = None
def _writeLangpacksConfig(self):
langs = [self.data.lang.lang] + self.data.lang.addsupport
log.debug("configuring langpacks for %s", langs)
iutil.mkdirChain(os.path.dirname(_yum_installer_langpack_conf))
shutil.copy2(_yum_target_langpack_conf,
_yum_installer_langpack_conf)
try:
# langpacks.conf is an INI style config file, read it and
# Add or change the langpack_locales entry without changing anything else.
keys=[("langpack_locales", "langpack_locales="+", ".join(langs))]
simple_replace(_yum_installer_langpack_conf, keys)
except IOError as msg:
log.error ("Error setting langpack_locales: %s", msg)
def _copyLangpacksConfigToTarget(self):
shutil.copy2(_yum_installer_langpack_conf,
iutil.getSysroot()+_yum_target_langpack_conf)
def _writeYumConfig(self):
""" Write out anaconda's main yum configuration file. """
buf = """
[main]
cachedir=%s
keepcache=0
logfile=/tmp/yum.log
metadata_expire=never
pluginpath=/usr/lib/yum-plugins,/tmp/updates/yum-plugins
pluginconfpath=%s,/etc/yum/pluginconf.d,/tmp/updates/pluginconf.d
plugins=1
debuglevel=3
errorlevel=6
reposdir=%s
""" % (_yum_cache_dir, os.path.dirname(_yum_installer_langpack_conf),
self._repos_dir)
if flags.noverifyssl:
buf += "sslverify=0\n"
if self.data.packages.multiLib:
buf += "multilib_policy=all\n"
if hasattr(self.data.method, "proxy") and self.data.method.proxy:
try:
proxy = ProxyString(self.data.method.proxy)
buf += "proxy=%s\n" % (proxy.noauth_url,)
if proxy.username:
buf += "proxy_username=%s\n" % (proxy.username,)
if proxy.password:
buf += "proxy_password=%s\n" % (proxy.password,)
except ProxyStringError as e:
log.error("Failed to parse proxy for _writeYumConfig %s: %s",
self.data.method.proxy, e)
open("/tmp/anaconda-yum.conf", "w").write(buf)
# YUMFIXME: yum should allow a cache dir outside of the installroot
def _yumCacheDirHack(self):
# This is what it takes to get yum to use a cache dir outside the
# install root. We do this so we don't have to re-gather repo meta-
# data after we change the install root to sysroot, which can only
# happen after we've enabled the new storage configuration.
with _yum_lock:
if not self._yum.conf.cachedir.startswith(self._yum.conf.installroot):
return
root = self._yum.conf.installroot
self._yum.conf.cachedir = self._yum.conf.cachedir[len(root):]
def _writeYumRepo(self, repo, repo_path):
""" Write a repo object to a yum repo.conf file
:param repo: Yum repository object
:param string repo_path: Path to write the repo to
:raises: PayloadSetupError if the repo doesn't have a url
"""
with open(repo_path, "w") as f:
f.write("[%s]\n" % repo.id)
f.write("name=%s\n" % repo.id)
if self.isRepoEnabled(repo.id):
f.write("enabled=1\n")
else:
f.write("enabled=0\n")
if repo.mirrorlist:
f.write("mirrorlist=%s\n" % repo.mirrorlist)
elif repo.baseurl:
f.write("baseurl=%s\n" % repo.baseurl[0])
else:
f.close()
os.unlink(repo_path)
raise PayloadSetupError("repo %s has no baseurl, mirrorlist or metalink", repo.id)
# kickstart repo modifiers
ks_repo = self.getAddOnRepo(repo.id)
if not ks_repo and not repo.sslverify:
f.write("sslverify=0\n")
if not ks_repo:
return
if ks_repo.noverifyssl:
f.write("sslverify=0\n")
if ks_repo.proxy:
try:
proxy = ProxyString(ks_repo.proxy)
f.write("proxy=%s\n" % (proxy.noauth_url,))
if proxy.username:
f.write("proxy_username=%s\n" % (proxy.username,))
if proxy.password:
f.write("proxy_password=%s\n" % (proxy.password,))
except ProxyStringError as e:
log.error("Failed to parse proxy for _writeYumRepo %s: %s",
ks_repo.proxy, e)
if ks_repo.cost:
f.write("cost=%d\n" % ks_repo.cost)
if ks_repo.includepkgs:
f.write("includepkgs=%s\n"
% ",".join(ks_repo.includepkgs))
if ks_repo.excludepkgs:
f.write("exclude=%s\n"
% ",".join(ks_repo.excludepkgs))
if ks_repo.ignoregroups:
f.write("enablegroups=0\n")
def _writeInstallConfig(self):
""" Write out the yum config that will be used to install packages.
Write out repo config files for all enabled repos, then
create a new YumBase instance with the new filesystem tree as its
install root.
This needs to be called from inside a yum_lock
"""
self._repos_dir = "/tmp/yum.repos.d"
if not os.path.isdir(self._repos_dir):
os.mkdir(self._repos_dir)
for repo in self._yum.repos.listEnabled():
cfg_path = "%s/%s.repo" % (self._repos_dir, repo.id)
log.debug("writing repository file %s for repository %s", cfg_path, repo.id)
try:
self._writeYumRepo(repo, cfg_path)
except PayloadSetupError as e:
log.error(e)
releasever = self._yum.conf.yumvar['releasever']
self._writeYumConfig()
self._writeLangpacksConfig()
log.debug("setting releasever to previous value of %s", releasever)
self._resetYum(root=iutil.getSysroot(), keep_cache=True, releasever=releasever)
self._yumCacheDirHack()
self.gatherRepoMetadata()
# trigger setup of self._yum.config
log.debug("installation yum config repos: %s",
",".join(r.id for r in self._yum.repos.listEnabled()))
# YUMFIXME: there should be a way to reset package sacks without all this
# knowledge of the yum internals or, better yet, some convenience
# functions for multi-threaded applications
def release(self):
from yum.packageSack import MetaSack
with _yum_lock:
log.debug("deleting package sacks")
if hasattr(self._yum, "_pkgSack"):
self._yum._pkgSack = None
self._yum.repos.pkgSack = MetaSack()
for repo in self._yum.repos.repos.values():
repo._sack = None
def deleteYumTS(self):
with _yum_lock:
log.debug("deleting yum transaction info")
self._yum.closeRpmDB()
del self._yum.tsInfo
del self._yum.ts
def preStorage(self):
self.release()
with _yum_lock:
self._yum.close()
###
### METHODS FOR WORKING WITH REPOSITORIES
###
@property
def repos(self):
if not self._setup:
return []
_repos = []
with _yum_lock:
_repos = self._yum.repos.repos.keys()
return _repos
@property
def baseRepo(self):
""" Return the current base repo id
:returns: repo id or None
Methods that change (or could change) the base_repo
need to be decorated with @refresh_base_repo
"""
return self._base_repo
def _refreshBaseRepo(self):
""" Examine the enabled repos and update _base_repo
"""
with _yum_lock:
for repo_name in BASE_REPO_NAMES:
if repo_name in self.repos and \
self._yum.repos.getRepo(repo_name).enabled:
with self._base_repo_lock:
self._base_repo = repo_name
break
else:
# didn't find any base repo set and enabled
with self._base_repo_lock:
log.debug("No base_repo found in %s", BASE_REPO_NAMES)
self._base_repo = None
@property
def mirrorEnabled(self):
with _yum_lock:
# yum initializes with plugins disabled, and when plugins are disabled
# _yum.plugins is a DummyYumPlugins object, which has no useful attributes.
if hasattr(self._yum.plugins, "enabledPlugins"):
return "fastestmirror" in self._yum.plugins.enabledPlugins
else:
return False
def getRepo(self, repo_id):
""" Return the yum repo object. """
with _yum_lock:
repo = self._yum.repos.getRepo(repo_id)
return repo
def isRepoEnabled(self, repo_id):
""" Return True if repo is enabled. """
try:
return self.getRepo(repo_id).enabled
except RepoError:
return super(YumPayload, self).isRepoEnabled(repo_id)
@refresh_base_repo()
def updateBaseRepo(self, fallback=True, root=None, checkmount=True):
""" Update the base repo based on self.data.method.
- Tear down any previous base repo devices, symlinks, &c.
- Reset the YumBase instance.
- Try to convert the new method to a base repo.
- If that fails, we'll use whatever repos yum finds in the config.
- Set up addon repos.
- Filter out repos that don't make sense to have around.
- Get metadata for all enabled repos, disabling those for which the
retrieval fails.
"""
log.info("configuring base repo")
url, mirrorlist, sslverify = self._setupInstallDevice(self.storage, checkmount)
releasever = None
method = self.data.method
if method.method:
try:
releasever = self._getReleaseVersion(url)
log.debug("releasever from %s is %s", url, releasever)
except ConfigParser.MissingSectionHeaderError as e:
log.error("couldn't set releasever from base repo (%s): %s",
method.method, e)
# start with a fresh YumBase instance & tear down old install device
self.reset(root=root, releasever=releasever)
self._yumCacheDirHack()
# This needs to be done again, reset tore it down.
url, mirrorlist, sslverify = self._setupInstallDevice(self.storage, checkmount)
# If this is a kickstart install and no method has been set up, or
# askmethod was given on the command line, we don't want to do
# anything. Just disable all repos and return. This should avoid
# metadata fetching.
if (not method.method and flags.automatedInstall) or \
flags.askmethod:
with _yum_lock:
for repo in self._yum.repos.repos.values():
self.disableRepo(repo.id)
return
# see if we can get a usable base repo from self.data.method
if method.method:
try:
if releasever is None:
raise PayloadSetupError("base repo is unusable")
if hasattr(method, "proxy"):
proxyurl = method.proxy
else:
proxyurl = None
self._addYumRepo(BASE_REPO_NAME, url, mirrorlist=mirrorlist,
proxyurl=proxyurl, sslverify=sslverify)
except (MetadataError, PayloadError) as e:
log.error("base repo (%s/%s) not valid -- removing it",
method.method, url)
self._removeYumRepo(BASE_REPO_NAME)
if not fallback:
with _yum_lock:
for repo in self._yum.repos.repos.values():
if repo.enabled:
self.disableRepo(repo.id)
return
# this preserves the method details while disabling it
method.method = None
self.install_device = None
with _yum_lock:
if BASE_REPO_NAME not in self._yum.repos.repos.keys():
log.info("using default repos from local yum configuration")
if self._yum.conf.yumvar['releasever'] == "rawhide" and \
"rawhide" in self.repos:
self.enableRepo("rawhide")
# set up addon repos
# FIXME: driverdisk support
for repo in self.data.repo.dataList():
if not repo.enabled:
continue
try:
self._configureAddOnRepo(repo)
except NoNetworkError as e:
log.error("repo %s needs an active network connection", repo.name)
self.disableRepo(repo.name)
except PayloadError as e:
log.error("repo %s setup failed: %s", repo.name, e)
self.disableRepo(repo.name)
# now disable and/or remove any repos that don't make sense
with _yum_lock:
for repo in self._yum.repos.repos.values():
# Rules for which repos to enable/disable/remove
#
# - always remove
# - source, debuginfo
# - disable if isFinal
# - rawhide, development
# - disable all other built-in repos if rawhide is enabled
# - remove any repo when not isFinal and repo not enabled
# - if a base repo is defined, disable any repo not defined by
# the user that is not the base repo
#
# FIXME: updates needs special handling
if repo.id in self.addOns:
continue
if "-source" in repo.id or "-debuginfo" in repo.id:
self._removeYumRepo(repo.id)
elif isFinal and ("rawhide" in repo.id or "development" in repo.id):
# XXX the "development" part seems a bit heavy handed
self._removeYumRepo(repo.id)
elif self._yum.conf.yumvar['releasever'] == "rawhide" and \
"rawhide" in self.repos and \
self._yum.repos.getRepo("rawhide").enabled and \
repo.id not in (BASE_REPO_NAME, "rawhide"):
self.disableRepo(repo.id)
elif method.method and \
repo.id != BASE_REPO_NAME and \
repo.id not in (r.name for r in self.data.repo.dataList()):
# if a method/repo was given, disable all default repos
self.disableRepo(repo.id)
@refresh_base_repo()
def gatherRepoMetadata(self):
# now go through and get metadata for all enabled repos
log.info("gathering repo metadata")
for repo_id in self.repos:
with _yum_lock:
repo = self._yum.repos.getRepo(repo_id)
if repo.enabled:
# retry metadata downloads with a progressively longer pause,
# so that unattended installations on unreliable networks have
# a higher chance of finishing successfully
xdelay = xprogressive_delay()
for retry_count in xrange(0, MAX_METADATA_DOWNLOAD_RETRIES + 1):
if retry_count > 0:
# introduce a retry delay
time.sleep(next(xdelay))
try:
log.info("gathering repo metadata for %s", repo_id)
self._getRepoMetadata(repo)
log.info("gathered repo metadata for %s", repo_id)
break
except PayloadError as e:
log.error("failed to grab repo metadata for %s: %s", repo_id, e)
if retry_count < MAX_METADATA_DOWNLOAD_RETRIES:
# retry
log.info("retrying metadata download for repo %s, retrying (%d/%d)",
repo_id, retry_count + 1, MAX_METADATA_DOWNLOAD_RETRIES)
else:
# run out of retries
log.error("metadata download for repo %s failed after %d retries",
repo_id, retry_count)
self.disableRepo(repo_id)
else:
log.info("skipping disabled repo %s", repo_id)
# Make sure environmentAddon information is current
self._refreshEnvironmentAddons()
log.info("metadata retrieval complete")
@property
def ISOImage(self):
if not self.data.method.method == "harddrive":
return None
# This could either be mounted to INSTALL_TREE or on
# DRACUT_ISODIR if dracut did the mount.
dev = blivet.util.get_mount_device(INSTALL_TREE)
if dev:
return dev[len(ISO_DIR)+1:]
dev = blivet.util.get_mount_device(DRACUT_ISODIR)
if dev:
return dev[len(DRACUT_ISODIR)+1:]
return None
@refresh_base_repo()
def _configureAddOnRepo(self, repo):
""" Configure a single ksdata repo. """
url = repo.baseurl
if url and url.startswith("nfs://"):
# Let the assignment throw ValueError for bad NFS urls from kickstart
(server, path) = url.strip("nfs://").split(":", 1)
mountpoint = "%s/%s.nfs" % (MOUNT_DIR, repo.name)
self._setupNFS(mountpoint, server, path, None)
url = "file://" + mountpoint
if self._repoNeedsNetwork(repo) and not nm_is_connected():
raise NoNetworkError
if repo.proxy:
proxy = repo.proxy
elif hasattr(self.data.method, "proxy"):
proxy = self.data.method.proxy
else:
proxy = None
sslverify = not (flags.noverifyssl or repo.noverifyssl)
# this repo is already in ksdata, so we only add it to yum here
self._addYumRepo(repo.name, url, repo.mirrorlist, cost=repo.cost,
exclude=repo.excludepkgs, includepkgs=repo.includepkgs,
proxyurl=proxy, sslverify=sslverify)
addons = self._getAddons(url or repo.mirrorlist,
proxy,
sslverify)
# Addons are added to the kickstart, but are disabled by default
for addon in addons:
# Does this repo already exist? If so, it was already added and may have
# been edited by the user so skip adding it again.
if self.getAddOnRepo(addon[1]):
log.debug("Skipping %s, already exists.", addon[1])
continue
log.info("Adding addon repo %s", addon[1])
ks_repo = self.data.RepoData(name=addon[1],
baseurl=addon[2],
proxy=repo.proxy,
enabled=False)
self.data.repo.dataList().append(ks_repo)
def _getAddons(self, baseurl, proxy_url, sslverify):
""" Check the baseurl or mirrorlist for a repository, see if it has any
valid addon repos and if so, return a list of (repo name, repo URL).
:param baseurl: url of the repo
:type baseurl: string
:param proxy_url: Full URL of optional proxy or ""
:type proxy_url: string
:param sslverify: True if SSL certificate should be varified
:type sslverify: bool
:returns: list of tuples of addons (id, name, url)
:rtype: list of tuples
"""
retval = []
# If there's no .treeinfo for this repo, don't bother looking for addons.
treeinfo = self._getTreeInfo(baseurl, proxy_url, sslverify)
if not treeinfo:
return retval
# We need to know which variant is being installed so we know what addons
# are valid options.
try:
c = ConfigParser.ConfigParser()
ConfigParser.ConfigParser.read(c, treeinfo)
variant = c.get("general", "variant")
except ConfigParser.Error:
return retval
section = "variant-%s" % variant
if c.has_section(section) and c.has_option(section, "addons"):
validAddons = c.get(section, "addons").split(",")
else:
return retval
log.debug("Addons found: %s", validAddons)
for addon in validAddons:
addonSection = "addon-%s" % addon
if not c.has_section(addonSection) or not c.has_option(addonSection, "repository"):
continue
url = "%s/%s" % (baseurl, c.get(addonSection, "repository"))
retval.append((addon, c.get(addonSection, "name"), url))
return retval
def _getRepoMetadata(self, yumrepo):
""" Retrieve repo metadata if we don't already have it. """
# And try to grab its metadata. We do this here so it can be done
# on a per-repo basis, so we can then get some finer grained error
# handling and recovery.
log.debug("getting repo metadata for %s", yumrepo.id)
with _yum_lock:
try:
yumrepo.getPrimaryXML()
except RepoError as e:
raise MetadataError(e.value)
# Not getting group info is bad, but doesn't seem like a fatal error.
# At the worst, it just means the groups won't be displayed in the UI
# which isn't too bad, because you may be doing a kickstart install and
# picking packages instead.
log.debug("getting group info for %s", yumrepo.id)
try:
yumrepo.getGroups()
except RepoMDError:
log.error("failed to get groups for repo %s", yumrepo.id)
def _replaceVars(self, url):
""" Replace url variables with their values
:param url: url string to do replacement on
:type url: string
:returns: string with variables substituted
:rtype: string or None
Currently supports $releasever and $basearch
"""
if not url:
return url
with _yum_lock:
url = url.replace("$releasever", self._yum.conf.yumvar['releasever'])
url = url.replace("$basearch", blivet.arch.getArch())
return url
def _addYumRepo(self, name, baseurl, mirrorlist=None, proxyurl=None, **kwargs):
""" Add a yum repo to the YumBase instance. """
needsAdding = True
# First, delete any pre-existing repo with the same name.
# First, check for any pre-existing repo with the same name.
with _yum_lock:
if name in self._yum.repos.repos:
if not baseurl and not mirrorlist:
# This is a repo we already have a config file in /etc/anaconda.repos.d,
# so we just need to enable it here. See the kickstart docs for the repo
# command.
self.enableRepo(name)
obj = self._yum.repos.repos[name]
needsAdding = False
else:
self._yum.repos.delete(name)
if proxyurl and needsAdding:
try:
proxy = ProxyString(proxyurl)
kwargs["proxy"] = proxy.noauth_url
if proxy.username:
kwargs["proxy_username"] = proxy.username
if proxy.password:
kwargs["proxy_password"] = proxy.password
except ProxyStringError as e:
log.error("Failed to parse proxy for _addYumRepo %s: %s",
proxyurl, e)
if baseurl:
baseurl = self._replaceVars(baseurl)
if mirrorlist:
mirrorlist = self._replaceVars(mirrorlist)
log.info("adding yum repo, name: %s, baseurl: %s, mirrorlist: %s",
name, baseurl, mirrorlist)
with _yum_lock:
if needsAdding:
# Then add it to yum's internal structures.
obj = self._yum.add_enable_repo(name,
baseurl=[baseurl],
mirrorlist=mirrorlist,
**kwargs)
# this will trigger retrieval of repomd.xml, which is small and yet
# gives us some assurance that the repo config is sane
# YUMFIXME: yum's instant policy doesn't work as advertised
obj.mdpolicy = "meh"
try:
obj.repoXML
except RepoError as e:
raise MetadataError(e.value)
# Adding a new repo means the cached packages and groups lists
# are out of date. Clear them out now so the next reference to
# either will cause it to be regenerated.
self._groups = None
self._packages = []
@refresh_base_repo(lambda s, r_id: r_id in BASE_REPO_NAMES)
def addRepo(self, newrepo):
""" Add a ksdata repo. """
log.debug("adding new repo %s", newrepo.name)
self._addYumRepo(newrepo.name, newrepo.baseurl, newrepo.mirrorlist, newrepo.proxy) # FIXME: handle MetadataError
super(YumPayload, self).addRepo(newrepo)
def _removeYumRepo(self, repo_id):
if repo_id in self.repos:
with _yum_lock:
self._yum.repos.delete(repo_id)
self._groups = None
self._packages = []
@refresh_base_repo(lambda s, r_id: r_id in BASE_REPO_NAMES)
def removeRepo(self, repo_id):
""" Remove a repo as specified by id. """
log.debug("removing repo %s", repo_id)
# if this is an NFS repo, we'll want to unmount the NFS mount after
# removing the repo
mountpoint = None
with _yum_lock:
yum_repo = self._yum.repos.getRepo(repo_id)
ks_repo = self.getAddOnRepo(repo_id)
if yum_repo and ks_repo and ks_repo.baseurl.startswith("nfs:"):
mountpoint = yum_repo.baseurl[0][7:] # strip leading "file://"
self._removeYumRepo(repo_id)
super(YumPayload, self).removeRepo(repo_id)
if mountpoint and os.path.ismount(mountpoint):
try:
blivet.util.umount(mountpoint)
except SystemError as e:
log.error("failed to unmount nfs repo %s: %s", mountpoint, e)
@refresh_base_repo(lambda s, r_id: r_id in BASE_REPO_NAMES)
def enableRepo(self, repo_id):
""" Enable a repo as specified by id. """
log.debug("enabling repo %s", repo_id)
if repo_id in self.repos:
with _yum_lock:
self._yum.repos.enableRepo(repo_id)
super(YumPayload, self).enableRepo(repo_id)
@refresh_base_repo(lambda s, r_id: r_id in BASE_REPO_NAMES)
def disableRepo(self, repo_id):
""" Disable a repo as specified by id. """
log.debug("disabling repo %s", repo_id)
if repo_id in self.repos:
with _yum_lock:
self._yum.repos.disableRepo(repo_id)
self._groups = None
self._packages = []
super(YumPayload, self).disableRepo(repo_id)
###
### METHODS FOR WORKING WITH ENVIRONMENTS
###
@property
def environments(self):
""" List of environment ids. """
environments = []
yum_groups = self._yumGroups
if yum_groups:
with _yum_lock:
environments = [i.environmentid for i in yum_groups.get_environments()]
return environments
def environmentSelected(self, environmentid):
groups = self._yumGroups
if not groups:
return False
with _yum_lock:
if not groups.has_environment(environmentid):
raise NoSuchGroup(environmentid)
environment = groups.return_environment(environmentid)
for group in environment.groups:
if not self.groupSelected(group):
return False
return True
def environmentHasOption(self, environmentid, grpid):
groups = self._yumGroups
if not groups:
return False
with _yum_lock:
if not groups.has_environment(environmentid):
raise NoSuchGroup(environmentid)
environment = groups.return_environment(environmentid)
if grpid in environment.options:
return True
return False
def environmentOptionIsDefault(self, environmentid, grpid):
groups = self._yumGroups
if not groups:
return False
with _yum_lock:
if not groups.has_environment(environmentid):
raise NoSuchGroup(environmentid)
environment = groups.return_environment(environmentid)
if grpid in environment.defaultoptions:
return True
return False
def environmentDescription(self, environmentid):
""" Return name/description tuple for the environment specified by id. """
groups = self._yumGroups
if not groups:
return (environmentid, environmentid)