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
69 self.probFilterFlags = []
73 self.has_prov_query = True
75 def doFileLogSetup(self, uid, logfile):
76 # don't do the file log for the livecd as it can lead to open fds
77 # being left and an inability to clean up after ourself
90 if not os.path.exists("/etc/fedora-release") and \
91 not os.path.exists("/etc/meego-release"):
92 for i in range(3, os.sysconf("SC_OPEN_MAX")):
101 def _cleanupRpmdbLocks(self, installroot):
102 # cleans up temporary files left by bdb so that differing
103 # versions of rpm don't cause problems
105 for f in glob.glob(installroot + "/var/lib/rpm/__db*"):
109 self._cleanupRpmdbLocks(self.instroot)
111 def whatObsolete(self, pkg):
112 query = zypp.PoolQuery()
113 query.addKind(zypp.ResKind.package)
114 query.addAttribute(zypp.SolvAttr.obsoletes, pkg)
115 query.setMatchExact()
116 for pi in query.queryResults(self.Z.pool()):
120 def _splitPkgString(self, pkg):
121 sp = pkg.rsplit(".",1)
126 sysarch = zypp.Arch(self.target_arch)
127 if not zypp.Arch(arch).compatible_with (sysarch):
132 def selectPackage(self, pkg):
133 """Select a given package or package pattern, can be specified
134 with name.arch or name* or *name
138 self.__initialize_zypp()
140 def markPoolItem(obs, pi):
142 pi.status().setToBeInstalled (zypp.ResStatus.USER)
144 obs.status().setToBeInstalled (zypp.ResStatus.USER)
147 startx = pkg.startswith("*")
148 endx = pkg.endswith("*")
149 ispattern = startx or endx
150 name, arch = self._splitPkgString(pkg)
153 q.addKind(zypp.ResKind.package)
156 if startx and not endx:
157 pattern = '%s$' % (pkg[1:])
158 if endx and not startx:
159 pattern = '^%s' % (pkg[0:-1])
161 pattern = '%s' % (pkg[1:-1])
163 q.addAttribute(zypp.SolvAttr.name,pattern)
167 q.addAttribute(zypp.SolvAttr.name,name)
171 q.addAttribute(zypp.SolvAttr.name,pkg)
174 q.queryResults(self.Z.pool()),
175 key=lambda item: str(item.edition()),
178 if item.name() in self.excpkgs.keys() and \
179 self.excpkgs[item.name()] == item.repoInfo().name():
181 if item.name() in self.incpkgs.keys() and \
182 self.incpkgs[item.name()] != item.repoInfo().name():
186 obspkg = self.whatObsolete(item.name())
188 if arch == str(item.arch()):
189 item.status().setToBeInstalled (zypp.ResStatus.USER)
191 markPoolItem(obspkg, item)
195 # Can't match using package name, then search from packge
196 # provides infomation
197 if found == False and not ispattern:
198 q.addAttribute(zypp.SolvAttr.provides, pkg)
199 q.addAttribute(zypp.SolvAttr.name,'')
202 q.queryResults(self.Z.pool()),
203 key=lambda item: str(item.edition()),
205 if item.name() in self.excpkgs.keys() and \
206 self.excpkgs[item.name()] == item.repoInfo().name():
208 if item.name() in self.incpkgs.keys() and \
209 self.incpkgs[item.name()] != item.repoInfo().name():
213 obspkg = self.whatObsolete(item.name())
214 markPoolItem(obspkg, item)
220 raise CreatorError("Unable to find package: %s" % (pkg,))
222 def inDeselectPackages(self, item):
223 """check if specified pacakges are in the list of inDeselectPackages
227 for pkg in self.to_deselect:
228 startx = pkg.startswith("*")
229 endx = pkg.endswith("*")
230 ispattern = startx or endx
231 pkgname, pkgarch = self._splitPkgString(pkg)
234 if name == pkgname and str(item.arch()) == pkgarch:
240 if startx and name.endswith(pkg[1:]):
242 if endx and name.startswith(pkg[:-1]):
247 def deselectPackage(self, pkg):
248 """collect packages should not be installed"""
249 self.to_deselect.append(pkg)
251 def selectGroup(self, grp, include = ksparser.GROUP_DEFAULT):
253 self.__initialize_zypp()
256 q.addKind(zypp.ResKind.pattern)
257 for item in q.queryResults(self.Z.pool()):
258 summary = "%s" % item.summary()
259 name = "%s" % item.name()
260 if name == grp or summary == grp:
262 item.status().setToBeInstalled (zypp.ResStatus.USER)
266 if include == ksparser.GROUP_REQUIRED:
268 lambda p: self.deselectPackage(p),
269 grp.default_packages.keys())
273 raise CreatorError("Unable to find pattern: %s" % (grp,))
275 def addRepository(self, name,
279 proxy_username = None,
280 proxy_password = None,
286 # TODO: Handle cost attribute for repos
288 if not self.repo_manager:
289 self.__initialize_repo_manager()
291 if not proxy and url:
292 proxy = get_proxy_for(url)
294 repo = RepositoryStub()
298 repo.proxy_username = proxy_username
299 repo.proxy_password = proxy_password
300 repo.ssl_verify = ssl_verify
301 repo.baseurl.append(url)
304 self.incpkgs[pkg] = name
307 self.excpkgs[pkg] = name
309 # check LICENSE files
310 if not rpmmisc.checkRepositoryEULA(name, repo):
311 msger.warning('skip repo:%s for failed EULA confirmation' % name)
315 repo.mirrorlist = mirrorlist
317 # Enable gpg check for verifying corrupt packages
320 repo.priority = priority
321 self.repos.append(repo)
324 repo_info = zypp.RepoInfo()
325 repo_info.setAlias(repo.name)
326 repo_info.setName(repo.name)
327 repo_info.setEnabled(repo.enabled)
328 repo_info.setAutorefresh(repo.autorefresh)
329 repo_info.setKeepPackages(repo.keeppackages)
330 baseurl = zypp.Url(repo.baseurl[0])
332 baseurl.setQueryParam("ssl_verify", "no")
334 scheme, host, path, parm, query, frag = urlparse.urlparse(proxy)
336 proxyinfo = host.split(":")
340 if len(proxyinfo) > 1:
343 if proxy.startswith("socks") and len(proxy.rsplit(':', 1)) == 2:
344 host = proxy.rsplit(':', 1)[0]
345 port = proxy.rsplit(':', 1)[1]
347 baseurl.setQueryParam ("proxy", host)
348 baseurl.setQueryParam ("proxyport", port)
350 repo_info.addBaseUrl(baseurl)
353 repo_info.setPriority(repo.priority)
355 self.repo_manager.addRepository(repo_info)
357 self.__build_repo_cache(name)
359 except RuntimeError, e:
360 raise CreatorError(str(e))
362 msger.verbose('repo: %s was added' % name)
365 def installHasFile(self, file):
368 def runInstall(self, checksize = 0):
369 os.environ["HOME"] = "/"
370 self.buildTransaction()
372 todo = zypp.GetResolvablesToInsDel(self.Z.pool())
373 installed_pkgs = todo._toInstall
375 for item in installed_pkgs:
376 if not zypp.isKindPattern(item) and \
377 not self.inDeselectPackages(item):
380 # record all pkg and the content
381 localpkgs = self.localpkgs.keys()
384 if pkg.name() in localpkgs:
385 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
386 pkg_long_name = misc.RPM_FMT % {
389 'ver_rel': '%s-%s' % (hdr['version'],
392 license = hdr['license']
395 pkg_long_name = misc.RPM_FMT % {
398 'ver_rel': pkg.edition(),
401 package = zypp.asKindPackage(pkg)
402 license = package.license()
404 self.__pkgs_content[pkg_long_name] = {} #TBD: to get file list
406 if license in self.__pkgs_license.keys():
407 self.__pkgs_license[license].append(pkg_long_name)
409 self.__pkgs_license[license] = [pkg_long_name]
411 total_count = len(dlpkgs)
413 download_total_size = sum(map(lambda x: int(x.downloadSize()), dlpkgs))
414 localpkgs = self.localpkgs.keys()
416 msger.info("Checking packages cache and packages integrity ...")
418 # Check if it is cached locally
419 if po.name() in localpkgs:
422 local = self.getLocalPkgPath(po)
423 if os.path.exists(local):
424 if self.checkPkg(local) != 0:
427 download_total_size -= int(po.downloadSize())
429 cache_avail_size = misc.get_filesystem_avail(self.cachedir)
430 if cache_avail_size < download_total_size:
431 raise CreatorError("No enough space used for downloading.")
433 # record the total size of installed pkgs
434 install_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
435 # check needed size before actually download and install
436 if checksize and install_total_size > checksize:
437 raise CreatorError("No enough space used for installing, "
438 "please resize partition size in ks file")
440 download_count = total_count - cached_count
441 msger.info("%d packages to be installed, "
442 "%d packages gotten from cache, "
443 "%d packages to be downloaded" \
444 % (total_count, cached_count, download_count))
447 if download_count > 0:
448 msger.info("Downloading packages ...")
449 self.downloadPkgs(dlpkgs, download_count)
451 self.installPkgs(dlpkgs)
454 raise CreatorError("Unable to download from repo : %s" % (e,))
456 raise CreatorError("Unable to install: %s" % (e,))
458 def getAllContent(self):
459 return self.__pkgs_content
461 def getPkgsLicense(self):
462 return self.__pkgs_license
464 def __initialize_repo_manager(self):
465 if self.repo_manager:
468 # Clean up repo metadata
469 shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
470 shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
471 shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
473 zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
474 | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
475 | zypp.KeyRing.ACCEPT_UNKNOWNKEY
476 | zypp.KeyRing.TRUST_KEY_TEMPORARILY
479 self.repo_manager_options = \
480 zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
482 self.repo_manager_options.knownReposPath = \
483 zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
485 self.repo_manager_options.repoCachePath = \
486 zypp.Pathname(self.cachedir)
488 self.repo_manager_options.repoRawCachePath = \
489 zypp.Pathname(self.cachedir + "/raw")
491 self.repo_manager_options.repoSolvCachePath = \
492 zypp.Pathname(self.cachedir + "/solv")
494 self.repo_manager_options.repoPackagesCachePath = \
495 zypp.Pathname(self.cachedir + "/packages")
497 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
499 def __build_repo_cache(self, name):
500 repo = self.repo_manager.getRepositoryInfo(name)
501 if self.repo_manager.isCached(repo) or not repo.enabled():
504 msger.info('Refreshing repository: %s ...' % name)
505 self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
507 def __initialize_zypp(self):
511 zconfig = zypp.ZConfig_instance()
513 # Set system architecture
515 zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
517 msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
519 # repoPackagesCachePath is corrected by this
520 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
521 repos = self.repo_manager.knownRepositories()
523 if not repo.enabled():
525 self.repo_manager.loadFromCache(repo)
527 self.Z = zypp.ZYppFactory_instance().getZYpp()
528 self.Z.initializeTarget(zypp.Pathname(self.instroot))
529 self.Z.target().load()
531 def buildTransaction(self):
532 if not self.Z.resolver().resolvePool():
533 probs = self.Z.resolver().problems()
535 for problem in probs:
536 msger.warning("repo problem: %s, %s" \
537 % (problem.description().decode("utf-8"),
538 problem.details().decode("utf-8")))
540 raise RepoError("found %d resolver problem, abort!" \
543 def getLocalPkgPath(self, po):
544 repoinfo = po.repoInfo()
545 cacheroot = repoinfo.packagesPath()
546 location= zypp.asKindPackage(po).location()
547 rpmpath = str(location.filename())
548 pkgpath = "%s/%s" % (cacheroot, rpmpath)
551 def installLocal(self, pkg, po=None, updateonly=False):
553 self.__initialize_transaction()
555 solvfile = "%s/.solv" % (self.cachedir)
557 rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"),
560 f = open(solvfile, "w+")
564 warnmsg = self.repo_manager.loadSolvFile(solvfile,
565 os.path.basename(pkg))
567 msger.warning(warnmsg)
571 msger.warning('Can not get %s solv data.' % pkg)
573 hdr = rpmmisc.readRpmHeader(self.ts, pkg)
574 arch = zypp.Arch(hdr['arch'])
575 sysarch = zypp.Arch(self.target_arch)
577 if arch.compatible_with (sysarch):
578 pkgname = hdr['name']
579 self.localpkgs[pkgname] = pkg
580 self.selectPackage(pkgname)
581 msger.info("Marking %s to be installed" % (pkg))
584 msger.warning("Cannot add package %s to transaction. "
585 "Not a compatible architecture: %s" \
586 % (pkg, hdr['arch']))
588 def downloadPkgs(self, package_objects, count):
589 localpkgs = self.localpkgs.keys()
590 progress_obj = rpmmisc.TextProgress(count)
592 for po in package_objects:
593 if po.name() in localpkgs:
596 filename = self.getLocalPkgPath(po)
597 if os.path.exists(filename):
598 if self.checkPkg(filename) == 0:
601 dirn = os.path.dirname(filename)
602 if not os.path.exists(dirn):
605 baseurl = str(po.repoInfo().baseUrls()[0])
606 index = baseurl.find("?")
608 baseurl = baseurl[:index]
610 proxy = self.get_proxy(po.repoInfo())
613 proxies = {str(proxy.split(":")[0]):str(proxy)}
615 location = zypp.asKindPackage(po).location()
616 location = str(location.filename())
617 if location.startswith("./"):
618 location = location[2:]
620 url = baseurl + "/%s" % location
623 filename = rpmmisc.myurlgrab(url,
631 def installPkgs(self, package_objects):
633 self.__initialize_transaction()
637 for flag in self.probFilterFlags:
639 self.ts.setProbFilter(probfilter)
641 localpkgs = self.localpkgs.keys()
643 for po in package_objects:
645 if pkgname in localpkgs:
646 rpmpath = self.localpkgs[pkgname]
648 rpmpath = self.getLocalPkgPath(po)
650 if not os.path.exists(rpmpath):
651 # Maybe it is a local repo
652 baseurl = str(po.repoInfo().baseUrls()[0])
653 baseurl = baseurl.strip()
655 location = zypp.asKindPackage(po).location()
656 location = str(location.filename())
658 if baseurl.startswith("file:/"):
659 rpmpath = baseurl[5:] + "/%s" % (location)
661 if not os.path.exists(rpmpath):
662 raise RpmError("Error: %s doesn't exist" % rpmpath)
664 h = rpmmisc.readRpmHeader(self.ts, rpmpath)
665 self.ts.addInstall(h, rpmpath, 'u')
667 unresolved_dependencies = self.ts.check()
668 if not unresolved_dependencies:
670 cb = rpmmisc.RPMInstallCallback(self.ts)
671 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
673 # start to catch stderr output from librpm
674 msger.enable_logstderr(installlogfile)
676 errors = self.ts.run(cb.callback, '')
680 elif len(errors) == 0:
681 msger.warning('scriptlet or other non-fatal errors occurred '
682 'during transaction.')
687 msger.error('Could not run transaction.')
690 msger.disable_logstderr()
696 for pkg, need, needflags, sense, key in unresolved_dependencies:
697 package = '-'.join(pkg)
699 if needflags == rpm.RPMSENSE_LESS:
700 deppkg = ' < '.join(need)
701 elif needflags == rpm.RPMSENSE_EQUAL:
702 deppkg = ' = '.join(need)
703 elif needflags == rpm.RPMSENSE_GREATER:
704 deppkg = ' > '.join(need)
706 deppkg = '-'.join(need)
708 if sense == rpm.RPMDEP_SENSE_REQUIRES:
709 msger.warning("[%s] Requires [%s], which is not provided" \
712 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
713 msger.warning("[%s] Conflicts with [%s]" %(package,deppkg))
715 raise RepoError("Unresolved dependencies, transaction failed.")
717 def __initialize_transaction(self):
719 self.ts = rpm.TransactionSet(self.instroot)
720 # Set to not verify DSA signatures.
721 self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
723 def checkPkg(self, pkg):
725 if not os.path.exists(pkg):
727 ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
729 msger.warning("package %s is damaged: %s" \
730 % (os.path.basename(pkg), pkg))
734 def _add_prob_flags(self, *flags):
736 if flag not in self.probFilterFlags:
737 self.probFilterFlags.append(flag)
739 def get_proxy(self, repoinfo):
741 reponame = "%s" % repoinfo.name()
742 for repo in self.repos:
743 if repo.name == reponame:
750 repourl = str(repoinfo.baseUrls()[0])
751 return get_proxy_for(repourl)