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
437 # FIXME: for multiple partitions for loop type, check fails
438 # skip the check temporarily
439 #if checksize and install_total_size > checksize:
440 # raise CreatorError("No enough space used for installing, "
441 # "please resize partition size in ks file")
443 download_count = total_count - cached_count
444 msger.info("%d packages to be installed, "
445 "%d packages gotten from cache, "
446 "%d packages to be downloaded" \
447 % (total_count, cached_count, download_count))
450 if download_count > 0:
451 msger.info("Downloading packages ...")
452 self.downloadPkgs(dlpkgs, download_count)
454 self.installPkgs(dlpkgs)
457 raise CreatorError("Unable to download from repo : %s" % (e,))
459 raise CreatorError("Unable to install: %s" % (e,))
461 def getAllContent(self):
462 return self.__pkgs_content
464 def getPkgsLicense(self):
465 return self.__pkgs_license
467 def __initialize_repo_manager(self):
468 if self.repo_manager:
471 # Clean up repo metadata
472 shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
473 shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
474 shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
476 zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
477 | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
478 | zypp.KeyRing.ACCEPT_UNKNOWNKEY
479 | zypp.KeyRing.TRUST_KEY_TEMPORARILY
482 self.repo_manager_options = \
483 zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
485 self.repo_manager_options.knownReposPath = \
486 zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
488 self.repo_manager_options.repoCachePath = \
489 zypp.Pathname(self.cachedir)
491 self.repo_manager_options.repoRawCachePath = \
492 zypp.Pathname(self.cachedir + "/raw")
494 self.repo_manager_options.repoSolvCachePath = \
495 zypp.Pathname(self.cachedir + "/solv")
497 self.repo_manager_options.repoPackagesCachePath = \
498 zypp.Pathname(self.cachedir + "/packages")
500 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
502 def __build_repo_cache(self, name):
503 repo = self.repo_manager.getRepositoryInfo(name)
504 if self.repo_manager.isCached(repo) or not repo.enabled():
507 msger.info('Refreshing repository: %s ...' % name)
508 self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
510 def __initialize_zypp(self):
514 zconfig = zypp.ZConfig_instance()
516 # Set system architecture
518 zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
520 msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
522 # repoPackagesCachePath is corrected by this
523 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
524 repos = self.repo_manager.knownRepositories()
526 if not repo.enabled():
528 self.repo_manager.loadFromCache(repo)
530 self.Z = zypp.ZYppFactory_instance().getZYpp()
531 self.Z.initializeTarget(zypp.Pathname(self.instroot))
532 self.Z.target().load()
534 def buildTransaction(self):
535 if not self.Z.resolver().resolvePool():
536 probs = self.Z.resolver().problems()
538 for problem in probs:
539 msger.warning("repo problem: %s, %s" \
540 % (problem.description().decode("utf-8"),
541 problem.details().decode("utf-8")))
543 raise RepoError("found %d resolver problem, abort!" \
546 def getLocalPkgPath(self, po):
547 repoinfo = po.repoInfo()
548 cacheroot = repoinfo.packagesPath()
549 location= zypp.asKindPackage(po).location()
550 rpmpath = str(location.filename())
551 pkgpath = "%s/%s" % (cacheroot, os.path.basename(rpmpath))
554 def installLocal(self, pkg, po=None, updateonly=False):
556 self.__initialize_transaction()
558 solvfile = "%s/.solv" % (self.cachedir)
560 rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"),
563 f = open(solvfile, "w+")
567 warnmsg = self.repo_manager.loadSolvFile(solvfile,
568 os.path.basename(pkg))
570 msger.warning(warnmsg)
574 msger.warning('Can not get %s solv data.' % pkg)
576 hdr = rpmmisc.readRpmHeader(self.ts, pkg)
577 arch = zypp.Arch(hdr['arch'])
578 sysarch = zypp.Arch(self.target_arch)
580 if arch.compatible_with (sysarch):
581 pkgname = hdr['name']
582 self.localpkgs[pkgname] = pkg
583 self.selectPackage(pkgname)
584 msger.info("Marking %s to be installed" % (pkg))
587 msger.warning("Cannot add package %s to transaction. "
588 "Not a compatible architecture: %s" \
589 % (pkg, hdr['arch']))
591 def downloadPkgs(self, package_objects, count):
592 localpkgs = self.localpkgs.keys()
593 progress_obj = rpmmisc.TextProgress(count)
595 for po in package_objects:
596 if po.name() in localpkgs:
599 filename = self.getLocalPkgPath(po)
600 if os.path.exists(filename):
601 if self.checkPkg(filename) == 0:
604 dirn = os.path.dirname(filename)
605 if not os.path.exists(dirn):
608 baseurl = str(po.repoInfo().baseUrls()[0])
609 index = baseurl.find("?")
611 baseurl = baseurl[:index]
613 proxy = self.get_proxy(po.repoInfo())
616 proxies = {str(proxy.split(":")[0]):str(proxy)}
618 location = zypp.asKindPackage(po).location()
619 location = str(location.filename())
620 if location.startswith("./"):
621 location = location[2:]
623 url = baseurl + "/%s" % location
626 filename = rpmmisc.myurlgrab(url,
634 def installPkgs(self, package_objects):
636 self.__initialize_transaction()
640 for flag in self.probFilterFlags:
642 self.ts.setProbFilter(probfilter)
644 localpkgs = self.localpkgs.keys()
646 for po in package_objects:
648 if pkgname in localpkgs:
649 rpmpath = self.localpkgs[pkgname]
651 rpmpath = self.getLocalPkgPath(po)
653 if not os.path.exists(rpmpath):
654 # Maybe it is a local repo
655 baseurl = str(po.repoInfo().baseUrls()[0])
656 baseurl = baseurl.strip()
658 location = zypp.asKindPackage(po).location()
659 location = str(location.filename())
661 if baseurl.startswith("file:/"):
662 rpmpath = baseurl[5:] + "/%s" % (location)
664 if not os.path.exists(rpmpath):
665 raise RpmError("Error: %s doesn't exist" % rpmpath)
667 h = rpmmisc.readRpmHeader(self.ts, rpmpath)
668 self.ts.addInstall(h, rpmpath, 'u')
670 unresolved_dependencies = self.ts.check()
671 if not unresolved_dependencies:
673 cb = rpmmisc.RPMInstallCallback(self.ts)
674 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
676 # start to catch stderr output from librpm
677 msger.enable_logstderr(installlogfile)
679 errors = self.ts.run(cb.callback, '')
681 msger.disable_logstderr()
685 if errors is not None:
687 msger.warning('scriptlet or other non-fatal errors occurred '
688 'during transaction.')
693 raise RepoError('Could not run transaction.')
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)