3 # Copyright (c) 2010, 2011 Intel, Inc.
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation; version 2 of the License
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc., 59
16 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 if not hasattr(zypp, 'PoolQuery') or \
25 not hasattr(zypp.RepoManager, 'loadSolvFile'):
26 raise ImportError("python-zypp in host system cannot support PoolQuery or "
27 "loadSolvFile interface, please update it to enhanced "
28 "version which can be found in download.tizen.org/tools")
31 from mic.kickstart import ksparser
32 from mic.utils import misc, rpmmisc, runner, fs_related
33 from mic.utils.grabber import myurlgrab, TextProgress
34 from mic.utils.proxy import get_proxy_for
35 from mic.utils.errors import CreatorError, RepoError, RpmError
36 from mic.imager.baseimager import BaseImageCreator
42 self.mirrorlist = None
44 self.proxy_username = None
45 self.proxy_password = None
49 self.autorefresh = True
50 self.keeppackages = True
53 from mic.pluginbase import BackendPlugin
54 class Zypp(BackendPlugin):
57 def __init__(self, target_arch, instroot, cachedir):
58 self.cachedir = cachedir
59 self.instroot = instroot
60 self.target_arch = target_arch
62 self.__pkgs_license = {}
63 self.__pkgs_content = {}
64 self.__pkgs_vcsinfo = {}
68 self.repo_manager = None
69 self.repo_manager_options = None
77 self.probFilterFlags = [ rpm.RPMPROB_FILTER_OLDPACKAGE,
78 rpm.RPMPROB_FILTER_REPLACEPKG ]
80 self.has_prov_query = True
81 self.install_debuginfo = False
83 def doFileLogSetup(self, uid, logfile):
84 # don't do the file log for the livecd as it can lead to open fds
85 # being left and an inability to clean up after ourself
102 if not os.path.exists("/etc/fedora-release") and \
103 not os.path.exists("/etc/meego-release"):
104 for i in range(3, os.sysconf("SC_OPEN_MAX")):
113 def _cleanupRpmdbLocks(self, installroot):
114 # cleans up temporary files left by bdb so that differing
115 # versions of rpm don't cause problems
117 for f in glob.glob(installroot + "/var/lib/rpm/__db*"):
120 def _cleanupZyppJunk(self, installroot):
122 shutil.rmtree(os.path.join(installroot, '.zypp'))
127 self._cleanupRpmdbLocks(self.instroot)
129 def whatObsolete(self, pkg):
130 query = zypp.PoolQuery()
131 query.addKind(zypp.ResKind.package)
132 query.addAttribute(zypp.SolvAttr.obsoletes, pkg)
133 query.setMatchExact()
134 for pi in query.queryResults(self.Z.pool()):
138 def _zyppQueryPackage(self, pkg):
139 query = zypp.PoolQuery()
140 query.addKind(zypp.ResKind.package)
141 query.addAttribute(zypp.SolvAttr.name,pkg)
142 query.setMatchExact()
143 for pi in query.queryResults(self.Z.pool()):
147 def _splitPkgString(self, pkg):
148 sp = pkg.rsplit(".",1)
153 sysarch = zypp.Arch(self.target_arch)
154 if not zypp.Arch(arch).compatible_with (sysarch):
159 def selectPackage(self, pkg):
160 """Select a given package or package pattern, can be specified
161 with name.arch or name* or *name
165 self.__initialize_zypp()
167 def markPoolItem(obs, pi):
169 pi.status().setToBeInstalled (zypp.ResStatus.USER)
171 obs.status().setToBeInstalled (zypp.ResStatus.USER)
174 # compare criterion: arch compatibility first, then repo
175 # priority, and version last
178 if str(a1) != str(a2):
179 if a1.compatible_with(a2):
183 # Priority of a repository is an integer value between 0 (the
184 # highest priority) and 99 (the lowest priority)
185 pr1 = int(p1.repoInfo().priority())
186 pr2 = int(p2.repoInfo().priority())
194 (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
195 (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
196 return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
199 startx = pkg.startswith("*")
200 endx = pkg.endswith("*")
201 ispattern = startx or endx
202 name, arch = self._splitPkgString(pkg)
205 q.addKind(zypp.ResKind.package)
208 if startx and not endx:
209 pattern = '%s$' % (pkg[1:])
210 if endx and not startx:
211 pattern = '^%s' % (pkg[0:-1])
213 pattern = '%s' % (pkg[1:-1])
215 q.addAttribute(zypp.SolvAttr.name,pattern)
219 q.addAttribute(zypp.SolvAttr.name,name)
223 q.addAttribute(zypp.SolvAttr.name,pkg)
226 q.queryResults(self.Z.pool()),
227 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
229 item = zypp.asKindPackage(pitem)
230 if item.name() in self.excpkgs.keys() and \
231 self.excpkgs[item.name()] == item.repoInfo().name():
233 if item.name() in self.incpkgs.keys() and \
234 self.incpkgs[item.name()] != item.repoInfo().name():
238 obspkg = self.whatObsolete(item.name())
240 if arch == str(item.arch()):
241 item.status().setToBeInstalled (zypp.ResStatus.USER)
243 markPoolItem(obspkg, pitem)
247 # Can't match using package name, then search from packge
248 # provides infomation
249 if found == False and not ispattern:
250 q.addAttribute(zypp.SolvAttr.provides, pkg)
251 q.addAttribute(zypp.SolvAttr.name,'')
254 q.queryResults(self.Z.pool()),
255 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
257 item = zypp.asKindPackage(pitem)
258 if item.name() in self.excpkgs.keys() and \
259 self.excpkgs[item.name()] == item.repoInfo().name():
261 if item.name() in self.incpkgs.keys() and \
262 self.incpkgs[item.name()] != item.repoInfo().name():
266 obspkg = self.whatObsolete(item.name())
267 markPoolItem(obspkg, pitem)
273 raise CreatorError("Unable to find package: %s" % (pkg,))
275 def inDeselectPackages(self, pitem):
276 """check if specified pacakges are in the list of inDeselectPackages
278 item = zypp.asKindPackage(pitem)
280 for pkg in self.to_deselect:
281 startx = pkg.startswith("*")
282 endx = pkg.endswith("*")
283 ispattern = startx or endx
284 pkgname, pkgarch = self._splitPkgString(pkg)
287 if name == pkgname and str(item.arch()) == pkgarch:
293 if startx and name.endswith(pkg[1:]):
295 if endx and name.startswith(pkg[:-1]):
300 def deselectPackage(self, pkg):
301 """collect packages should not be installed"""
302 self.to_deselect.append(pkg)
304 def selectGroup(self, grp, include = ksparser.GROUP_DEFAULT):
306 self.__initialize_zypp()
309 q.addKind(zypp.ResKind.pattern)
310 for pitem in q.queryResults(self.Z.pool()):
311 item = zypp.asKindPattern(pitem)
312 summary = "%s" % item.summary()
313 name = "%s" % item.name()
314 if name == grp or summary == grp:
316 pitem.status().setToBeInstalled (zypp.ResStatus.USER)
320 if include == ksparser.GROUP_REQUIRED:
322 lambda p: self.deselectPackage(p),
323 grp.default_packages.keys())
327 raise CreatorError("Unable to find pattern: %s" % (grp,))
329 def addRepository(self, name,
333 proxy_username = None,
334 proxy_password = None,
341 # TODO: Handle cost attribute for repos
343 if not self.repo_manager:
344 self.__initialize_repo_manager()
346 if not proxy and url:
347 proxy = get_proxy_for(url)
349 repo = RepositoryStub()
353 repo.proxy_username = proxy_username
354 repo.proxy_password = proxy_password
355 repo.ssl_verify = ssl_verify
356 repo.nocache = nocache
357 repo.baseurl.append(url)
360 self.incpkgs[pkg] = name
363 self.excpkgs[pkg] = name
365 # check LICENSE files
366 if not rpmmisc.checkRepositoryEULA(name, repo):
367 msger.warning('skip repo:%s for failed EULA confirmation' % name)
371 repo.mirrorlist = mirrorlist
373 # Enable gpg check for verifying corrupt packages
375 if priority is not None:
376 # priority 0 has issue in RepoInfo.setPriority
377 repo.priority = priority + 1
380 repo_info = zypp.RepoInfo()
381 repo_info.setAlias(repo.name)
382 repo_info.setName(repo.name)
383 repo_info.setEnabled(repo.enabled)
384 repo_info.setAutorefresh(repo.autorefresh)
385 repo_info.setKeepPackages(repo.keeppackages)
386 baseurl = zypp.Url(repo.baseurl[0])
388 baseurl.setQueryParam("ssl_verify", "no")
390 scheme, host, path, parm, query, frag = urlparse.urlparse(proxy)
392 proxyinfo = host.rsplit(":", 1)
396 if len(proxyinfo) > 1:
399 if proxy.startswith("socks") and len(proxy.rsplit(':', 1)) == 2:
400 host = proxy.rsplit(':', 1)[0]
401 port = proxy.rsplit(':', 1)[1]
403 # parse user/pass from proxy host
404 proxyinfo = host.rsplit("@", 1)
405 if len(proxyinfo) == 2:
407 # Known Issue: If password contains ":", which should be
408 # quoted, for example, use '123%3Aabc' instead of 123:abc
409 userpassinfo = proxyinfo[0].rsplit(":", 1)
410 if len(userpassinfo) == 2:
411 proxy_username = userpassinfo[0]
412 proxy_password = userpassinfo[1]
413 elif len(userpassinfo) == 1:
414 proxy_username = userpassinfo[0]
416 baseurl.setQueryParam ("proxy", host)
417 baseurl.setQueryParam ("proxyport", port)
419 baseurl.setQueryParam ("proxyuser", proxy_username)
421 baseurl.setQueryParam ("proxypass", proxy_password)
423 baseurl.setQueryParam ("proxy", "_none_")
425 repo.baseurl[0] = baseurl.asCompleteString()
426 self.repos.append(repo)
428 repo_info.addBaseUrl(baseurl)
430 if repo.priority is not None:
431 repo_info.setPriority(repo.priority)
433 # this hack is used to change zypp credential file location
434 # the default one is $HOME/.zypp, which cause conflicts when
435 # installing some basic packages, and the location doesn't
436 # have any interface actually, so use a tricky way anyway
438 if 'HOME' in os.environ:
439 homedir = os.environ['HOME']
440 os.environ['HOME'] = '/'
442 os.environ['HOME'] = '/'
444 self.repo_manager.addRepository(repo_info)
446 # save back the $HOME env
448 os.environ['HOME'] = homedir
450 del os.environ['HOME']
452 self.__build_repo_cache(name)
454 except RuntimeError, e:
455 raise CreatorError(str(e))
457 msger.verbose('repo: %s was added' % name)
460 def installHasFile(self, file):
463 def preInstall(self, pkg):
464 self.pre_pkgs.append(pkg)
466 def checkPackage(self, pkg):
467 self.check_pkgs.append(pkg)
469 def runInstall(self, checksize = 0):
470 os.environ["HOME"] = "/"
471 os.environ["LD_PRELOAD"] = ""
472 self.buildTransaction()
474 todo = zypp.GetResolvablesToInsDel(self.Z.pool())
475 installed_pkgs = todo._toInstall
478 for pitem in installed_pkgs:
479 if not zypp.isKindPattern(pitem) and \
480 not self.inDeselectPackages(pitem):
481 item = zypp.asKindPackage(pitem)
484 if item.name() in self.check_pkgs:
485 self.check_pkgs.remove(item.name())
487 if not self.install_debuginfo or str(item.arch()) == "noarch":
490 dipkg = self._zyppQueryPackage("%s-debuginfo" % item.name())
492 ditem = zypp.asKindPackage(dipkg)
495 msger.warning("No debuginfo rpm found for: %s" \
499 raise CreatorError('Packages absent in image: %s' % ','.join(self.check_pkgs))
501 # record all pkg and the content
502 localpkgs = self.localpkgs.keys()
505 if pkg.name() in localpkgs:
506 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
507 pkg_long_name = misc.RPM_FMT % {
510 'version': hdr['version'],
511 'release': hdr['release']
513 license = hdr['license']
516 pkg_long_name = misc.RPM_FMT % {
519 'version': pkg.edition().version(),
520 'release': pkg.edition().release()
523 license = pkg.license()
525 if license in self.__pkgs_license.keys():
526 self.__pkgs_license[license].append(pkg_long_name)
528 self.__pkgs_license[license] = [pkg_long_name]
530 total_count = len(dlpkgs)
532 download_total_size = sum(map(lambda x: int(x.downloadSize()), dlpkgs))
533 localpkgs = self.localpkgs.keys()
535 msger.info("Checking packages cached ...")
537 # Check if it is cached locally
538 if po.name() in localpkgs:
541 local = self.getLocalPkgPath(po)
542 name = str(po.repoInfo().name())
544 repo = filter(lambda r: r.name == name, self.repos)[0]
547 nocache = repo.nocache if repo else False
549 if os.path.exists(local):
550 if nocache or self.checkPkg(local) !=0:
553 download_total_size -= int(po.downloadSize())
555 cache_avail_size = misc.get_filesystem_avail(self.cachedir)
556 if cache_avail_size < download_total_size:
557 raise CreatorError("No enough space used for downloading.")
559 # record the total size of installed pkgs
560 install_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
561 # check needed size before actually download and install
563 # FIXME: for multiple partitions for loop type, check fails
564 # skip the check temporarily
565 #if checksize and install_total_size > checksize:
566 # raise CreatorError("No enough space used for installing, "
567 # "please resize partition size in ks file")
569 download_count = total_count - cached_count
570 msger.info("Packages: %d Total, %d Cached, %d Missed" \
571 % (total_count, cached_count, download_count))
574 if download_count > 0:
575 msger.info("Downloading packages ...")
576 self.downloadPkgs(dlpkgs, download_count)
578 self.installPkgs(dlpkgs)
580 except (RepoError, RpmError):
583 raise CreatorError("Package installation failed: %s" % (e,))
585 def getVcsInfo(self):
586 if self.__pkgs_vcsinfo:
590 self.__initialize_transaction()
592 mi = self.ts.dbMatch()
594 lname = misc.RPM_FMT % {
597 'version': hdr['version'],
598 'release': hdr['release']
601 self.__pkgs_vcsinfo[lname] = hdr['VCS']
603 # if rpm not support VCS, set to None
604 self.__pkgs_vcsinfo[lname] = None
606 return self.__pkgs_vcsinfo
608 def getAllContent(self):
609 if self.__pkgs_content:
610 return self.__pkgs_content
613 self.__initialize_transaction()
615 mi = self.ts.dbMatch()
617 lname = misc.RPM_FMT % {
620 'version': hdr['version'],
621 'release': hdr['release']
623 self.__pkgs_content[lname] = hdr['FILENAMES']
625 return self.__pkgs_content
627 def getPkgsLicense(self):
628 return self.__pkgs_license
630 def getFilelist(self, pkgname):
635 self.__initialize_transaction()
637 mi = self.ts.dbMatch('name', pkgname)
639 return header['FILENAMES']
641 def __initialize_repo_manager(self):
642 if self.repo_manager:
645 # Clean up repo metadata
646 shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
647 shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
648 shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
650 zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
651 | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
652 | zypp.KeyRing.ACCEPT_UNKNOWNKEY
653 | zypp.KeyRing.TRUST_KEY_TEMPORARILY
656 self.repo_manager_options = \
657 zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
659 self.repo_manager_options.knownReposPath = \
660 zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
662 self.repo_manager_options.repoCachePath = \
663 zypp.Pathname(self.cachedir)
665 self.repo_manager_options.repoRawCachePath = \
666 zypp.Pathname(self.cachedir + "/raw")
668 self.repo_manager_options.repoSolvCachePath = \
669 zypp.Pathname(self.cachedir + "/solv")
671 self.repo_manager_options.repoPackagesCachePath = \
672 zypp.Pathname(self.cachedir + "/packages")
674 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
676 def __build_repo_cache(self, name):
677 repo = self.repo_manager.getRepositoryInfo(name)
678 if self.repo_manager.isCached(repo) or not repo.enabled():
681 msger.info('Refreshing repository: %s ...' % name)
682 self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
684 def __initialize_zypp(self):
688 zconfig = zypp.ZConfig_instance()
690 # Set system architecture
692 zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
694 msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
696 # repoPackagesCachePath is corrected by this
697 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
698 repos = self.repo_manager.knownRepositories()
700 if not repo.enabled():
702 self.repo_manager.loadFromCache(repo)
704 self.Z = zypp.ZYppFactory_instance().getZYpp()
705 self.Z.initializeTarget(zypp.Pathname(self.instroot))
706 self.Z.target().load()
708 def buildTransaction(self):
709 if not self.Z.resolver().resolvePool():
710 probs = self.Z.resolver().problems()
712 for problem in probs:
713 msger.warning("repo problem: %s, %s" \
714 % (problem.description().decode("utf-8"),
715 problem.details().decode("utf-8")))
717 raise RepoError("found %d resolver problem, abort!" \
720 def getLocalPkgPath(self, po):
721 repoinfo = po.repoInfo()
722 cacheroot = repoinfo.packagesPath()
723 location= po.location()
724 rpmpath = str(location.filename())
725 pkgpath = "%s/%s" % (cacheroot, os.path.basename(rpmpath))
728 def installLocal(self, pkg, po=None, updateonly=False):
730 self.__initialize_transaction()
732 solvfile = "%s/.solv" % (self.cachedir)
734 rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"),
737 f = open(solvfile, "w+")
741 warnmsg = self.repo_manager.loadSolvFile(solvfile,
742 os.path.basename(pkg))
744 msger.warning(warnmsg)
748 msger.warning('Can not get %s solv data.' % pkg)
750 hdr = rpmmisc.readRpmHeader(self.ts, pkg)
751 arch = zypp.Arch(hdr['arch'])
752 sysarch = zypp.Arch(self.target_arch)
754 if arch.compatible_with (sysarch):
755 pkgname = hdr['name']
756 self.localpkgs[pkgname] = pkg
757 self.selectPackage(pkgname)
758 msger.info("Marking %s to be installed" % (pkg))
761 msger.warning("Cannot add package %s to transaction. "
762 "Not a compatible architecture: %s" \
763 % (pkg, hdr['arch']))
765 def downloadPkgs(self, package_objects, count):
766 localpkgs = self.localpkgs.keys()
767 progress_obj = TextProgress(count)
769 for po in package_objects:
770 if po.name() in localpkgs:
773 filename = self.getLocalPkgPath(po)
774 if os.path.exists(filename):
775 if self.checkPkg(filename) == 0:
778 dirn = os.path.dirname(filename)
779 if not os.path.exists(dirn):
782 url = self.get_url(po)
783 proxies = self.get_proxies(po)
786 filename = myurlgrab(url, filename, proxies, progress_obj)
791 def preinstallPkgs(self):
793 self.__initialize_transaction()
796 cb = rpmmisc.RPMInstallCallback(self.ts_pre)
797 cb.headmsg = "Preinstall"
798 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
800 # start to catch stderr output from librpm
801 msger.enable_logstderr(installlogfile)
803 errors = self.ts_pre.run(cb.callback, '')
805 msger.disable_logstderr()
806 self.ts_pre.closeDB()
809 if errors is not None:
811 msger.warning('scriptlet or other non-fatal errors occurred '
812 'during transaction.')
817 raise RepoError('Could not run transaction.')
819 def installPkgs(self, package_objects):
821 self.__initialize_transaction()
824 self._cleanupRpmdbLocks(self.instroot)
825 self._cleanupZyppJunk(self.instroot)
828 for flag in self.probFilterFlags:
830 self.ts.setProbFilter(probfilter)
831 self.ts_pre.setProbFilter(probfilter)
833 localpkgs = self.localpkgs.keys()
835 for po in package_objects:
837 if pkgname in localpkgs:
838 rpmpath = self.localpkgs[pkgname]
840 rpmpath = self.getLocalPkgPath(po)
842 if not os.path.exists(rpmpath):
843 # Maybe it is a local repo
844 rpmuri = self.get_url(po)
845 if rpmuri.startswith("file:/"):
848 if not os.path.exists(rpmpath):
849 raise RpmError("Error: %s doesn't exist" % rpmpath)
851 h = rpmmisc.readRpmHeader(self.ts, rpmpath)
853 if pkgname in self.pre_pkgs:
854 msger.verbose("pre-install package added: %s" % pkgname)
855 self.ts_pre.addInstall(h, rpmpath, 'u')
857 self.ts.addInstall(h, rpmpath, 'u')
859 unresolved_dependencies = self.ts.check()
860 if not unresolved_dependencies:
862 self.preinstallPkgs()
865 cb = rpmmisc.RPMInstallCallback(self.ts)
866 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
868 # start to catch stderr output from librpm
869 msger.enable_logstderr(installlogfile)
871 errors = self.ts.run(cb.callback, '')
873 msger.disable_logstderr()
877 if errors is not None:
879 msger.warning('scriptlet or other non-fatal errors occurred '
880 'during transaction.')
885 raise RepoError('Could not run transaction.')
888 for pkg, need, needflags, sense, key in unresolved_dependencies:
889 package = '-'.join(pkg)
891 if needflags == rpm.RPMSENSE_LESS:
892 deppkg = ' < '.join(need)
893 elif needflags == rpm.RPMSENSE_EQUAL:
894 deppkg = ' = '.join(need)
895 elif needflags == rpm.RPMSENSE_GREATER:
896 deppkg = ' > '.join(need)
898 deppkg = '-'.join(need)
900 if sense == rpm.RPMDEP_SENSE_REQUIRES:
901 msger.warning("[%s] Requires [%s], which is not provided" \
904 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
905 msger.warning("[%s] Conflicts with [%s]" %(package,deppkg))
907 raise RepoError("Unresolved dependencies, transaction failed.")
909 def __initialize_transaction(self):
911 self.ts = rpm.TransactionSet(self.instroot)
912 # Set to not verify DSA signatures.
913 self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
916 self.ts_pre = rpm.TransactionSet(self.instroot)
917 # Just unpack the files, don't run scripts
918 self.ts_pre.setFlags(rpm.RPMTRANS_FLAG_ALLFILES | rpm.RPMTRANS_FLAG_NOSCRIPTS)
919 # Set to not verify DSA signatures.
920 self.ts_pre.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
922 def checkPkg(self, pkg):
924 if not os.path.exists(pkg):
926 ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
928 msger.warning("package %s is damaged: %s" \
929 % (os.path.basename(pkg), pkg))
933 def _add_prob_flags(self, *flags):
935 if flag not in self.probFilterFlags:
936 self.probFilterFlags.append(flag)
938 def get_proxies(self, pobj):
944 repoinfo = pobj.repoInfo()
945 reponame = "%s" % repoinfo.name()
946 repos = filter(lambda r: r.name == reponame, self.repos)
947 repourl = str(repoinfo.baseUrls()[0])
950 proxy = repos[0].proxy
952 proxy = get_proxy_for(repourl)
954 proxies = {str(repourl.split(':')[0]): str(proxy)}
958 def get_url(self, pobj):
962 name = str(pobj.repoInfo().name())
964 repo = filter(lambda r: r.name == name, self.repos)[0]
968 baseurl = repo.baseurl[0]
970 index = baseurl.find("?")
972 baseurl = baseurl[:index]
974 location = pobj.location()
975 location = str(location.filename())
976 if location.startswith("./"):
977 location = location[2:]
979 return os.path.join(baseurl, location)
981 def package_url(self, pkgname):
986 (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
987 (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
988 return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
991 self.__initialize_zypp()
994 q.addKind(zypp.ResKind.package)
996 q.addAttribute(zypp.SolvAttr.name, pkgname)
997 items = sorted(q.queryResults(self.Z.pool()),
998 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
1002 item = zypp.asKindPackage(items[0])
1003 url = self.get_url(item)
1004 proxies = self.get_proxies(item)
1005 return (url, proxies)