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.
22 from mic.utils import runner, fs_related
25 if not hasattr(zypp, 'PoolQuery') or not hasattr(zypp.RepoManager, 'loadSolvFile'):
26 raise ImportError("python-zypp in host system cannot support PoolQuery or loadSolvFile interface, "
27 "please update it to enhanced version which can be found in repo.meego.com/tools")
30 from mic.kickstart import ksparser
31 from mic.utils import rpmmisc
32 from mic.utils.proxy import get_proxy_for
33 from mic.utils.errors import CreatorError
34 from mic.imager.baseimager import BaseImageCreator
40 self.mirrorlist = None
42 self.proxy_username = None
43 self.proxy_password = None
46 self.autorefresh = True
47 self.keeppackages = True
50 class RepoError(CreatorError):
53 class RpmError(CreatorError):
56 from mic.pluginbase import BackendPlugin
57 class Zypp(BackendPlugin):
60 def __init__(self, target_arch, instroot, cachedir):
61 self.cachedir = cachedir
62 self.instroot = instroot
63 self.target_arch = target_arch
65 self.__pkgs_license = {}
66 self.__pkgs_content = {}
70 self.repo_manager = None
71 self.repo_manager_options = None
74 self.probFilterFlags = []
78 self.has_prov_query = True
80 def doFileLogSetup(self, uid, logfile):
81 # don't do the file log for the livecd as it can lead to open fds
82 # being left and an inability to clean up after ourself
90 if not os.path.exists("/etc/fedora-release") and not os.path.exists("/etc/meego-release"):
91 for i in range(3, os.sysconf("SC_OPEN_MAX")):
103 def _cleanupRpmdbLocks(self, installroot):
104 # cleans up temporary files left by bdb so that differing
105 # versions of rpm don't cause problems
107 for f in glob.glob(installroot + "/var/lib/rpm/__db*"):
110 def setup(self, confpath, installroot):
111 self._cleanupRpmdbLocks(installroot)
112 self.installroot = installroot
114 def whatObsolete(self, pkg):
115 query = zypp.PoolQuery()
116 query.addKind(zypp.ResKind.package)
117 query.addAttribute(zypp.SolvAttr.obsoletes, pkg)
118 query.setMatchExact()
119 for pi in query.queryResults(self.Z.pool()):
123 def _splitPkgString(self, pkg):
124 sp = pkg.rsplit(".",1)
129 sysarch = zypp.Arch(self.target_arch)
130 if not zypp.Arch(arch).compatible_with (sysarch):
135 def selectPackage(self, pkg):
136 """ Select a given package or package pattern, can be specified 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)
155 if startx and not endx:
156 pattern = '%s$' % (pkg[1:])
157 if endx and not startx:
158 pattern = '^%s' % (pkg[0:-1])
160 pattern = '%s' % (pkg[1:-1])
162 q.addAttribute(zypp.SolvAttr.name,pattern)
165 q.addAttribute(zypp.SolvAttr.name,name)
168 q.addAttribute(zypp.SolvAttr.name,pkg)
170 for item in sorted(q.queryResults(self.Z.pool()), key=lambda item: str(item.edition()), reverse=True):
171 if item.name() in self.excpkgs.keys() and self.excpkgs[item.name()] == item.repoInfo().name():
173 if item.name() in self.incpkgs.keys() and self.incpkgs[item.name()] != item.repoInfo().name():
176 obspkg = self.whatObsolete(item.name())
178 if arch == str(item.arch()):
179 item.status().setToBeInstalled (zypp.ResStatus.USER)
181 markPoolItem(obspkg, item)
184 # Can't match using package name, then search from packge provides infomation
185 if found == False and not ispattern:
186 q.addAttribute(zypp.SolvAttr.provides, pkg)
187 q.addAttribute(zypp.SolvAttr.name,'')
188 for item in sorted(q.queryResults(self.Z.pool()), key=lambda item: str(item.edition()), reverse=True):
189 if item.name() in self.excpkgs.keys() and self.excpkgs[item.name()] == item.repoInfo().name():
191 if item.name() in self.incpkgs.keys() and self.incpkgs[item.name()] != item.repoInfo().name():
194 obspkg = self.whatObsolete(item.name())
195 markPoolItem(obspkg, item)
200 raise CreatorError("Unable to find package: %s" % (pkg,))
202 def inDeselectPackages(self, item):
203 """check if specified pacakges are in the list of inDeselectPackages"""
205 for pkg in self.to_deselect:
206 startx = pkg.startswith("*")
207 endx = pkg.endswith("*")
208 ispattern = startx or endx
209 pkgname, pkgarch = self._splitPkgString(pkg)
212 if name == pkgname and str(item.arch()) == pkgarch:
218 if startx and name.endswith(pkg[1:]):
220 if endx and name.startswith(pkg[:-1]):
224 def deselectPackage(self, pkg):
225 """collect packages should not be installed"""
226 self.to_deselect.append(pkg)
228 def selectGroup(self, grp, include = ksparser.GROUP_DEFAULT):
230 self.__initialize_zypp()
233 q.addKind(zypp.ResKind.pattern)
234 for item in q.queryResults(self.Z.pool()):
235 summary = "%s" % item.summary()
236 name = "%s" % item.name()
237 if name == grp or summary == grp:
239 item.status().setToBeInstalled (zypp.ResStatus.USER)
243 if include == ksparser.GROUP_REQUIRED:
244 map(lambda p: self.deselectPackage(p), grp.default_packages.keys())
247 raise CreatorError("Unable to find pattern: %s" % (grp,))
249 def addRepository(self, name, url = None, mirrorlist = None, proxy = None,
250 proxy_username = None, proxy_password = None,
251 inc = None, exc = None, ssl_verify = True, cost=None,
253 # TODO: Handle cost attribute for repos
254 if not self.repo_manager:
255 self.__initialize_repo_manager()
257 repo = RepositoryStub()
261 repo.proxy_username = proxy_username
262 repo.proxy_password = proxy_password
263 repo.ssl_verify = ssl_verify
264 repo.baseurl.append(url)
267 self.incpkgs[pkg] = name
270 self.excpkgs[pkg] = name
272 # check LICENSE files
273 if not rpmmisc.checkRepositoryEULA(name, repo):
274 msger.warning('skip repo:%s for failed EULA confirmation' % name)
278 repo.mirrorlist = mirrorlist
280 # Enable gpg check for verifying corrupt packages
283 repo.priority = priority
284 self.repos.append(repo)
287 repo_info = zypp.RepoInfo()
288 repo_info.setAlias(repo.name)
289 repo_info.setName(repo.name)
290 repo_info.setEnabled(repo.enabled)
291 repo_info.setAutorefresh(repo.autorefresh)
292 repo_info.setKeepPackages(repo.keeppackages)
293 baseurl = zypp.Url(repo.baseurl[0])
295 baseurl.setQueryParam("ssl_verify", "no")
297 (scheme, host, path, parm, query, frag) = urlparse.urlparse(proxy)
298 proxyinfo = host.split(":")
299 baseurl.setQueryParam ("proxy", proxyinfo[0])
301 if len(proxyinfo) > 1:
303 baseurl.setQueryParam ("proxyport", port)
304 repo_info.addBaseUrl(baseurl)
306 repo_info.setPriority(repo.priority)
307 self.repo_manager.addRepository(repo_info)
308 self.__build_repo_cache(name)
309 except RuntimeError, e:
310 raise CreatorError(str(e))
312 msger.verbose('repo: %s was added' % name)
315 def installHasFile(self, file):
318 def runInstall(self, checksize = 0):
319 os.environ["HOME"] = "/"
320 self.buildTransaction()
322 todo = zypp.GetResolvablesToInsDel(self.Z.pool())
323 installed_pkgs = todo._toInstall
325 for item in installed_pkgs:
326 if not zypp.isKindPattern(item) and not self.inDeselectPackages(item):
329 # record the total size of installed pkgs
330 pkgs_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
332 # check needed size before actually download and install
333 if checksize and pkgs_total_size > checksize:
334 raise CreatorError("Size of specified root partition in kickstart file is too small to install all selected packages.")
336 # record all pkg and the content
337 localpkgs = self.localpkgs.keys()
340 if pkg.name() in localpkgs:
341 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
342 pkg_long_name = "%s-%s-%s.%s.rpm" % (hdr['name'], hdr['version'], hdr['release'], hdr['arch'])
343 license = hdr['license']
345 pkg_long_name = "%s-%s.%s.rpm" % (pkg.name(), pkg.edition(), pkg.arch())
346 package = zypp.asKindPackage(pkg)
347 license = package.license()
348 self.__pkgs_content[pkg_long_name] = {} #TBD: to get file list
349 if license in self.__pkgs_license.keys():
350 self.__pkgs_license[license].append(pkg_long_name)
352 self.__pkgs_license[license] = [pkg_long_name]
354 total_count = len(dlpkgs)
356 localpkgs = self.localpkgs.keys()
357 msger.info("Checking packages cache and packages integrity ...")
359 """ Check if it is cached locally """
360 if po.name() in localpkgs:
363 local = self.getLocalPkgPath(po)
364 if os.path.exists(local):
365 if self.checkPkg(local) != 0:
369 download_count = total_count - cached_count
370 msger.info("%d packages to be installed, %d packages gotten from cache, %d packages to be downloaded" % (total_count, cached_count, download_count))
372 if download_count > 0:
373 msger.info("Downloading packages ...")
374 self.downloadPkgs(dlpkgs, download_count)
375 self.installPkgs(dlpkgs)
378 raise CreatorError("Unable to download from repo : %s" % (e,))
380 raise CreatorError("Unable to install: %s" % (e,))
382 def getAllContent(self):
383 return self.__pkgs_content
385 def getPkgsLicense(self):
386 return self.__pkgs_license
388 def __initialize_repo_manager(self):
389 if self.repo_manager:
392 """ Clean up repo metadata """
393 shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
394 shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
395 shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
397 zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
398 | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
399 | zypp.KeyRing.ACCEPT_UNKNOWNKEY
400 | zypp.KeyRing.TRUST_KEY_TEMPORARILY
402 self.repo_manager_options = zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
403 self.repo_manager_options.knownReposPath = zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
404 self.repo_manager_options.repoCachePath = zypp.Pathname(self.cachedir)
405 self.repo_manager_options.repoRawCachePath = zypp.Pathname(self.cachedir + "/raw")
406 self.repo_manager_options.repoSolvCachePath = zypp.Pathname(self.cachedir + "/solv")
407 self.repo_manager_options.repoPackagesCachePath = zypp.Pathname(self.cachedir + "/packages")
409 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
411 def __build_repo_cache(self, name):
412 repo = self.repo_manager.getRepositoryInfo(name)
413 if self.repo_manager.isCached(repo) or not repo.enabled():
415 self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
417 def __initialize_zypp(self):
421 zconfig = zypp.ZConfig_instance()
423 """ Set system architecture """
425 zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
427 msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
429 """ repoPackagesCachePath is corrected by this """
430 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
431 repos = self.repo_manager.knownRepositories()
433 if not repo.enabled():
435 self.repo_manager.loadFromCache(repo)
437 self.Z = zypp.ZYppFactory_instance().getZYpp()
438 self.Z.initializeTarget(zypp.Pathname(self.instroot))
439 self.Z.target().load()
442 def buildTransaction(self):
443 if not self.Z.resolver().resolvePool():
444 msger.warning("Problem count: %d" % len(self.Z.resolver().problems()))
445 for problem in self.Z.resolver().problems():
446 msger.warning("Problem: %s, %s" % (problem.description().decode("utf-8"), problem.details().decode("utf-8")))
448 def getLocalPkgPath(self, po):
449 repoinfo = po.repoInfo()
450 cacheroot = repoinfo.packagesPath()
451 location= zypp.asKindPackage(po).location()
452 rpmpath = str(location.filename())
453 pkgpath = "%s/%s" % (cacheroot, rpmpath)
456 def installLocal(self, pkg, po=None, updateonly=False):
458 self.__initialize_transaction()
459 solvfile = "%s/.solv" % (self.cachedir)
460 rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"), pkg])
462 f = open(solvfile, "w+")
465 warnmsg = self.repo_manager.loadSolvFile(solvfile , os.path.basename(pkg))
467 msger.warning(warnmsg)
470 msger.warning('Can not get %s solv data.' % pkg)
471 hdr = rpmmisc.readRpmHeader(self.ts, pkg)
472 arch = zypp.Arch(hdr['arch'])
473 sysarch = zypp.Arch(self.target_arch)
474 if arch.compatible_with (sysarch):
475 pkgname = hdr['name']
476 self.localpkgs[pkgname] = pkg
477 self.selectPackage(pkgname)
478 msger.info("Marking %s to be installed" % (pkg))
480 msger.warning ("Cannot add package %s to transaction. Not a compatible architecture: %s" % (pkg, hdr['arch']))
482 def downloadPkgs(self, package_objects, count):
483 localpkgs = self.localpkgs.keys()
484 progress_obj = rpmmisc.TextProgress(count)
485 for po in package_objects:
486 if po.name() in localpkgs:
488 filename = self.getLocalPkgPath(po)
489 if os.path.exists(filename):
490 if self.checkPkg(filename) == 0:
492 dirn = os.path.dirname(filename)
493 if not os.path.exists(dirn):
495 baseurl = str(po.repoInfo().baseUrls()[0])
496 index = baseurl.find("?")
498 baseurl = baseurl[:index]
499 proxy = self.get_proxy(po.repoInfo())
502 proxies = {str(proxy.split(":")[0]):str(proxy)}
504 location = zypp.asKindPackage(po).location()
505 location = str(location.filename())
506 if location.startswith("./"):
507 location = location[2:]
508 url = baseurl + "/%s" % location
510 filename = rpmmisc.myurlgrab(url, filename, proxies, progress_obj)
515 def installPkgs(self, package_objects):
517 self.__initialize_transaction()
521 for flag in self.probFilterFlags:
523 self.ts.setProbFilter(probfilter)
525 localpkgs = self.localpkgs.keys()
526 for po in package_objects:
528 if pkgname in localpkgs:
529 rpmpath = self.localpkgs[pkgname]
531 rpmpath = self.getLocalPkgPath(po)
532 if not os.path.exists(rpmpath):
533 """ Maybe it is a local repo """
534 baseurl = str(po.repoInfo().baseUrls()[0])
535 baseurl = baseurl.strip()
536 location = zypp.asKindPackage(po).location()
537 location = str(location.filename())
538 if baseurl.startswith("file:/"):
539 rpmpath = baseurl[5:] + "/%s" % (location)
540 if not os.path.exists(rpmpath):
541 raise RpmError("Error: %s doesn't exist" % rpmpath)
542 h = rpmmisc.readRpmHeader(self.ts, rpmpath)
543 self.ts.addInstall(h, rpmpath, 'u')
545 unresolved_dependencies = self.ts.check()
546 if not unresolved_dependencies:
548 cb = rpmmisc.RPMInstallCallback(self.ts)
549 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
550 msger.enable_logstderr(installlogfile)
551 errors = self.ts.run(cb.callback, '')
554 elif len(errors) == 0:
555 msger.warning('scriptlet or other non-fatal errors occurred during transaction.')
559 msger.error('Could not run transaction.')
560 msger.disable_logstderr()
565 for pkg, need, needflags, sense, key in unresolved_dependencies:
566 package = '-'.join(pkg)
567 if needflags == rpm.RPMSENSE_LESS:
568 deppkg = ' < '.join(need)
569 elif needflags == rpm.RPMSENSE_EQUAL:
570 deppkg = ' = '.join(need)
571 elif needflags == rpm.RPMSENSE_GREATER:
572 deppkg = ' > '.join(need)
574 deppkg = '-'.join(need)
576 if sense == rpm.RPMDEP_SENSE_REQUIRES:
577 msger.warning ("[%s] Requires [%s], which is not provided" % (package, deppkg))
578 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
579 msger.warning ("[%s] Conflicts with [%s]" % (package, deppkg))
581 raise RepoError("Unresolved dependencies, transaction failed.")
583 def __initialize_transaction(self):
585 self.ts = rpm.TransactionSet(self.instroot)
586 # Set to not verify DSA signatures.
587 self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
589 def checkPkg(self, pkg):
591 if not os.path.exists(pkg):
593 ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
595 msger.warning("package %s is damaged: %s" % (os.path.basename(pkg), pkg))
599 def _add_prob_flags(self, *flags):
601 if flag not in self.probFilterFlags:
602 self.probFilterFlags.append(flag)
604 def get_proxy(self, repoinfo):
606 reponame = "%s" % repoinfo.name()
607 for repo in self.repos:
608 if repo.name == reponame:
615 repourl = str(repoinfo.baseUrls()[0])
616 return get_proxy_for(repourl)