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
82 # this can't be changed, it is used by zypp
83 self.tmp_file_path = '/var/tmp'
85 def doFileLogSetup(self, uid, logfile):
86 # don't do the file log for the livecd as it can lead to open fds
87 # being left and an inability to clean up after ourself
107 def _cleanupRpmdbLocks(self, installroot):
108 # cleans up temporary files left by bdb so that differing
109 # versions of rpm don't cause problems
111 for f in glob.glob(installroot + "/var/lib/rpm/__db*"):
114 def _cleanupZyppJunk(self, installroot):
116 shutil.rmtree(os.path.join(installroot, '.zypp'))
121 self._cleanupRpmdbLocks(self.instroot)
122 # '/var/tmp' is used by zypp to build cache, so make sure
124 if not os.path.exists(self.tmp_file_path ):
125 os.makedirs(self.tmp_file_path)
127 def whatObsolete(self, pkg):
128 query = zypp.PoolQuery()
129 query.addKind(zypp.ResKind.package)
130 query.addDependency(zypp.SolvAttr.obsoletes, pkg.name(), pkg.edition())
131 query.setMatchExact()
132 for pi in query.queryResults(self.Z.pool()):
136 def _zyppQueryPackage(self, pkg):
137 query = zypp.PoolQuery()
138 query.addKind(zypp.ResKind.package)
139 query.addAttribute(zypp.SolvAttr.name, pkg)
140 query.setMatchExact()
141 for pi in query.queryResults(self.Z.pool()):
145 def _splitPkgString(self, pkg):
146 sp = pkg.rsplit(".", 1)
151 sysarch = zypp.Arch(self.target_arch)
152 if not zypp.Arch(arch).compatible_with (sysarch):
157 def selectPackage(self, pkg):
158 """Select a given package or package pattern, can be specified
159 with name.arch or name* or *name
163 self.__initialize_zypp()
165 def markPoolItem(obs, pi):
167 pi.status().setToBeInstalled (zypp.ResStatus.USER)
169 obs.status().setToBeInstalled (zypp.ResStatus.USER)
172 # compare criterion: arch compatibility first, then repo
173 # priority, and version last
176 if str(a1) != str(a2):
177 if a1.compatible_with(a2):
181 # Priority of a repository is an integer value between 0 (the
182 # highest priority) and 99 (the lowest priority)
183 pr1 = int(p1.repoInfo().priority())
184 pr2 = int(p2.repoInfo().priority())
192 (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
193 (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
194 return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
197 startx = pkg.startswith("*")
198 endx = pkg.endswith("*")
199 ispattern = startx or endx
200 name, arch = self._splitPkgString(pkg)
203 q.addKind(zypp.ResKind.package)
206 if startx and not endx:
207 pattern = '%s$' % (pkg[1:])
208 if endx and not startx:
209 pattern = '^%s' % (pkg[0:-1])
211 pattern = '%s' % (pkg[1:-1])
213 q.addAttribute(zypp.SolvAttr.name, pattern)
217 q.addAttribute(zypp.SolvAttr.name, name)
221 q.addAttribute(zypp.SolvAttr.name, pkg)
224 q.queryResults(self.Z.pool()),
225 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
227 item = zypp.asKindPackage(pitem)
228 if item.name() in self.excpkgs.keys() and \
229 self.excpkgs[item.name()] == item.repoInfo().name():
231 if item.name() in self.incpkgs.keys() and \
232 self.incpkgs[item.name()] != item.repoInfo().name():
236 obspkg = self.whatObsolete(item)
238 if arch == str(item.arch()):
239 pitem.status().setToBeInstalled (zypp.ResStatus.USER)
241 markPoolItem(obspkg, pitem)
245 # Can't match using package name, then search from packge
246 # provides infomation
247 if found == False and not ispattern:
248 q.addAttribute(zypp.SolvAttr.provides, pkg)
249 q.addAttribute(zypp.SolvAttr.name,'')
252 q.queryResults(self.Z.pool()),
253 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
255 item = zypp.asKindPackage(pitem)
256 if item.name() in self.excpkgs.keys() and \
257 self.excpkgs[item.name()] == item.repoInfo().name():
259 if item.name() in self.incpkgs.keys() and \
260 self.incpkgs[item.name()] != item.repoInfo().name():
264 obspkg = self.whatObsolete(item)
265 markPoolItem(obspkg, pitem)
271 raise CreatorError("Unable to find package: %s" % (pkg,))
273 def inDeselectPackages(self, pitem):
274 """check if specified pacakges are in the list of inDeselectPackages
276 item = zypp.asKindPackage(pitem)
278 for pkg in self.to_deselect:
279 startx = pkg.startswith("*")
280 endx = pkg.endswith("*")
281 ispattern = startx or endx
282 pkgname, pkgarch = self._splitPkgString(pkg)
285 if name == pkgname and str(item.arch()) == pkgarch:
291 if startx and name.endswith(pkg[1:]):
293 if endx and name.startswith(pkg[:-1]):
298 def deselectPackage(self, pkg):
299 """collect packages should not be installed"""
300 self.to_deselect.append(pkg)
302 def selectGroup(self, grp, include = ksparser.GROUP_DEFAULT):
304 self.__initialize_zypp()
307 q.addKind(zypp.ResKind.pattern)
308 for pitem in q.queryResults(self.Z.pool()):
309 item = zypp.asKindPattern(pitem)
310 summary = "%s" % item.summary()
311 name = "%s" % item.name()
312 if name == grp or summary == grp:
314 pitem.status().setToBeInstalled (zypp.ResStatus.USER)
318 if include == ksparser.GROUP_REQUIRED:
320 lambda p: self.deselectPackage(p),
321 grp.default_packages.keys())
325 raise CreatorError("Unable to find pattern: %s" % (grp,))
327 def addRepository(self, name,
331 proxy_username = None,
332 proxy_password = None,
339 # TODO: Handle cost attribute for repos
341 if not self.repo_manager:
342 self.__initialize_repo_manager()
344 if not proxy and url:
345 proxy = get_proxy_for(url)
347 repo = RepositoryStub()
351 repo.proxy_username = proxy_username
352 repo.proxy_password = proxy_password
353 repo.ssl_verify = ssl_verify
354 repo.nocache = nocache
355 repo.baseurl.append(url)
358 self.incpkgs[pkg] = name
361 self.excpkgs[pkg] = name
364 repo.mirrorlist = mirrorlist
366 # Enable gpg check for verifying corrupt packages
368 if priority is not None:
369 # priority 0 has issue in RepoInfo.setPriority
370 repo.priority = priority + 1
373 repo_info = zypp.RepoInfo()
374 repo_info.setAlias(repo.name)
375 repo_info.setName(repo.name)
376 repo_info.setEnabled(repo.enabled)
377 repo_info.setAutorefresh(repo.autorefresh)
378 repo_info.setKeepPackages(repo.keeppackages)
379 baseurl = zypp.Url(repo.baseurl[0].full)
381 baseurl.setQueryParam("ssl_verify", "no")
383 host = urlparse.urlparse(proxy)[1]
384 # scheme, host, path, parm, query, frag = urlparse.urlparse(proxy)
386 proxyinfo = host.rsplit(":", 1)
390 if len(proxyinfo) > 1:
393 if proxy.startswith("socks") and len(proxy.rsplit(':', 1)) == 2:
394 host = proxy.rsplit(':', 1)[0]
395 port = proxy.rsplit(':', 1)[1]
397 # parse user/pass from proxy host
398 proxyinfo = host.rsplit("@", 1)
399 if len(proxyinfo) == 2:
401 # Known Issue: If password contains ":", which should be
402 # quoted, for example, use '123%3Aabc' instead of 123:abc
403 userpassinfo = proxyinfo[0].rsplit(":", 1)
404 if len(userpassinfo) == 2:
405 proxy_username = userpassinfo[0]
406 proxy_password = userpassinfo[1]
407 elif len(userpassinfo) == 1:
408 proxy_username = userpassinfo[0]
410 baseurl.setQueryParam ("proxy", host)
411 baseurl.setQueryParam ("proxyport", port)
413 baseurl.setQueryParam ("proxyuser", proxy_username)
415 baseurl.setQueryParam ("proxypass", proxy_password)
417 baseurl.setQueryParam ("proxy", "_none_")
419 self.repos.append(repo)
421 repo_info.addBaseUrl(baseurl)
423 if repo.priority is not None:
424 repo_info.setPriority(repo.priority)
426 # this hack is used to change zypp credential file location
427 # the default one is $HOME/.zypp, which cause conflicts when
428 # installing some basic packages, and the location doesn't
429 # have any interface actually, so use a tricky way anyway
431 if 'HOME' in os.environ:
432 homedir = os.environ['HOME']
433 os.environ['HOME'] = '/'
435 os.environ['HOME'] = '/'
437 self.repo_manager.addRepository(repo_info)
439 # save back the $HOME env
441 os.environ['HOME'] = homedir
443 del os.environ['HOME']
445 self.__build_repo_cache(name)
447 except RuntimeError, e:
448 raise CreatorError(str(e))
450 msger.verbose('repo: %s was added' % name)
453 def installHasFile(self, file):
456 def preInstall(self, pkg):
457 self.pre_pkgs.append(pkg)
459 def checkPackage(self, pkg):
460 self.check_pkgs.append(pkg)
462 def runInstall(self, checksize = 0):
463 os.environ["HOME"] = "/"
464 os.environ["LD_PRELOAD"] = ""
465 self.buildTransaction()
467 todo = zypp.GetResolvablesToInsDel(self.Z.pool())
468 installed_pkgs = todo._toInstall
471 for pitem in installed_pkgs:
472 if not zypp.isKindPattern(pitem) and \
473 not self.inDeselectPackages(pitem):
474 item = zypp.asKindPackage(pitem)
477 if item.name() in self.check_pkgs:
478 self.check_pkgs.remove(item.name())
480 if not self.install_debuginfo or str(item.arch()) == "noarch":
483 dipkg = self._zyppQueryPackage("%s-debuginfo" % item.name())
485 ditem = zypp.asKindPackage(dipkg)
488 msger.warning("No debuginfo rpm found for: %s" \
492 raise CreatorError('Packages absent in image: %s' % ','.join(self.check_pkgs))
494 # record all pkg and the content
495 localpkgs = self.localpkgs.keys()
498 if pkg.name() in localpkgs:
499 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
500 pkg_long_name = misc.RPM_FMT % {
503 'version': hdr['version'],
504 'release': hdr['release']
506 license = hdr['license']
509 pkg_long_name = misc.RPM_FMT % {
512 'version': pkg.edition().version(),
513 'release': pkg.edition().release()
516 license = pkg.license()
518 if license in self.__pkgs_license.keys():
519 self.__pkgs_license[license].append(pkg_long_name)
521 self.__pkgs_license[license] = [pkg_long_name]
523 total_count = len(dlpkgs)
525 download_total_size = sum(map(lambda x: int(x.downloadSize()), dlpkgs))
526 localpkgs = self.localpkgs.keys()
528 msger.info("Checking packages cached ...")
530 # Check if it is cached locally
531 if po.name() in localpkgs:
534 local = self.getLocalPkgPath(po)
535 name = str(po.repoInfo().name())
537 repo = filter(lambda r: r.name == name, self.repos)[0]
540 nocache = repo.nocache if repo else False
542 if os.path.exists(local):
543 if nocache or self.checkPkg(local) !=0:
546 download_total_size -= int(po.downloadSize())
548 cache_avail_size = misc.get_filesystem_avail(self.cachedir)
549 if cache_avail_size < download_total_size:
550 raise CreatorError("No enough space used for downloading.")
552 # record the total size of installed pkgs
553 install_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
554 # check needed size before actually download and install
556 # FIXME: for multiple partitions for loop type, check fails
557 # skip the check temporarily
558 #if checksize and install_total_size > checksize:
559 # raise CreatorError("No enough space used for installing, "
560 # "please resize partition size in ks file")
562 download_count = total_count - cached_count
563 msger.info("Packages: %d Total, %d Cached, %d Missed" \
564 % (total_count, cached_count, download_count))
567 if download_count > 0:
568 msger.info("Downloading packages ...")
569 self.downloadPkgs(dlpkgs, download_count)
570 except CreatorError, e:
571 raise CreatorError("Package download failed: %s" %(e,))
574 self.installPkgs(dlpkgs)
575 except (RepoError, RpmError):
578 raise CreatorError("Package installation failed: %s" % (e,))
580 def getVcsInfo(self):
581 if self.__pkgs_vcsinfo:
585 self.__initialize_transaction()
587 mi = self.ts.dbMatch()
589 lname = misc.RPM_FMT % {
592 'version': hdr['version'],
593 'release': hdr['release']
596 self.__pkgs_vcsinfo[lname] = hdr['VCS']
598 # if rpm not support VCS, set to None
599 self.__pkgs_vcsinfo[lname] = None
601 return self.__pkgs_vcsinfo
603 def getAllContent(self):
604 if self.__pkgs_content:
605 return self.__pkgs_content
608 self.__initialize_transaction()
610 mi = self.ts.dbMatch()
612 lname = misc.RPM_FMT % {
615 'version': hdr['version'],
616 'release': hdr['release']
618 self.__pkgs_content[lname] = hdr['FILENAMES']
620 return self.__pkgs_content
622 def getPkgsLicense(self):
623 return self.__pkgs_license
625 def getFilelist(self, pkgname):
630 self.__initialize_transaction()
632 mi = self.ts.dbMatch('name', pkgname)
634 return header['FILENAMES']
636 def __initialize_repo_manager(self):
637 if self.repo_manager:
640 # Clean up repo metadata
641 shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
642 shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
643 shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
645 zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
646 | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
647 | zypp.KeyRing.ACCEPT_UNKNOWNKEY
648 | zypp.KeyRing.TRUST_KEY_TEMPORARILY
651 self.repo_manager_options = \
652 zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
654 self.repo_manager_options.knownReposPath = \
655 zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
657 self.repo_manager_options.repoCachePath = \
658 zypp.Pathname(self.cachedir)
660 self.repo_manager_options.repoRawCachePath = \
661 zypp.Pathname(self.cachedir + "/raw")
663 self.repo_manager_options.repoSolvCachePath = \
664 zypp.Pathname(self.cachedir + "/solv")
666 self.repo_manager_options.repoPackagesCachePath = \
667 zypp.Pathname(self.cachedir + "/packages")
669 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
671 def __build_repo_cache(self, name):
672 repo = self.repo_manager.getRepositoryInfo(name)
673 if self.repo_manager.isCached(repo) or not repo.enabled():
676 msger.info('Refreshing repository: %s ...' % name)
677 self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
679 def __initialize_zypp(self):
683 zconfig = zypp.ZConfig_instance()
685 # Set system architecture
687 zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
689 msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
691 # repoPackagesCachePath is corrected by this
692 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
693 repos = self.repo_manager.knownRepositories()
695 if not repo.enabled():
697 self.repo_manager.loadFromCache(repo)
699 self.Z = zypp.ZYppFactory_instance().getZYpp()
700 self.Z.initializeTarget(zypp.Pathname(self.instroot))
701 self.Z.target().load()
703 def buildTransaction(self):
704 if not self.Z.resolver().resolvePool():
705 probs = self.Z.resolver().problems()
707 for problem in probs:
708 msger.warning("repo problem: %s, %s" \
709 % (problem.description().decode("utf-8"),
710 problem.details().decode("utf-8")))
712 raise RepoError("found %d resolver problem, abort!" \
715 def getLocalPkgPath(self, po):
716 repoinfo = po.repoInfo()
717 cacheroot = repoinfo.packagesPath()
718 location = po.location()
719 rpmpath = str(location.filename())
720 pkgpath = "%s/%s" % (cacheroot, os.path.basename(rpmpath))
723 def installLocal(self, pkg, po=None, updateonly=False):
725 self.__initialize_transaction()
727 solvfile = "%s/.solv" % (self.cachedir)
729 rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"),
732 f = open(solvfile, "w+")
736 warnmsg = self.repo_manager.loadSolvFile(solvfile,
737 os.path.basename(pkg))
739 msger.warning(warnmsg)
743 msger.warning('Can not get %s solv data.' % pkg)
745 hdr = rpmmisc.readRpmHeader(self.ts, pkg)
746 arch = zypp.Arch(hdr['arch'])
747 sysarch = zypp.Arch(self.target_arch)
749 if arch.compatible_with (sysarch):
750 pkgname = hdr['name']
751 self.localpkgs[pkgname] = pkg
752 self.selectPackage(pkgname)
753 msger.info("Marking %s to be installed" % (pkg))
756 msger.warning("Cannot add package %s to transaction. "
757 "Not a compatible architecture: %s" \
758 % (pkg, hdr['arch']))
760 def downloadPkgs(self, package_objects, count):
761 localpkgs = self.localpkgs.keys()
762 progress_obj = TextProgress(count)
764 for po in package_objects:
765 if po.name() in localpkgs:
768 filename = self.getLocalPkgPath(po)
769 if os.path.exists(filename):
770 if self.checkPkg(filename) == 0:
773 dirn = os.path.dirname(filename)
774 if not os.path.exists(dirn):
777 url = self.get_url(po)
778 proxies = self.get_proxies(po)
781 filename = myurlgrab(url.full, filename, proxies, progress_obj)
786 def preinstallPkgs(self):
788 self.__initialize_transaction()
791 cb = rpmmisc.RPMInstallCallback(self.ts_pre)
792 cb.headmsg = "Preinstall"
793 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
795 # start to catch stderr output from librpm
796 msger.enable_logstderr(installlogfile)
798 errors = self.ts_pre.run(cb.callback, '')
800 msger.disable_logstderr()
801 self.ts_pre.closeDB()
804 if errors is not None:
806 msger.warning('scriptlet or other non-fatal errors occurred '
807 'during transaction.')
812 raise RepoError('Could not run transaction.')
814 def installPkgs(self, package_objects):
816 self.__initialize_transaction()
819 self._cleanupRpmdbLocks(self.instroot)
820 self._cleanupZyppJunk(self.instroot)
823 for flag in self.probFilterFlags:
825 self.ts.setProbFilter(probfilter)
826 self.ts_pre.setProbFilter(probfilter)
828 localpkgs = self.localpkgs.keys()
830 for po in package_objects:
832 if pkgname in localpkgs:
833 rpmpath = self.localpkgs[pkgname]
835 rpmpath = self.getLocalPkgPath(po)
837 if not os.path.exists(rpmpath):
838 # Maybe it is a local repo
839 rpmuri = self.get_url(po)
840 if rpmuri.startswith("file:/"):
843 if not os.path.exists(rpmpath):
844 raise RpmError("Error: %s doesn't exist" % rpmpath)
846 h = rpmmisc.readRpmHeader(self.ts, rpmpath)
848 if pkgname in self.pre_pkgs:
849 msger.verbose("pre-install package added: %s" % pkgname)
850 self.ts_pre.addInstall(h, rpmpath, 'u')
852 self.ts.addInstall(h, rpmpath, 'u')
854 unresolved_dependencies = self.ts.check()
855 if not unresolved_dependencies:
857 self.preinstallPkgs()
860 cb = rpmmisc.RPMInstallCallback(self.ts)
861 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
863 # start to catch stderr output from librpm
864 msger.enable_logstderr(installlogfile)
866 errors = self.ts.run(cb.callback, '')
868 msger.disable_logstderr()
872 if errors is not None:
874 msger.warning('scriptlet or other non-fatal errors occurred '
875 'during transaction.')
880 raise RepoError('Could not run transaction.')
883 for pkg, need, needflags, sense, key in unresolved_dependencies:
884 package = '-'.join(pkg)
886 if needflags == rpm.RPMSENSE_LESS:
887 deppkg = ' < '.join(need)
888 elif needflags == rpm.RPMSENSE_EQUAL:
889 deppkg = ' = '.join(need)
890 elif needflags == rpm.RPMSENSE_GREATER:
891 deppkg = ' > '.join(need)
893 deppkg = '-'.join(need)
895 if sense == rpm.RPMDEP_SENSE_REQUIRES:
896 msger.warning("[%s] Requires [%s], which is not provided" \
899 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
900 msger.warning("[%s] Conflicts with [%s]" % (package, deppkg))
902 raise RepoError("Unresolved dependencies, transaction failed.")
904 def __initialize_transaction(self):
906 self.ts = rpm.TransactionSet(self.instroot)
907 # Set to not verify DSA signatures.
908 self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
911 self.ts_pre = rpm.TransactionSet(self.instroot)
912 # Just unpack the files, don't run scripts
913 self.ts_pre.setFlags(rpm.RPMTRANS_FLAG_ALLFILES | rpm.RPMTRANS_FLAG_NOSCRIPTS)
914 # Set to not verify DSA signatures.
915 self.ts_pre.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
917 def checkPkg(self, pkg):
919 if not os.path.exists(pkg):
921 ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
923 msger.warning("package %s is damaged: %s" \
924 % (os.path.basename(pkg), pkg))
928 def _add_prob_flags(self, *flags):
930 if flag not in self.probFilterFlags:
931 self.probFilterFlags.append(flag)
933 def get_proxies(self, pobj):
939 repoinfo = pobj.repoInfo()
940 reponame = "%s" % repoinfo.name()
941 repos = filter(lambda r: r.name == reponame, self.repos)
942 repourl = str(repoinfo.baseUrls()[0])
945 proxy = repos[0].proxy
947 proxy = get_proxy_for(repourl)
949 proxies = {str(repourl.split(':')[0]): str(proxy)}
953 def get_url(self, pobj):
957 name = str(pobj.repoInfo().name())
959 repo = filter(lambda r: r.name == name, self.repos)[0]
963 location = pobj.location()
964 location = str(location.filename())
965 if location.startswith("./"):
966 location = location[2:]
968 return repo.baseurl[0].join(location)
970 def package_url(self, pkgname):
975 (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
976 (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
977 return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
980 self.__initialize_zypp()
983 q.addKind(zypp.ResKind.package)
985 q.addAttribute(zypp.SolvAttr.name, pkgname)
986 items = sorted(q.queryResults(self.Z.pool()),
987 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
991 item = zypp.asKindPackage(items[0])
992 url = self.get_url(item)
993 proxies = self.get_proxies(item)
994 return (url, proxies)