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 repo.meego.com/tools")
31 from mic.kickstart import ksparser
32 from mic.utils import misc, rpmmisc, runner, fs_related
33 from mic.utils.proxy import get_proxy_for
34 from mic.utils.errors import CreatorError, RepoError, RpmError
35 from mic.imager.baseimager import BaseImageCreator
41 self.mirrorlist = None
43 self.proxy_username = None
44 self.proxy_password = None
47 self.autorefresh = True
48 self.keeppackages = True
51 from mic.pluginbase import BackendPlugin
52 class Zypp(BackendPlugin):
55 def __init__(self, target_arch, instroot, cachedir):
56 self.cachedir = cachedir
57 self.instroot = instroot
58 self.target_arch = target_arch
60 self.__pkgs_license = {}
61 self.__pkgs_content = {}
65 self.repo_manager = None
66 self.repo_manager_options = None
73 self.probFilterFlags = [ rpm.RPMPROB_FILTER_OLDPACKAGE,
74 rpm.RPMPROB_FILTER_REPLACEPKG ]
76 self.has_prov_query = True
78 def doFileLogSetup(self, uid, logfile):
79 # don't do the file log for the livecd as it can lead to open fds
80 # being left and an inability to clean up after ourself
97 if not os.path.exists("/etc/fedora-release") and \
98 not os.path.exists("/etc/meego-release"):
99 for i in range(3, os.sysconf("SC_OPEN_MAX")):
108 def _cleanupRpmdbLocks(self, installroot):
109 # cleans up temporary files left by bdb so that differing
110 # versions of rpm don't cause problems
112 for f in glob.glob(installroot + "/var/lib/rpm/__db*"):
116 self._cleanupRpmdbLocks(self.instroot)
118 def whatObsolete(self, pkg):
119 query = zypp.PoolQuery()
120 query.addKind(zypp.ResKind.package)
121 query.addAttribute(zypp.SolvAttr.obsoletes, pkg)
122 query.setMatchExact()
123 for pi in query.queryResults(self.Z.pool()):
127 def _splitPkgString(self, pkg):
128 sp = pkg.rsplit(".",1)
133 sysarch = zypp.Arch(self.target_arch)
134 if not zypp.Arch(arch).compatible_with (sysarch):
139 def selectPackage(self, pkg):
140 """Select a given package or package pattern, can be specified
141 with name.arch or name* or *name
145 self.__initialize_zypp()
147 def markPoolItem(obs, pi):
149 pi.status().setToBeInstalled (zypp.ResStatus.USER)
151 obs.status().setToBeInstalled (zypp.ResStatus.USER)
153 def cmpEVR(ed1, ed2):
154 (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
155 (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
156 return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
159 startx = pkg.startswith("*")
160 endx = pkg.endswith("*")
161 ispattern = startx or endx
162 name, arch = self._splitPkgString(pkg)
165 q.addKind(zypp.ResKind.package)
168 if startx and not endx:
169 pattern = '%s$' % (pkg[1:])
170 if endx and not startx:
171 pattern = '^%s' % (pkg[0:-1])
173 pattern = '%s' % (pkg[1:-1])
175 q.addAttribute(zypp.SolvAttr.name,pattern)
179 q.addAttribute(zypp.SolvAttr.name,name)
183 q.addAttribute(zypp.SolvAttr.name,pkg)
186 q.queryResults(self.Z.pool()),
187 cmp=lambda x,y: cmpEVR(x.edition(), y.edition()),
190 if item.name() in self.excpkgs.keys() and \
191 self.excpkgs[item.name()] == item.repoInfo().name():
193 if item.name() in self.incpkgs.keys() and \
194 self.incpkgs[item.name()] != item.repoInfo().name():
198 obspkg = self.whatObsolete(item.name())
200 if arch == str(item.arch()):
201 item.status().setToBeInstalled (zypp.ResStatus.USER)
203 markPoolItem(obspkg, item)
207 # Can't match using package name, then search from packge
208 # provides infomation
209 if found == False and not ispattern:
210 q.addAttribute(zypp.SolvAttr.provides, pkg)
211 q.addAttribute(zypp.SolvAttr.name,'')
214 q.queryResults(self.Z.pool()),
215 cmp=lambda x,y: cmpEVR(x.edition(), y.edition()),
217 if item.name() in self.excpkgs.keys() and \
218 self.excpkgs[item.name()] == item.repoInfo().name():
220 if item.name() in self.incpkgs.keys() and \
221 self.incpkgs[item.name()] != item.repoInfo().name():
225 obspkg = self.whatObsolete(item.name())
226 markPoolItem(obspkg, item)
232 raise CreatorError("Unable to find package: %s" % (pkg,))
234 def inDeselectPackages(self, item):
235 """check if specified pacakges are in the list of inDeselectPackages
239 for pkg in self.to_deselect:
240 startx = pkg.startswith("*")
241 endx = pkg.endswith("*")
242 ispattern = startx or endx
243 pkgname, pkgarch = self._splitPkgString(pkg)
246 if name == pkgname and str(item.arch()) == pkgarch:
252 if startx and name.endswith(pkg[1:]):
254 if endx and name.startswith(pkg[:-1]):
259 def deselectPackage(self, pkg):
260 """collect packages should not be installed"""
261 self.to_deselect.append(pkg)
263 def selectGroup(self, grp, include = ksparser.GROUP_DEFAULT):
265 self.__initialize_zypp()
268 q.addKind(zypp.ResKind.pattern)
269 for item in q.queryResults(self.Z.pool()):
270 summary = "%s" % item.summary()
271 name = "%s" % item.name()
272 if name == grp or summary == grp:
274 item.status().setToBeInstalled (zypp.ResStatus.USER)
278 if include == ksparser.GROUP_REQUIRED:
280 lambda p: self.deselectPackage(p),
281 grp.default_packages.keys())
285 raise CreatorError("Unable to find pattern: %s" % (grp,))
287 def addRepository(self, name,
291 proxy_username = None,
292 proxy_password = None,
298 # TODO: Handle cost attribute for repos
300 if not self.repo_manager:
301 self.__initialize_repo_manager()
303 if not proxy and url:
304 proxy = get_proxy_for(url)
306 repo = RepositoryStub()
310 repo.proxy_username = proxy_username
311 repo.proxy_password = proxy_password
312 repo.ssl_verify = ssl_verify
313 repo.baseurl.append(url)
316 self.incpkgs[pkg] = name
319 self.excpkgs[pkg] = name
321 # check LICENSE files
322 if not rpmmisc.checkRepositoryEULA(name, repo):
323 msger.warning('skip repo:%s for failed EULA confirmation' % name)
327 repo.mirrorlist = mirrorlist
329 # Enable gpg check for verifying corrupt packages
332 repo.priority = priority
333 self.repos.append(repo)
336 repo_info = zypp.RepoInfo()
337 repo_info.setAlias(repo.name)
338 repo_info.setName(repo.name)
339 repo_info.setEnabled(repo.enabled)
340 repo_info.setAutorefresh(repo.autorefresh)
341 repo_info.setKeepPackages(repo.keeppackages)
342 baseurl = zypp.Url(repo.baseurl[0])
344 baseurl.setQueryParam("ssl_verify", "no")
346 scheme, host, path, parm, query, frag = urlparse.urlparse(proxy)
348 proxyinfo = host.split(":")
352 if len(proxyinfo) > 1:
355 if proxy.startswith("socks") and len(proxy.rsplit(':', 1)) == 2:
356 host = proxy.rsplit(':', 1)[0]
357 port = proxy.rsplit(':', 1)[1]
359 baseurl.setQueryParam ("proxy", host)
360 baseurl.setQueryParam ("proxyport", port)
362 repo_info.addBaseUrl(baseurl)
365 repo_info.setPriority(repo.priority)
367 self.repo_manager.addRepository(repo_info)
369 self.__build_repo_cache(name)
371 except RuntimeError, e:
372 raise CreatorError(str(e))
374 msger.verbose('repo: %s was added' % name)
377 def installHasFile(self, file):
380 def preInstall(self, pkg):
381 self.pre_pkgs.append(pkg)
383 def runInstall(self, checksize = 0):
384 os.environ["HOME"] = "/"
385 self.buildTransaction()
387 todo = zypp.GetResolvablesToInsDel(self.Z.pool())
388 installed_pkgs = todo._toInstall
390 for item in installed_pkgs:
391 if not zypp.isKindPattern(item) and \
392 not self.inDeselectPackages(item):
395 # record all pkg and the content
396 localpkgs = self.localpkgs.keys()
399 if pkg.name() in localpkgs:
400 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
401 pkg_long_name = misc.RPM_FMT % {
404 'ver_rel': '%s-%s' % (hdr['version'],
407 license = hdr['license']
410 pkg_long_name = misc.RPM_FMT % {
413 'ver_rel': pkg.edition(),
416 package = zypp.asKindPackage(pkg)
417 license = package.license()
419 self.__pkgs_content[pkg_long_name] = {} #TBD: to get file list
421 if license in self.__pkgs_license.keys():
422 self.__pkgs_license[license].append(pkg_long_name)
424 self.__pkgs_license[license] = [pkg_long_name]
426 total_count = len(dlpkgs)
428 download_total_size = sum(map(lambda x: int(x.downloadSize()), dlpkgs))
429 localpkgs = self.localpkgs.keys()
431 msger.info("Checking packages cache and packages integrity ...")
433 # Check if it is cached locally
434 if po.name() in localpkgs:
437 local = self.getLocalPkgPath(po)
438 if os.path.exists(local):
439 if self.checkPkg(local) != 0:
442 download_total_size -= int(po.downloadSize())
444 cache_avail_size = misc.get_filesystem_avail(self.cachedir)
445 if cache_avail_size < download_total_size:
446 raise CreatorError("No enough space used for downloading.")
448 # record the total size of installed pkgs
449 install_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
450 # check needed size before actually download and install
452 # FIXME: for multiple partitions for loop type, check fails
453 # skip the check temporarily
454 #if checksize and install_total_size > checksize:
455 # raise CreatorError("No enough space used for installing, "
456 # "please resize partition size in ks file")
458 download_count = total_count - cached_count
459 msger.info("%d packages to be installed, "
460 "%d packages gotten from cache, "
461 "%d packages to be downloaded" \
462 % (total_count, cached_count, download_count))
465 if download_count > 0:
466 msger.info("Downloading packages ...")
467 self.downloadPkgs(dlpkgs, download_count)
469 self.installPkgs(dlpkgs)
471 except (RepoError, RpmError):
474 raise CreatorError("Package installation failed: %s" % (e,))
476 def getAllContent(self):
477 return self.__pkgs_content
479 def getPkgsLicense(self):
480 return self.__pkgs_license
482 def getFilelist(self, pkgname):
487 self.__initialize_transaction()
489 mi = self.ts.dbMatch('name', pkgname)
491 return header['FILENAMES']
493 def __initialize_repo_manager(self):
494 if self.repo_manager:
497 # Clean up repo metadata
498 shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
499 shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
500 shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
502 zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
503 | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
504 | zypp.KeyRing.ACCEPT_UNKNOWNKEY
505 | zypp.KeyRing.TRUST_KEY_TEMPORARILY
508 self.repo_manager_options = \
509 zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
511 self.repo_manager_options.knownReposPath = \
512 zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
514 self.repo_manager_options.repoCachePath = \
515 zypp.Pathname(self.cachedir)
517 self.repo_manager_options.repoRawCachePath = \
518 zypp.Pathname(self.cachedir + "/raw")
520 self.repo_manager_options.repoSolvCachePath = \
521 zypp.Pathname(self.cachedir + "/solv")
523 self.repo_manager_options.repoPackagesCachePath = \
524 zypp.Pathname(self.cachedir + "/packages")
526 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
528 def __build_repo_cache(self, name):
529 repo = self.repo_manager.getRepositoryInfo(name)
530 if self.repo_manager.isCached(repo) or not repo.enabled():
533 msger.info('Refreshing repository: %s ...' % name)
534 self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
536 def __initialize_zypp(self):
540 zconfig = zypp.ZConfig_instance()
542 # Set system architecture
544 zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
546 msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
548 # repoPackagesCachePath is corrected by this
549 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
550 repos = self.repo_manager.knownRepositories()
552 if not repo.enabled():
554 self.repo_manager.loadFromCache(repo)
556 self.Z = zypp.ZYppFactory_instance().getZYpp()
557 self.Z.initializeTarget(zypp.Pathname(self.instroot))
558 self.Z.target().load()
560 def buildTransaction(self):
561 if not self.Z.resolver().resolvePool():
562 probs = self.Z.resolver().problems()
564 for problem in probs:
565 msger.warning("repo problem: %s, %s" \
566 % (problem.description().decode("utf-8"),
567 problem.details().decode("utf-8")))
569 raise RepoError("found %d resolver problem, abort!" \
572 def getLocalPkgPath(self, po):
573 repoinfo = po.repoInfo()
574 cacheroot = repoinfo.packagesPath()
575 location= zypp.asKindPackage(po).location()
576 rpmpath = str(location.filename())
577 pkgpath = "%s/%s" % (cacheroot, os.path.basename(rpmpath))
580 def installLocal(self, pkg, po=None, updateonly=False):
582 self.__initialize_transaction()
584 solvfile = "%s/.solv" % (self.cachedir)
586 rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"),
589 f = open(solvfile, "w+")
593 warnmsg = self.repo_manager.loadSolvFile(solvfile,
594 os.path.basename(pkg))
596 msger.warning(warnmsg)
600 msger.warning('Can not get %s solv data.' % pkg)
602 hdr = rpmmisc.readRpmHeader(self.ts, pkg)
603 arch = zypp.Arch(hdr['arch'])
604 sysarch = zypp.Arch(self.target_arch)
606 if arch.compatible_with (sysarch):
607 pkgname = hdr['name']
608 self.localpkgs[pkgname] = pkg
609 self.selectPackage(pkgname)
610 msger.info("Marking %s to be installed" % (pkg))
613 msger.warning("Cannot add package %s to transaction. "
614 "Not a compatible architecture: %s" \
615 % (pkg, hdr['arch']))
617 def downloadPkgs(self, package_objects, count):
618 localpkgs = self.localpkgs.keys()
619 progress_obj = rpmmisc.TextProgress(count)
621 for po in package_objects:
622 if po.name() in localpkgs:
625 filename = self.getLocalPkgPath(po)
626 if os.path.exists(filename):
627 if self.checkPkg(filename) == 0:
630 dirn = os.path.dirname(filename)
631 if not os.path.exists(dirn):
634 baseurl = str(po.repoInfo().baseUrls()[0])
635 index = baseurl.find("?")
637 baseurl = baseurl[:index]
639 proxy = self.get_proxy(po.repoInfo())
642 proxies = {str(proxy.split(":")[0]):str(proxy)}
644 location = zypp.asKindPackage(po).location()
645 location = str(location.filename())
646 if location.startswith("./"):
647 location = location[2:]
649 url = baseurl + "/%s" % location
652 filename = rpmmisc.myurlgrab(url,
660 def preinstallPkgs(self):
662 self.__initialize_transaction()
665 cb = rpmmisc.RPMInstallCallback(self.ts_pre)
666 cb.headmsg = "Preinstall"
667 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
669 # start to catch stderr output from librpm
670 msger.enable_logstderr(installlogfile)
672 errors = self.ts_pre.run(cb.callback, '')
674 msger.disable_logstderr()
675 self.ts_pre.closeDB()
678 if errors is not None:
680 msger.warning('scriptlet or other non-fatal errors occurred '
681 'during transaction.')
686 raise RepoError('Could not run transaction.')
688 def installPkgs(self, package_objects):
690 self.__initialize_transaction()
694 for flag in self.probFilterFlags:
696 self.ts.setProbFilter(probfilter)
697 self.ts_pre.setProbFilter(probfilter)
699 localpkgs = self.localpkgs.keys()
701 for po in package_objects:
703 if pkgname in localpkgs:
704 rpmpath = self.localpkgs[pkgname]
706 rpmpath = self.getLocalPkgPath(po)
708 if not os.path.exists(rpmpath):
709 # Maybe it is a local repo
710 baseurl = str(po.repoInfo().baseUrls()[0])
711 baseurl = baseurl.strip()
713 location = zypp.asKindPackage(po).location()
714 location = str(location.filename())
716 if baseurl.startswith("file:/"):
717 rpmpath = baseurl[5:] + "/%s" % (location)
719 if not os.path.exists(rpmpath):
720 raise RpmError("Error: %s doesn't exist" % rpmpath)
722 h = rpmmisc.readRpmHeader(self.ts, rpmpath)
724 if pkgname in self.pre_pkgs:
725 msger.verbose("pre-install package added: %s" % pkgname)
726 self.ts_pre.addInstall(h, rpmpath, 'u')
728 self.ts.addInstall(h, rpmpath, 'u')
730 unresolved_dependencies = self.ts.check()
731 if not unresolved_dependencies:
733 self.preinstallPkgs()
736 cb = rpmmisc.RPMInstallCallback(self.ts)
737 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
739 # start to catch stderr output from librpm
740 msger.enable_logstderr(installlogfile)
742 errors = self.ts.run(cb.callback, '')
744 msger.disable_logstderr()
748 if errors is not None:
750 msger.warning('scriptlet or other non-fatal errors occurred '
751 'during transaction.')
756 raise RepoError('Could not run transaction.')
759 for pkg, need, needflags, sense, key in unresolved_dependencies:
760 package = '-'.join(pkg)
762 if needflags == rpm.RPMSENSE_LESS:
763 deppkg = ' < '.join(need)
764 elif needflags == rpm.RPMSENSE_EQUAL:
765 deppkg = ' = '.join(need)
766 elif needflags == rpm.RPMSENSE_GREATER:
767 deppkg = ' > '.join(need)
769 deppkg = '-'.join(need)
771 if sense == rpm.RPMDEP_SENSE_REQUIRES:
772 msger.warning("[%s] Requires [%s], which is not provided" \
775 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
776 msger.warning("[%s] Conflicts with [%s]" %(package,deppkg))
778 raise RepoError("Unresolved dependencies, transaction failed.")
780 def __initialize_transaction(self):
782 self.ts = rpm.TransactionSet(self.instroot)
783 # Set to not verify DSA signatures.
784 self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
787 self.ts_pre = rpm.TransactionSet(self.instroot)
788 # Just unpack the files, don't run scripts
789 self.ts_pre.setFlags(rpm.RPMTRANS_FLAG_ALLFILES | rpm.RPMTRANS_FLAG_NOSCRIPTS)
790 # Set to not verify DSA signatures.
791 self.ts_pre.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
793 def checkPkg(self, pkg):
795 if not os.path.exists(pkg):
797 ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
799 msger.warning("package %s is damaged: %s" \
800 % (os.path.basename(pkg), pkg))
804 def _add_prob_flags(self, *flags):
806 if flag not in self.probFilterFlags:
807 self.probFilterFlags.append(flag)
809 def get_proxy(self, repoinfo):
811 reponame = "%s" % repoinfo.name()
812 for repo in self.repos:
813 if repo.name == reponame:
820 repourl = str(repoinfo.baseUrls()[0])
821 return get_proxy_for(repourl)
823 def package_url(self, pkg):
825 def cmpEVR(ed1, ed2):
826 (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
827 (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
828 return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
831 self.__initialize_zypp()
834 q.addKind(zypp.ResKind.package)
836 q.addAttribute(zypp.SolvAttr.name,pkg)
837 items = sorted(q.queryResults(self.Z.pool()),
838 cmp=lambda x,y: cmpEVR(x.edition(), y.edition()),
842 baseurl = items[0].repoInfo().baseUrls()[0]
843 location = zypp.asKindPackage(items[0]).location()
844 return os.path.join(str(baseurl), str(location.filename()))