/
yumRepo.py
2227 lines (1887 loc) · 85.6 KB
/
yumRepo.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
# Copyright 2007 Red Hat
import os
import re
import time
import types
import urlparse
urlparse.uses_fragment.append("media")
import urllib
import Errors
from urlgrabber.grabber import URLGrabber
from urlgrabber.grabber import default_grabber
from urlgrabber.progress import format_number
import urlgrabber.mirror
from urlgrabber.grabber import URLGrabError
import repoMDObject
import packageSack
from repos import Repository
import parser
import sqlitecachec
import sqlitesack
from yum import config
from yum import misc
from yum import comps
from yum import _
from constants import *
import metalink
import logging
import logginglevels
import warnings
import glob
import shutil
import stat
import errno
import tempfile
# This is unused now, probably nothing uses it but it was global/public.
skip_old_DBMD_check = False
try:
import xattr
if not hasattr(xattr, 'get') or not hasattr(xattr, 'set'):
xattr = None # This is a "newer" API.
except ImportError:
xattr = None
# The problem we are trying to solve here is that:
#
# 1. We rarely want to be downloading MD/pkgs/etc.
# 2. We want to check those files are valid (match checksums) when we do
# download them.
# 3. We _really_ don't want to checksum all the files every time we
# run (100s of MBs).
# 4. We can continue to download files from bad mirrors, or retry files due to
# C-c etc.
#
# ...we used to solve this by just checking the file size, and assuming the
# files had been downloaded and checksumed as correct if that matched. But that
# was error prone on bad mirrors, so now we store the checksum in an
# xattr ... this does mean that if you can't store xattrs (Eg. NFS) you will
# rechecksum everything constantly.
def _xattr_get_chksum(filename, chktype):
if not xattr:
return None
try:
ret = xattr.get(filename, 'user.yum.checksum.' + chktype)
except: # Documented to be "EnvironmentError", but make sure
return None
return ret
def _xattr_set_chksum(filename, chktype, chksum):
if not xattr:
return None
try:
xattr.set(filename, 'user.yum.checksum.' + chktype, chksum)
except:
return False # Data too long. = IOError ... ignore everything.
return True
warnings.simplefilter("ignore", Errors.YumFutureDeprecationWarning)
logger = logging.getLogger("yum.Repos")
verbose_logger = logging.getLogger("yum.verbose.Repos")
class YumPackageSack(packageSack.PackageSack):
"""imports/handles package objects from an mdcache dict object"""
def __init__(self, packageClass):
packageSack.PackageSack.__init__(self)
self.pc = packageClass
self.added = {}
def __del__(self):
try:
self.close()
except Errors.RepoError, e:
verbose_logger.debug("Exception %s %s in %s ignored" % (repr(e), str(e), self.__del__))
def close(self):
self.added = {}
def addDict(self, repo, datatype, dataobj, callback=None):
if repo in self.added:
if datatype in self.added[repo]:
return
total = len(dataobj)
if datatype == 'metadata':
current = 0
for pkgid in dataobj:
current += 1
if callback: callback.progressbar(current, total, repo)
pkgdict = dataobj[pkgid]
po = self.pc(repo, pkgdict)
po.id = pkgid
self._addToDictAsList(self.pkgsByID, pkgid, po)
self.addPackage(po)
if repo not in self.added:
self.added[repo] = []
self.added[repo].append('metadata')
# indexes will need to be rebuilt
self.indexesBuilt = 0
elif datatype in ['filelists', 'otherdata']:
if repo in self.added:
if 'metadata' not in self.added[repo]:
raise Errors.RepoError('%s md for %s imported before primary' \
% (datatype, repo.ui_id),
repo=self)
current = 0
for pkgid in dataobj:
current += 1
if callback: callback.progressbar(current, total, repo)
pkgdict = dataobj[pkgid]
if pkgid in self.pkgsByID:
for po in self.pkgsByID[pkgid]:
po.importFromDict(pkgdict)
self.added[repo].append(datatype)
# indexes will need to be rebuilt
self.indexesBuilt = 0
else:
# umm, wtf?
pass
def _retrieve_async(self, repo, data):
""" Just schedule the metadata downloads """
for item in data:
if item in self.added.get(repo, []):
continue
if item == 'metadata':
mydbtype = 'primary_db'
elif item == 'filelists':
mydbtype = 'filelists_db'
elif item == 'otherdata':
mydbtype = 'other_db'
else:
continue
if self._check_db_version(repo, mydbtype):
if not self._check_uncompressed_db_gen(repo, mydbtype):
# NOTE: No failfunc.
repo._retrieveMD(mydbtype, async=True, failfunc=None)
def populate(self, repo, mdtype='metadata', callback=None, cacheonly=0):
if mdtype == 'all':
data = ['metadata', 'filelists', 'otherdata']
else:
data = [ mdtype ]
if not hasattr(repo, 'cacheHandler'):
repo.cacheHandler = sqlitecachec.RepodataParserSqlite(
storedir=repo.cachedir,
repoid=repo.id,
callback=callback,
)
for item in data:
if repo in self.added:
if item in self.added[repo]:
continue
if item == 'metadata':
mydbtype = 'primary_db'
mymdtype = 'primary'
repo_get_function = repo.getPrimaryXML
repo_cache_function = repo.cacheHandler.getPrimary
elif item == 'filelists':
mydbtype = 'filelists_db'
mymdtype = 'filelists'
repo_get_function = repo.getFileListsXML
repo_cache_function = repo.cacheHandler.getFilelists
elif item == 'otherdata':
mydbtype = 'other_db'
mymdtype = 'other'
repo_get_function = repo.getOtherXML
repo_cache_function = repo.cacheHandler.getOtherdata
else:
continue
if self._check_db_version(repo, mydbtype):
# Use gen decompression on DB files. Keeps exactly what we
# downloaded in the download dir.
# Backwards compat. ... try the old uncompressed version first.
db_un_fn = self._check_uncompressed_db(repo, mydbtype)
if not db_un_fn:
db_un_fn = self._check_uncompressed_db_gen(repo, mydbtype)
if not db_un_fn:
db_fn = repo._retrieveMD(mydbtype)
if db_fn:
# unlink the decompressed file, we know it's not valid
misc.unlink_f(repo.cachedir +'/gen/%s.sqlite' % mydbtype)
db_un_fn = self._check_uncompressed_db_gen(repo,
mydbtype)
if not db_un_fn: # Shouldn't happen?
raise Errors.RepoError('%s: Check uncompressed DB failed' % repo,
repo=self)
dobj = repo.cacheHandler.open_database(db_un_fn)
else:
repo._xml2sqlite_local = True
# Download...
xml = repo_get_function()
# Use generated dir. and handle compression types metadata
# parser doesn't understand.
gen = mymdtype + '.xml'
ret = misc.repo_gen_decompress(xml, gen, cached=repo.cache)
if not ret:
raise Errors.RepoError('%s: Decompress DB failed' % repo,
repo=self)
xml = ret
# Convert XML => .sqlite
xmldata = repo.repoXML.getData(mymdtype)
(ctype, csum) = xmldata.checksum
dobj = repo_cache_function(xml, csum)
if not cacheonly:
self.addDict(repo, item, dobj, callback)
del dobj
# get rid of all this stuff we don't need now
del repo.cacheHandler
def _check_uncompressed_db_gen(self, repo, mdtype):
"""return file name of db in gen/ dir if good, None if not"""
mydbdata = repo.repoXML.getData(mdtype)
(r_base, remote) = mydbdata.location
fname = os.path.basename(remote)
compressed_fn = repo.cachedir + '/' + fname
db_un_fn = mdtype + '.sqlite'
if not repo._checkMD(compressed_fn, mdtype, data=mydbdata,
check_can_fail=True):
return None
ret = misc.repo_gen_decompress(compressed_fn, db_un_fn,
cached=repo.cache)
if ret:
return self._check_uncompressed_db_fn(repo, mdtype, ret)
return None
def _check_uncompressed_db(self, repo, mdtype):
"""return file name of uncompressed db is good, None if not"""
mydbdata = repo.repoXML.getData(mdtype)
(r_base, remote) = mydbdata.location
fname = os.path.basename(remote)
compressed_fn = repo.cachedir + '/' + fname
db_un_fn = misc.decompress(compressed_fn, fn_only=True)
return self._check_uncompressed_db_fn(repo, mdtype, db_un_fn)
def _check_uncompressed_db_fn(self, repo, mdtype, db_un_fn):
result = None
if os.path.exists(db_un_fn):
try:
repo.checkMD(db_un_fn, mdtype, openchecksum=True)
except URLGrabError:
if not repo.cache:
misc.unlink_f(db_un_fn)
else:
result = db_un_fn
return result
def _check_db_version(self, repo, mdtype):
return repo._check_db_version(mdtype)
class YumRepository(Repository, config.RepoConf):
"""
This is an actual repository object
Configuration attributes are pulled in from config.RepoConf.
"""
def __init__(self, repoid):
config.RepoConf.__init__(self)
Repository.__init__(self, repoid)
self.repofile = None
self.mirrorurls = []
self._urls = []
self.enablegroups = 0
self.groupsfilename = 'yumgroups.xml' # something some freaks might
# eventually want
self.repoMDFile = 'repodata/repomd.xml'
self._repoXML = None
self._oldRepoMDData = {}
self.cache = 0
self._retry_no_cache = False
self.mirrorlistparsed = 0
self.yumvar = {} # empty dict of yumvariables for $string replacement
self._proxy_dict = {}
self.metadata_cookie_fn = 'cachecookie'
self._metadataCurrent = None
self._metalink = None
self.groups_added = False
self.http_headers = {}
self.repo_config_age = 0 # if we're a repo not from a file then the
# config is very, very old
# throw in some stubs for things that will be set by the config class
self.basecachedir = ""
self.base_persistdir = ""
self.cost = 1000
self.copy_local = 0
# holder for stuff we've grabbed
self.retrieved = { 'primary':0, 'filelists':0, 'other':0, 'group':0,
'updateinfo':0, 'prestodelta':0}
self._preloaded_repomd = False
# callbacks
self.callback = None # for the grabber
self.multi_callback = None
self.failure_obj = None
self.mirror_failure_obj = None
self.interrupt_callback = None
self._callbacks_changed = False
# callback function for handling media
self.mediafunc = None
# callbacks for gpg key importing and confirmation
self.gpg_import_func = None
self.gpgca_import_func = None
self.confirm_func = None
# The reason we want to turn this off are things like repoids
# called "tmp" in repoquery --repofrompath and/or new1/old1 in repodiff.
self.timestamp_check = True
self._sack = None
self._grabfunc = None
self._grab = None
self._async = False
def __cmp__(self, other):
""" Sort yum repos. by cost, and then by alphanumeric on their id. """
if other is None:
return 1
if hasattr(other, 'cost'):
ocost = other.cost
else:
ocost = 1000
ret = cmp(self.cost, ocost)
if ret:
return ret
return cmp(self.id, other.id)
def _getSack(self):
# FIXME: Note that having the repo hold the sack, which holds "repos"
# is not only confusing but creates a circular dep.
# Atm. we don't leak memory because RepoStorage.close() is called,
# which calls repo.close() which calls sack.close() which removes the
# repos from the sack ... thus. breaking the cycle.
if self._sack is None:
self._sack = sqlitesack.YumSqlitePackageSack(
sqlitesack.YumAvailablePackageSqlite)
return self._sack
sack = property(_getSack)
def _ui_id(self):
""" Show self.id, but include any $releasever/$basearch/etc. data. """
if hasattr(self, '__cached_ui_id'):
return getattr(self, '__cached_ui_id')
val = config._readRawRepoFile(self)
if not val:
val = ''
else:
ini, section_id = val
ini = ini[section_id]
if 'metalink' in ini:
val = ini['metalink']
elif 'mirrorlist' in ini:
val = ini['mirrorlist']
elif 'baseurl' in ini:
val = ini['baseurl']
else:
val = ''
ret = self.id
for var in self.ui_repoid_vars:
if '$'+var in val:
ret += '/'
ret += str(self.yumvar[var])
setattr(self, '__cached_ui_id', ret)
return ret
ui_id = property(_ui_id)
def close(self):
if self._sack is not None:
self.sack.close()
Repository.close(self)
def _resetSack(self):
self._sack = None
def __getProxyDict(self):
self.doProxyDict()
if self._proxy_dict:
return self._proxy_dict
return None
# consistent access to how proxy information should look (and ensuring
# that it's actually determined for the repo)
proxy_dict = property(__getProxyDict)
def getPackageSack(self):
"""Returns the instance of this repository's package sack."""
return self.sack
def ready(self):
"""Returns true if this repository is setup and ready for use."""
if hasattr(self, 'metadata_cookie'):
return self.repoXML is not None
return False
def getGroupLocation(self):
"""Returns the location of the group."""
if 'group_gz' in self.repoXML.fileTypes():
thisdata = self.repoXML.getData('group_gz')
else:
thisdata = self.repoXML.getData('group')
return thisdata.location
def __str__(self):
# Note: You might expect this to be .ui_id, except people got used to
# the fact that str(repo) == repo.id and used the former instead of
# the later when they wanted just the .id. So we have to live with it
# and use .ui_id explicitly.
return self.id
def _checksum(self, sumtype, file, CHUNK=2**16, checksum_can_fail=False,
datasize=None):
"""takes filename, hand back Checksum of it
sumtype = md5 or sha
filename = /path/to/file
CHUNK=65536 by default"""
try:
return misc.checksum(sumtype, file, CHUNK, datasize)
except (Errors.MiscError, EnvironmentError), e:
if checksum_can_fail:
return None
msg = 'Error opening file for checksum: %s' % e
if isinstance(e, Errors.FIPSNonCompliantError):
msg = str(e)
raise Errors.RepoError(msg, repo=self)
def dump(self):
output = '[%s]\n' % self.id
# we exclude all vars which start with _ or are in this list:
excluded_vars = ('mediafunc', 'sack', 'metalink_data', 'grab',
'grabfunc', 'repoXML', 'cfg', 'retrieved',
'mirrorlistparsed', 'gpg_import_func',
'gpgca_import_func', 'failure_obj',
'callback', 'confirm_func', 'groups_added',
'interrupt_callback', 'id', 'mirror_failure_obj',
'repo_config_age', 'groupsfilename', 'copy_local',
'basecachedir', 'http_headers', 'metadata_cookie',
'metadata_cookie_fn', 'quick_enable_disable',
'repoMDFile', 'timestamp_check', 'urls', 'mirrorurls',
'yumvar', 'repofile', 'multi_callback')
for attr in dir(self):
if attr.startswith('_'):
continue
if attr in excluded_vars:
continue
if isinstance(getattr(self, attr), types.MethodType):
continue
res = getattr(self, attr)
if not res and type(res) not in (type(False), type(0)):
res = ''
if type(res) == types.ListType:
res = ',\n '.join(res)
output = output + '%s = %s\n' % (attr, res)
return output
def enablePersistent(self):
"""Persistently enables this repository."""
self.enable()
try:
config.writeRawRepoFile(self,only=['enabled'])
except IOError, e:
if e.errno == errno.EACCES:
logger.warning(e)
else:
raise IOError, str(e)
def disablePersistent(self):
"""Persistently disables this repository."""
self.disable()
try:
config.writeRawRepoFile(self,only=['enabled'])
except IOError, e:
if e.errno == errno.EACCES:
logger.warning(e)
else:
raise IOError, str(e)
def check(self):
"""self-check the repo information - if we don't have enough to move
on then raise a repo error"""
if len(self._urls) < 1 and not self.mediaid:
raise Errors.RepoError('Cannot find a valid baseurl for repo: %s' %
self.ui_id, repo=self)
def doProxyDict(self):
if self._proxy_dict:
return
self._proxy_dict = {} # zap it
proxy_string = None
empty = (None, '_none_', '')
if self.proxy is None: # got 'proxy=_none_'
proxy_string = '' # this disables default proxies
elif self.proxy:
proxy_string = '%s' % self.proxy
if self.proxy_username not in empty:
auth = urllib.quote(self.proxy_username)
if self.proxy_password not in empty:
auth += ':' + urllib.quote(self.proxy_password)
proto, rest = re.match('(\w+://)(.+)', proxy_string).groups()
proxy_string = '%s%s@%s' % (proto, auth, rest)
if proxy_string is not None:
self._proxy_dict['http'] = proxy_string
self._proxy_dict['https'] = proxy_string
self._proxy_dict['ftp'] = proxy_string
def __headersListFromDict(self, cache=True):
"""Convert our dict of headers to a list of 2-tuples for urlgrabber."""
headers = []
for key in self.http_headers:
headers.append((key, self.http_headers[key]))
if not (cache or 'Pragma' in self.http_headers):
headers.append(('Pragma', 'no-cache'))
return headers
def setupGrab(self):
warnings.warn('setupGrab() will go away in a future version of Yum.\n',
Errors.YumFutureDeprecationWarning, stacklevel=2)
self._setupGrab()
def _setupGrab(self):
"""sets up the grabber functions with the already stocked in urls for
the mirror groups"""
if self.failovermethod == 'roundrobin':
mgclass = urlgrabber.mirror.MGRandomOrder
else:
mgclass = urlgrabber.mirror.MirrorGroup
ugopts = self._default_grabopts()
self._grabfunc = URLGrabber(progress_obj=self.callback,
multi_progress_obj=self.multi_callback,
failure_callback=self.failure_obj,
interrupt_callback=self.interrupt_callback,
copy_local=self.copy_local,
reget='simple',
**ugopts)
def add_mc(url):
host = urlparse.urlsplit(url).netloc.split('@')[-1]
mc = self.metalink_data._host2mc.get(host)
if mc:
url = {
'mirror': misc.to_utf8(url),
'kwargs': {
'max_connections': mc.max_connections,
'preference': mc.preference,
'private': mc.private,
},
}
return url
urls = self.urls
if self.metalink:
urls = map(add_mc, urls)
def mirror_failure(obj):
action = {}
# timeout, refused connect, and HTTP 503 may retry
e = obj.exception
if e.errno == 12 or \
e.errno == 14 and getattr(e, 'code', 0) in (7, 503):
tries = getattr(obj, 'tries', self.retries)
if tries <= self.retries - len(self.urls):
# don't remove this mirror yet
action['remove'] = False
elif e.errno == -3:
# unsupported checksum type, fail now
action['fail'] = True
# No known user of this callback, but just in case...
cb = self.mirror_failure_obj
if cb:
fun, arg, karg = callable(cb) and (cb, (), {}) or cb
action.update(fun(obj, *arg, **karg))
return action
self._grab = mgclass(self._grabfunc, urls,
failure_callback=mirror_failure)
def _default_grabopts(self, cache=True):
opts = { 'keepalive': self.keepalive,
'bandwidth': self.bandwidth,
'retry': self.retries,
'throttle': self.throttle,
'timeout': self.timeout,
'minrate': self.minrate,
'ip_resolve': self.ip_resolve,
'http_headers': tuple(self.__headersListFromDict(cache=cache)),
'ssl_verify_peer': self.sslverify,
'ssl_verify_host': self.sslverify,
'ssl_ca_cert': self.sslcacert,
'ssl_cert': self.sslclientcert,
'ssl_key': self.sslclientkey,
'user_agent': default_grabber.opts.user_agent,
'username': self.username,
'password': self.password,
'ftp_disable_epsv': self.ftp_disable_epsv,
}
if self.proxy == 'libproxy':
opts['libproxy'] = True
else:
opts['proxies'] = self.proxy_dict
return opts
def _getgrabfunc(self):
if not self._grabfunc or self._callbacks_changed:
self._setupGrab()
self._callbacks_changed = False
return self._grabfunc
def _getgrab(self):
if not self._grab or self._callbacks_changed:
self._setupGrab()
self._callbacks_changed = False
return self._grab
grabfunc = property(lambda self: self._getgrabfunc())
grab = property(lambda self: self._getgrab())
def _dirSetupMkdir_p(self, dpath):
"""make the necessary directory path, if possible, raise on failure"""
if os.path.exists(dpath) and os.path.isdir(dpath):
return
try:
os.makedirs(dpath, mode=0755)
except OSError, e:
msg = "%s: %s %s: %s" % ("Error making cache directory",
dpath, "error was", e)
raise Errors.RepoError(msg, repo=self)
def dirSetup(self):
"""make the necessary dirs, if possible, raise on failure"""
cachedir = os.path.join(self.basecachedir, self.id)
persistdir = os.path.join(self.base_persistdir, self.id)
pkgdir = os.path.join(cachedir, 'packages')
hdrdir = os.path.join(cachedir, 'headers')
self.setAttribute('_dir_setup_cachedir', cachedir)
self.setAttribute('_dir_setup_pkgdir', pkgdir)
self.setAttribute('_dir_setup_hdrdir', hdrdir)
self.setAttribute('_dir_setup_persistdir', persistdir)
ext=''
if os.geteuid() != 0:
ext = '-ro'
self.setAttribute('_dir_setup_gpgdir', persistdir + '/gpgdir' + ext)
self.setAttribute('_dir_setup_gpgcadir', persistdir + '/gpgcadir' + ext)
cookie = self.cachedir + '/' + self.metadata_cookie_fn
self.setAttribute('_dir_setup_metadata_cookie', cookie)
for dir in [self.cachedir, self.cachedir + '/gen', self.pkgdir]:
self._dirSetupMkdir_p(dir)
# persistdir is really root-only but try the make anyway and just
# catch the exception
for dir in [self.persistdir]:
try:
self._dirSetupMkdir_p(dir)
except Errors.RepoError, e:
pass
# if we're using a cachedir that's not the system one, copy over these
# basic items from the system one
if self._preload_md_from_system_cache('repomd.xml'):
self._preloaded_repomd = True
self._preload_md_from_system_cache('cachecookie')
self._preload_md_from_system_cache('mirrorlist.txt')
self._preload_md_from_system_cache('metalink.xml')
def _dirGetAttr(self, attr):
""" Make the directory attributes call .dirSetup() if needed. """
attr = '_dir_setup_' + attr
if not hasattr(self, attr):
self.dirSetup()
return getattr(self, attr)
def _dirSetAttr(self, attr, val):
""" Make the directory attributes call .dirSetup() if needed. """
attr = '_dir_setup_' + attr
if not hasattr(self, attr):
self.dirSetup()
if attr == '_dir_setup_pkgdir':
if not hasattr(self, '_old_pkgdirs'):
self._old_pkgdirs = []
self._old_pkgdirs.append(getattr(self, attr))
ret = setattr(self, attr, val)
if attr in ('_dir_setup_pkgdir', ):
self._dirSetupMkdir_p(val)
return ret
cachedir = property(lambda self: self._dirGetAttr('cachedir'))
persistdir = property(lambda self: self._dirGetAttr('persistdir'))
pkgdir = property(lambda self: self._dirGetAttr('pkgdir'),
lambda self, x: self._dirSetAttr('pkgdir', x))
hdrdir = property(lambda self: self._dirGetAttr('hdrdir'),
lambda self, x: self._dirSetAttr('hdrdir', x))
gpgdir = property(lambda self: self._dirGetAttr('gpgdir'),
lambda self, x: self._dirSetAttr('gpgdir', x))
gpgcadir = property(lambda self: self._dirGetAttr('gpgcadir'),
lambda self, x: self._dirSetAttr('gpgcadir', x))
metadata_cookie = property(lambda self: self._dirGetAttr('metadata_cookie'))
def baseurlSetup(self):
warnings.warn('baseurlSetup() will go away in a future version of Yum.\n',
Errors.YumFutureDeprecationWarning, stacklevel=2)
self._baseurlSetup()
def _hack_mirrorlist_for_anaconda(self):
# Anaconda doesn't like having mirrorlist and metalink, so we allow
# mirrorlist to act like metalink. Except we'd really like to know which
# we have without parsing it ... and want to store it in the right
# place etc.
# So here is #1 hack: see if the metalin kis unset and the mirrorlist
# URL contains the string "metalink", if it does we copy it over.
if self.metalink:
return
if not self.mirrorlist:
return
if self.mirrorlist.find("metalink") == -1:
return
self.metalink = self.mirrorlist
def _baseurlSetup(self):
"""go through the baseurls and mirrorlists and populate self.urls
with valid ones, run self.check() at the end to make sure it worked"""
self.baseurl = self._replace_and_check_url(self.baseurl)
# FIXME: We put all the mirrors in .baseurl as well as
# .urls for backward compat. (see bottom of func). So we'll save this
# out for repolist -v ... or anything else wants to know the baseurl
self._orig_baseurl = self.baseurl
mirrorurls = []
self._hack_mirrorlist_for_anaconda()
if self.metalink and not self.mirrorlistparsed:
# FIXME: This is kind of lying to API callers
mirrorurls.extend(list(self.metalink_data.urls()))
self.mirrorlistparsed = True
if self.mirrorlist and not self.mirrorlistparsed:
mirrorurls.extend(self._getMirrorList())
self.mirrorlistparsed = True
self.mirrorurls = self._replace_and_check_url(mirrorurls)
self._urls = self.baseurl + self.mirrorurls
# if our mirrorlist is just screwed then make sure we unlink a mirrorlist cache
if len(self._urls) < 1:
if hasattr(self, 'mirrorlist_file') and os.path.exists(self.mirrorlist_file):
if not self.cache:
try:
misc.unlink_f(self.mirrorlist_file)
except (IOError, OSError), e:
logger.error('Could not delete bad mirrorlist file: %s - %s' % (self.mirrorlist_file, e))
else:
logger.warning('removing mirrorlist with no valid mirrors: %s' % self.mirrorlist_file)
# store them all back in baseurl for compat purposes
self.baseurl = self._urls
self.check()
def _replace_and_check_url(self, url_list):
goodurls = []
skipped = None
for url in url_list:
# obvious bogons get ignored b/c, we could get more interesting checks but <shrug>
if url in ['', None]:
continue
url = parser.varReplace(url, self.yumvar)
try:
# This started throwing ValueErrors, BZ 666826
(s,b,p,q,f,o) = urlparse.urlparse(url)
if p[-1] != '/':
p = p + '/'
except (ValueError, IndexError, KeyError), e:
s = 'blah'
if s not in ['http', 'ftp', 'file', 'https']:
skipped = url
continue
else:
goodurls.append(urlparse.urlunparse((s,b,p,q,f,o)))
if skipped is not None:
# Caller cleans up for us.
if goodurls:
logger.warning('YumRepo Warning: Some mirror URLs are not using ftp, http[s] or file.\n Eg. %s' % misc.to_utf8(skipped))
else: # And raises in this case
logger.error('YumRepo Error: All mirror URLs are not using ftp, http[s] or file.\n Eg. %s' % misc.to_utf8(skipped))
return goodurls
def _geturls(self):
if not self._urls:
self._baseurlSetup()
return self._urls
urls = property(fget=lambda self: self._geturls(),
fset=lambda self, value: setattr(self, "_urls", value),
fdel=lambda self: setattr(self, "_urls", None))
def _getMetalink(self):
if not self._metalink:
self.metalink_filename = self.cachedir + '/' + 'metalink.xml'
local = self.metalink_filename + '.tmp'
if not self._metalinkCurrent():
url = misc.to_utf8(self.metalink)
ugopts = self._default_grabopts(cache=self.http_caching=='all')
try:
ug = URLGrabber(progress_obj = self.callback, **ugopts)
result = ug.urlgrab(url, local, text="%s/metalink" % self.ui_id)
except URLGrabError, e:
if not os.path.exists(self.metalink_filename):
msg = ("Cannot retrieve metalink for repository: %s. "
"Please verify its path and try again" % self.ui_id )
raise Errors.RepoError(msg, repo=self)
# Now, we have an old usable metalink, so we can't move to
# a newer repomd.xml ... or checksums won't match.
logger.error("Could not get metalink %s error was\n%s: %s" % (url, e.args[0], misc.to_unicode(e.args[1])))
self._metadataCurrent = True
if not self._metadataCurrent:
try:
self._metalink = metalink.MetaLinkRepoMD(result)
shutil.move(result, self.metalink_filename)
except metalink.MetaLinkRepoErrorParseFail, e:
# Downloaded file failed to parse, revert (dito. above):
logger.error("Could not parse metalink %s error was \n%s" % (url, e))
self._metadataCurrent = True
misc.unlink_f(result)
if self._metadataCurrent:
self._metalink = metalink.MetaLinkRepoMD(self.metalink_filename)
return self._metalink
metalink_data = property(fget=lambda self: self._getMetalink(),
fset=lambda self, value: setattr(self, "_metalink",
value),
fdel=lambda self: setattr(self, "_metalink", None))
def _all_urls_are_files(self, url):
if url:
return url.startswith("/") or url.startswith("file:")
if not self.urls: # WTF ... but whatever.
return False
# Not an explicit url ... so make sure all mirrors/etc. are file://
for url in self.urls:
if not self._all_urls_are_files(url):
return False
return True
def _getFile(self, url=None, relative=None, local=None, start=None, end=None,
copy_local=None, checkfunc=None, text=None, reget='simple',
cache=True, size=None, **kwargs):
"""retrieve file from the mirrorgroup for the repo
relative to local, optionally get range from
start to end, also optionally retrieve from a specific baseurl"""
# if local or relative is None: raise an exception b/c that shouldn't happen
# if url is not None - then do a grab from the complete url - not through
# the mirror, raise errors as need be
# if url is None do a grab via the mirror group/grab for the repo
# return the path to the local file
# if copylocal isn't specified pickup the repo-defined attr
if copy_local is None:
copy_local = self.copy_local
if local is None or relative is None:
raise Errors.RepoError("get request for Repo %s, gave no source or dest" % self.ui_id,
repo=self)
if self.cache == 1:
if os.path.exists(local): # FIXME - we should figure out a way
return local # to run the checkfunc from here
else: # ain't there - raise
raise Errors.RepoError("Caching enabled but no local cache of %s from %s" % (local, self.ui_id),
repo=self)
if url:
(scheme, netloc, path, query, fragid) = urlparse.urlsplit(url)
if self.mediaid and self.mediafunc:
discnum = 1
if url:
if scheme == "media" and fragid:
discnum = int(fragid)
try:
# FIXME: we need to figure out what really matters to
# pass to the media grabber function here
result = self.mediafunc(local = local, checkfunc = checkfunc, relative = relative, text = text, copy_local = copy_local, url = url, mediaid = self.mediaid, name = self.name, discnum = discnum, range = (start, end))
return result
except Errors.MediaError, e:
verbose_logger.log(logginglevels.DEBUG_2, "Error getting package from media; falling back to url %s" %(e,))
if size and (copy_local or not self._all_urls_are_files(url)):
dirstat = os.statvfs(os.path.dirname(local))
avail = dirstat.f_bavail * dirstat.f_bsize
if avail < long(size):
raise Errors.RepoError(_('''\
Insufficient space in download directory %s
* free %s
* needed %s'''
) % (os.path.dirname(local), format_number(avail), format_number(long(size))), repo=self)
if url and scheme != "media":
ugopts = self._default_grabopts(cache=cache)
ug = URLGrabber(progress_obj = self.callback,
copy_local = copy_local,