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.addAttribute(zypp.SolvAttr.obsoletes, pkg)
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.name())
238 if arch == str(item.arch()):
239 item.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.name())
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 scheme, host, path, parm, query, frag = urlparse.urlparse(proxy)
385 proxyinfo = host.rsplit(":", 1)
389 if len(proxyinfo) > 1:
392 if proxy.startswith("socks") and len(proxy.rsplit(':', 1)) == 2:
393 host = proxy.rsplit(':', 1)[0]
394 port = proxy.rsplit(':', 1)[1]
396 # parse user/pass from proxy host
397 proxyinfo = host.rsplit("@", 1)
398 if len(proxyinfo) == 2:
400 # Known Issue: If password contains ":", which should be
401 # quoted, for example, use '123%3Aabc' instead of 123:abc
402 userpassinfo = proxyinfo[0].rsplit(":", 1)
403 if len(userpassinfo) == 2:
404 proxy_username = userpassinfo[0]
405 proxy_password = userpassinfo[1]
406 elif len(userpassinfo) == 1:
407 proxy_username = userpassinfo[0]
409 baseurl.setQueryParam ("proxy", host)
410 baseurl.setQueryParam ("proxyport", port)
412 baseurl.setQueryParam ("proxyuser", proxy_username)
414 baseurl.setQueryParam ("proxypass", proxy_password)
416 baseurl.setQueryParam ("proxy", "_none_")
418 self.repos.append(repo)
420 repo_info.addBaseUrl(baseurl)
422 if repo.priority is not None:
423 repo_info.setPriority(repo.priority)
425 # this hack is used to change zypp credential file location
426 # the default one is $HOME/.zypp, which cause conflicts when
427 # installing some basic packages, and the location doesn't
428 # have any interface actually, so use a tricky way anyway
430 if 'HOME' in os.environ:
431 homedir = os.environ['HOME']
432 os.environ['HOME'] = '/'
434 os.environ['HOME'] = '/'
436 self.repo_manager.addRepository(repo_info)
438 # save back the $HOME env
440 os.environ['HOME'] = homedir
442 del os.environ['HOME']
444 self.__build_repo_cache(name)
446 except RuntimeError, e:
447 raise CreatorError(str(e))
449 msger.verbose('repo: %s was added' % name)
452 def installHasFile(self, file):
455 def preInstall(self, pkg):
456 self.pre_pkgs.append(pkg)
458 def checkPackage(self, pkg):
459 self.check_pkgs.append(pkg)
461 def runInstall(self, checksize = 0):
462 os.environ["HOME"] = "/"
463 os.environ["LD_PRELOAD"] = ""
464 self.buildTransaction()
466 todo = zypp.GetResolvablesToInsDel(self.Z.pool())
467 installed_pkgs = todo._toInstall
470 for pitem in installed_pkgs:
471 if not zypp.isKindPattern(pitem) and \
472 not self.inDeselectPackages(pitem):
473 item = zypp.asKindPackage(pitem)
476 if item.name() in self.check_pkgs:
477 self.check_pkgs.remove(item.name())
479 if not self.install_debuginfo or str(item.arch()) == "noarch":
482 dipkg = self._zyppQueryPackage("%s-debuginfo" % item.name())
484 ditem = zypp.asKindPackage(dipkg)
487 msger.warning("No debuginfo rpm found for: %s" \
491 raise CreatorError('Packages absent in image: %s' % ','.join(self.check_pkgs))
493 # record all pkg and the content
494 localpkgs = self.localpkgs.keys()
497 if pkg.name() in localpkgs:
498 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
499 pkg_long_name = misc.RPM_FMT % {
502 'version': hdr['version'],
503 'release': hdr['release']
505 license = hdr['license']
508 pkg_long_name = misc.RPM_FMT % {
511 'version': pkg.edition().version(),
512 'release': pkg.edition().release()
515 license = pkg.license()
517 if license in self.__pkgs_license.keys():
518 self.__pkgs_license[license].append(pkg_long_name)
520 self.__pkgs_license[license] = [pkg_long_name]
522 total_count = len(dlpkgs)
524 download_total_size = sum(map(lambda x: int(x.downloadSize()), dlpkgs))
525 localpkgs = self.localpkgs.keys()
527 msger.info("Checking packages cached ...")
529 # Check if it is cached locally
530 if po.name() in localpkgs:
533 local = self.getLocalPkgPath(po)
534 name = str(po.repoInfo().name())
536 repo = filter(lambda r: r.name == name, self.repos)[0]
539 nocache = repo.nocache if repo else False
541 if os.path.exists(local):
542 if nocache or self.checkPkg(local) !=0:
545 download_total_size -= int(po.downloadSize())
547 cache_avail_size = misc.get_filesystem_avail(self.cachedir)
548 if cache_avail_size < download_total_size:
549 raise CreatorError("No enough space used for downloading.")
551 # record the total size of installed pkgs
552 install_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
553 # check needed size before actually download and install
555 # FIXME: for multiple partitions for loop type, check fails
556 # skip the check temporarily
557 #if checksize and install_total_size > checksize:
558 # raise CreatorError("No enough space used for installing, "
559 # "please resize partition size in ks file")
561 download_count = total_count - cached_count
562 msger.info("Packages: %d Total, %d Cached, %d Missed" \
563 % (total_count, cached_count, download_count))
566 if download_count > 0:
567 msger.info("Downloading packages ...")
568 self.downloadPkgs(dlpkgs, download_count)
570 self.installPkgs(dlpkgs)
572 except (RepoError, RpmError):
575 raise CreatorError("Package installation failed: %s" % (e,))
577 def getVcsInfo(self):
578 if self.__pkgs_vcsinfo:
582 self.__initialize_transaction()
584 mi = self.ts.dbMatch()
586 lname = misc.RPM_FMT % {
589 'version': hdr['version'],
590 'release': hdr['release']
593 self.__pkgs_vcsinfo[lname] = hdr['VCS']
595 # if rpm not support VCS, set to None
596 self.__pkgs_vcsinfo[lname] = None
598 return self.__pkgs_vcsinfo
600 def getAllContent(self):
601 if self.__pkgs_content:
602 return self.__pkgs_content
605 self.__initialize_transaction()
607 mi = self.ts.dbMatch()
609 lname = misc.RPM_FMT % {
612 'version': hdr['version'],
613 'release': hdr['release']
615 self.__pkgs_content[lname] = hdr['FILENAMES']
617 return self.__pkgs_content
619 def getPkgsLicense(self):
620 return self.__pkgs_license
622 def getFilelist(self, pkgname):
627 self.__initialize_transaction()
629 mi = self.ts.dbMatch('name', pkgname)
631 return header['FILENAMES']
633 def __initialize_repo_manager(self):
634 if self.repo_manager:
637 # Clean up repo metadata
638 shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
639 shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
640 shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
642 zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
643 | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
644 | zypp.KeyRing.ACCEPT_UNKNOWNKEY
645 | zypp.KeyRing.TRUST_KEY_TEMPORARILY
648 self.repo_manager_options = \
649 zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
651 self.repo_manager_options.knownReposPath = \
652 zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
654 self.repo_manager_options.repoCachePath = \
655 zypp.Pathname(self.cachedir)
657 self.repo_manager_options.repoRawCachePath = \
658 zypp.Pathname(self.cachedir + "/raw")
660 self.repo_manager_options.repoSolvCachePath = \
661 zypp.Pathname(self.cachedir + "/solv")
663 self.repo_manager_options.repoPackagesCachePath = \
664 zypp.Pathname(self.cachedir + "/packages")
666 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
668 def __build_repo_cache(self, name):
669 repo = self.repo_manager.getRepositoryInfo(name)
670 if self.repo_manager.isCached(repo) or not repo.enabled():
673 msger.info('Refreshing repository: %s ...' % name)
674 self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
676 def __initialize_zypp(self):
680 zconfig = zypp.ZConfig_instance()
682 # Set system architecture
684 zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
686 msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
688 # repoPackagesCachePath is corrected by this
689 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
690 repos = self.repo_manager.knownRepositories()
692 if not repo.enabled():
694 self.repo_manager.loadFromCache(repo)
696 self.Z = zypp.ZYppFactory_instance().getZYpp()
697 self.Z.initializeTarget(zypp.Pathname(self.instroot))
698 self.Z.target().load()
700 def buildTransaction(self):
701 if not self.Z.resolver().resolvePool():
702 probs = self.Z.resolver().problems()
704 for problem in probs:
705 msger.warning("repo problem: %s, %s" \
706 % (problem.description().decode("utf-8"),
707 problem.details().decode("utf-8")))
709 raise RepoError("found %d resolver problem, abort!" \
712 def getLocalPkgPath(self, po):
713 repoinfo = po.repoInfo()
714 cacheroot = repoinfo.packagesPath()
715 location= po.location()
716 rpmpath = str(location.filename())
717 pkgpath = "%s/%s" % (cacheroot, os.path.basename(rpmpath))
720 def installLocal(self, pkg, po=None, updateonly=False):
722 self.__initialize_transaction()
724 solvfile = "%s/.solv" % (self.cachedir)
726 rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"),
729 f = open(solvfile, "w+")
733 warnmsg = self.repo_manager.loadSolvFile(solvfile,
734 os.path.basename(pkg))
736 msger.warning(warnmsg)
740 msger.warning('Can not get %s solv data.' % pkg)
742 hdr = rpmmisc.readRpmHeader(self.ts, pkg)
743 arch = zypp.Arch(hdr['arch'])
744 sysarch = zypp.Arch(self.target_arch)
746 if arch.compatible_with (sysarch):
747 pkgname = hdr['name']
748 self.localpkgs[pkgname] = pkg
749 self.selectPackage(pkgname)
750 msger.info("Marking %s to be installed" % (pkg))
753 msger.warning("Cannot add package %s to transaction. "
754 "Not a compatible architecture: %s" \
755 % (pkg, hdr['arch']))
757 def downloadPkgs(self, package_objects, count):
758 localpkgs = self.localpkgs.keys()
759 progress_obj = TextProgress(count)
761 for po in package_objects:
762 if po.name() in localpkgs:
765 filename = self.getLocalPkgPath(po)
766 if os.path.exists(filename):
767 if self.checkPkg(filename) == 0:
770 dirn = os.path.dirname(filename)
771 if not os.path.exists(dirn):
774 url = self.get_url(po)
775 proxies = self.get_proxies(po)
778 filename = myurlgrab(url.full, filename, proxies, progress_obj)
783 def preinstallPkgs(self):
785 self.__initialize_transaction()
788 cb = rpmmisc.RPMInstallCallback(self.ts_pre)
789 cb.headmsg = "Preinstall"
790 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
792 # start to catch stderr output from librpm
793 msger.enable_logstderr(installlogfile)
795 errors = self.ts_pre.run(cb.callback, '')
797 msger.disable_logstderr()
798 self.ts_pre.closeDB()
801 if errors is not None:
803 msger.warning('scriptlet or other non-fatal errors occurred '
804 'during transaction.')
809 raise RepoError('Could not run transaction.')
811 def installPkgs(self, package_objects):
813 self.__initialize_transaction()
816 self._cleanupRpmdbLocks(self.instroot)
817 self._cleanupZyppJunk(self.instroot)
820 for flag in self.probFilterFlags:
822 self.ts.setProbFilter(probfilter)
823 self.ts_pre.setProbFilter(probfilter)
825 localpkgs = self.localpkgs.keys()
827 for po in package_objects:
829 if pkgname in localpkgs:
830 rpmpath = self.localpkgs[pkgname]
832 rpmpath = self.getLocalPkgPath(po)
834 if not os.path.exists(rpmpath):
835 # Maybe it is a local repo
836 rpmuri = self.get_url(po)
837 if rpmuri.startswith("file:/"):
840 if not os.path.exists(rpmpath):
841 raise RpmError("Error: %s doesn't exist" % rpmpath)
843 h = rpmmisc.readRpmHeader(self.ts, rpmpath)
845 if pkgname in self.pre_pkgs:
846 msger.verbose("pre-install package added: %s" % pkgname)
847 self.ts_pre.addInstall(h, rpmpath, 'u')
849 self.ts.addInstall(h, rpmpath, 'u')
851 unresolved_dependencies = self.ts.check()
852 if not unresolved_dependencies:
854 self.preinstallPkgs()
857 cb = rpmmisc.RPMInstallCallback(self.ts)
858 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
860 # start to catch stderr output from librpm
861 msger.enable_logstderr(installlogfile)
863 errors = self.ts.run(cb.callback, '')
865 msger.disable_logstderr()
869 if errors is not None:
871 msger.warning('scriptlet or other non-fatal errors occurred '
872 'during transaction.')
877 raise RepoError('Could not run transaction.')
880 for pkg, need, needflags, sense, key in unresolved_dependencies:
881 package = '-'.join(pkg)
883 if needflags == rpm.RPMSENSE_LESS:
884 deppkg = ' < '.join(need)
885 elif needflags == rpm.RPMSENSE_EQUAL:
886 deppkg = ' = '.join(need)
887 elif needflags == rpm.RPMSENSE_GREATER:
888 deppkg = ' > '.join(need)
890 deppkg = '-'.join(need)
892 if sense == rpm.RPMDEP_SENSE_REQUIRES:
893 msger.warning("[%s] Requires [%s], which is not provided" \
896 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
897 msger.warning("[%s] Conflicts with [%s]" %(package,deppkg))
899 raise RepoError("Unresolved dependencies, transaction failed.")
901 def __initialize_transaction(self):
903 self.ts = rpm.TransactionSet(self.instroot)
904 # Set to not verify DSA signatures.
905 self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
908 self.ts_pre = rpm.TransactionSet(self.instroot)
909 # Just unpack the files, don't run scripts
910 self.ts_pre.setFlags(rpm.RPMTRANS_FLAG_ALLFILES | rpm.RPMTRANS_FLAG_NOSCRIPTS)
911 # Set to not verify DSA signatures.
912 self.ts_pre.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
914 def checkPkg(self, pkg):
916 if not os.path.exists(pkg):
918 ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
920 msger.warning("package %s is damaged: %s" \
921 % (os.path.basename(pkg), pkg))
925 def _add_prob_flags(self, *flags):
927 if flag not in self.probFilterFlags:
928 self.probFilterFlags.append(flag)
930 def get_proxies(self, pobj):
936 repoinfo = pobj.repoInfo()
937 reponame = "%s" % repoinfo.name()
938 repos = filter(lambda r: r.name == reponame, self.repos)
939 repourl = str(repoinfo.baseUrls()[0])
942 proxy = repos[0].proxy
944 proxy = get_proxy_for(repourl)
946 proxies = {str(repourl.split(':')[0]): str(proxy)}
950 def get_url(self, pobj):
954 name = str(pobj.repoInfo().name())
956 repo = filter(lambda r: r.name == name, self.repos)[0]
960 location = pobj.location()
961 location = str(location.filename())
962 if location.startswith("./"):
963 location = location[2:]
965 return repo.baseurl[0].join(location)
967 def package_url(self, pkgname):
972 (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
973 (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
974 return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
977 self.__initialize_zypp()
980 q.addKind(zypp.ResKind.package)
982 q.addAttribute(zypp.SolvAttr.name, pkgname)
983 items = sorted(q.queryResults(self.Z.pool()),
984 cmp=lambda x,y: cmpEVR(zypp.asKindPackage(x), zypp.asKindPackage(y)),
988 item = zypp.asKindPackage(items[0])
989 url = self.get_url(item)
990 proxies = self.get_proxies(item)
991 return (url, proxies)