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 import misc
33 from mic.utils.proxy import get_proxy_for
34 from mic.utils.errors import CreatorError
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 class RepoError(CreatorError):
54 class RpmError(CreatorError):
57 from mic.pluginbase import BackendPlugin
58 class Zypp(BackendPlugin):
61 def __init__(self, target_arch, instroot, cachedir):
62 self.cachedir = cachedir
63 self.instroot = instroot
64 self.target_arch = target_arch
66 self.__pkgs_license = {}
67 self.__pkgs_content = {}
71 self.repo_manager = None
72 self.repo_manager_options = None
75 self.probFilterFlags = []
79 self.has_prov_query = True
81 def doFileLogSetup(self, uid, logfile):
82 # don't do the file log for the livecd as it can lead to open fds
83 # being left and an inability to clean up after ourself
94 if not os.path.exists("/etc/fedora-release") and not os.path.exists("/etc/meego-release"):
95 for i in range(3, os.sysconf("SC_OPEN_MAX")):
104 def _cleanupRpmdbLocks(self, installroot):
105 # cleans up temporary files left by bdb so that differing
106 # versions of rpm don't cause problems
108 for f in glob.glob(installroot + "/var/lib/rpm/__db*"):
112 self._cleanupRpmdbLocks(self.instroot)
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(":")
301 if len(proxyinfo) > 1:
303 if proxy.startswith("socks") and len(proxy.rsplit(':', 1)) == 2:
304 host = proxy.rsplit(':', 1)[0]
305 port = proxy.rsplit(':', 1)[1]
306 baseurl.setQueryParam ("proxy", host)
307 baseurl.setQueryParam ("proxyport", port)
308 repo_info.addBaseUrl(baseurl)
310 repo_info.setPriority(repo.priority)
311 self.repo_manager.addRepository(repo_info)
312 self.__build_repo_cache(name)
313 except RuntimeError, e:
314 raise CreatorError(str(e))
316 msger.verbose('repo: %s was added' % name)
319 def installHasFile(self, file):
322 def runInstall(self, checksize = 0):
323 os.environ["HOME"] = "/"
324 self.buildTransaction()
326 todo = zypp.GetResolvablesToInsDel(self.Z.pool())
327 installed_pkgs = todo._toInstall
329 for item in installed_pkgs:
330 if not zypp.isKindPattern(item) and not self.inDeselectPackages(item):
333 # record all pkg and the content
334 localpkgs = self.localpkgs.keys()
337 if pkg.name() in localpkgs:
338 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
339 pkg_long_name = "%s.%s %s-%s" % (hdr['name'], hdr['arch'], hdr['version'], hdr['release'])
340 license = hdr['license']
342 pkg_long_name = "%s.%s %s" % (pkg.name(), pkg.arch(), pkg.edition())
343 package = zypp.asKindPackage(pkg)
344 license = package.license()
345 self.__pkgs_content[pkg_long_name] = {} #TBD: to get file list
346 if license in self.__pkgs_license.keys():
347 self.__pkgs_license[license].append(pkg_long_name)
349 self.__pkgs_license[license] = [pkg_long_name]
351 total_count = len(dlpkgs)
353 download_total_size = sum(map(lambda x: int(x.downloadSize()), dlpkgs))
354 localpkgs = self.localpkgs.keys()
355 msger.info("Checking packages cache and packages integrity ...")
357 """ Check if it is cached locally """
358 if po.name() in localpkgs:
361 local = self.getLocalPkgPath(po)
362 if os.path.exists(local):
363 if self.checkPkg(local) != 0:
366 download_total_size -= int(po.downloadSize())
368 cache_avail_size = misc.get_filesystem_avail(self.cachedir)
369 if cache_avail_size < download_total_size:
370 raise CreatorError("No enough space used for downloading.")
372 # record the total size of installed pkgs
373 install_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
374 # check needed size before actually download and install
375 if checksize and install_total_size > checksize:
376 raise CreatorError("No enough space used for installing, please resize partition size in ks file")
378 download_count = total_count - cached_count
379 msger.info("%d packages to be installed, %d packages gotten from cache, %d packages to be downloaded" % (total_count, cached_count, download_count))
381 if download_count > 0:
382 msger.info("Downloading packages ...")
383 self.downloadPkgs(dlpkgs, download_count)
384 self.installPkgs(dlpkgs)
387 raise CreatorError("Unable to download from repo : %s" % (e,))
389 raise CreatorError("Unable to install: %s" % (e,))
391 def getAllContent(self):
392 return self.__pkgs_content
394 def getPkgsLicense(self):
395 return self.__pkgs_license
397 def __initialize_repo_manager(self):
398 if self.repo_manager:
401 """ Clean up repo metadata """
402 shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
403 shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
404 shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
406 zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
407 | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
408 | zypp.KeyRing.ACCEPT_UNKNOWNKEY
409 | zypp.KeyRing.TRUST_KEY_TEMPORARILY
411 self.repo_manager_options = zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
412 self.repo_manager_options.knownReposPath = zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
413 self.repo_manager_options.repoCachePath = zypp.Pathname(self.cachedir)
414 self.repo_manager_options.repoRawCachePath = zypp.Pathname(self.cachedir + "/raw")
415 self.repo_manager_options.repoSolvCachePath = zypp.Pathname(self.cachedir + "/solv")
416 self.repo_manager_options.repoPackagesCachePath = zypp.Pathname(self.cachedir + "/packages")
418 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
420 def __build_repo_cache(self, name):
421 repo = self.repo_manager.getRepositoryInfo(name)
422 if self.repo_manager.isCached(repo) or not repo.enabled():
424 self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
426 def __initialize_zypp(self):
430 zconfig = zypp.ZConfig_instance()
432 """ Set system architecture """
434 zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
436 msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
438 """ repoPackagesCachePath is corrected by this """
439 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
440 repos = self.repo_manager.knownRepositories()
442 if not repo.enabled():
444 self.repo_manager.loadFromCache(repo)
446 self.Z = zypp.ZYppFactory_instance().getZYpp()
447 self.Z.initializeTarget(zypp.Pathname(self.instroot))
448 self.Z.target().load()
451 def buildTransaction(self):
452 if not self.Z.resolver().resolvePool():
453 msger.warning("Problem count: %d" % len(self.Z.resolver().problems()))
454 for problem in self.Z.resolver().problems():
455 msger.warning("Problem: %s, %s" % (problem.description().decode("utf-8"), problem.details().decode("utf-8")))
457 def getLocalPkgPath(self, po):
458 repoinfo = po.repoInfo()
459 cacheroot = repoinfo.packagesPath()
460 location= zypp.asKindPackage(po).location()
461 rpmpath = str(location.filename())
462 pkgpath = "%s/%s" % (cacheroot, rpmpath)
465 def installLocal(self, pkg, po=None, updateonly=False):
467 self.__initialize_transaction()
468 solvfile = "%s/.solv" % (self.cachedir)
469 rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"), pkg])
471 f = open(solvfile, "w+")
474 warnmsg = self.repo_manager.loadSolvFile(solvfile , os.path.basename(pkg))
476 msger.warning(warnmsg)
479 msger.warning('Can not get %s solv data.' % pkg)
480 hdr = rpmmisc.readRpmHeader(self.ts, pkg)
481 arch = zypp.Arch(hdr['arch'])
482 sysarch = zypp.Arch(self.target_arch)
483 if arch.compatible_with (sysarch):
484 pkgname = hdr['name']
485 self.localpkgs[pkgname] = pkg
486 self.selectPackage(pkgname)
487 msger.info("Marking %s to be installed" % (pkg))
489 msger.warning ("Cannot add package %s to transaction. Not a compatible architecture: %s" % (pkg, hdr['arch']))
491 def downloadPkgs(self, package_objects, count):
492 localpkgs = self.localpkgs.keys()
493 progress_obj = rpmmisc.TextProgress(count)
494 for po in package_objects:
495 if po.name() in localpkgs:
497 filename = self.getLocalPkgPath(po)
498 if os.path.exists(filename):
499 if self.checkPkg(filename) == 0:
501 dirn = os.path.dirname(filename)
502 if not os.path.exists(dirn):
504 baseurl = str(po.repoInfo().baseUrls()[0])
505 index = baseurl.find("?")
507 baseurl = baseurl[:index]
508 proxy = self.get_proxy(po.repoInfo())
511 proxies = {str(proxy.split(":")[0]):str(proxy)}
513 location = zypp.asKindPackage(po).location()
514 location = str(location.filename())
515 if location.startswith("./"):
516 location = location[2:]
517 url = baseurl + "/%s" % location
519 filename = rpmmisc.myurlgrab(url, filename, proxies, progress_obj)
524 def installPkgs(self, package_objects):
526 self.__initialize_transaction()
530 for flag in self.probFilterFlags:
532 self.ts.setProbFilter(probfilter)
534 localpkgs = self.localpkgs.keys()
535 for po in package_objects:
537 if pkgname in localpkgs:
538 rpmpath = self.localpkgs[pkgname]
540 rpmpath = self.getLocalPkgPath(po)
541 if not os.path.exists(rpmpath):
542 """ Maybe it is a local repo """
543 baseurl = str(po.repoInfo().baseUrls()[0])
544 baseurl = baseurl.strip()
545 location = zypp.asKindPackage(po).location()
546 location = str(location.filename())
547 if baseurl.startswith("file:/"):
548 rpmpath = baseurl[5:] + "/%s" % (location)
549 if not os.path.exists(rpmpath):
550 raise RpmError("Error: %s doesn't exist" % rpmpath)
551 h = rpmmisc.readRpmHeader(self.ts, rpmpath)
552 self.ts.addInstall(h, rpmpath, 'u')
554 unresolved_dependencies = self.ts.check()
555 if not unresolved_dependencies:
557 cb = rpmmisc.RPMInstallCallback(self.ts)
558 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
559 msger.enable_logstderr(installlogfile)
560 errors = self.ts.run(cb.callback, '')
563 elif len(errors) == 0:
564 msger.warning('scriptlet or other non-fatal errors occurred during transaction.')
568 msger.error('Could not run transaction.')
569 msger.disable_logstderr()
574 for pkg, need, needflags, sense, key in unresolved_dependencies:
575 package = '-'.join(pkg)
576 if needflags == rpm.RPMSENSE_LESS:
577 deppkg = ' < '.join(need)
578 elif needflags == rpm.RPMSENSE_EQUAL:
579 deppkg = ' = '.join(need)
580 elif needflags == rpm.RPMSENSE_GREATER:
581 deppkg = ' > '.join(need)
583 deppkg = '-'.join(need)
585 if sense == rpm.RPMDEP_SENSE_REQUIRES:
586 msger.warning ("[%s] Requires [%s], which is not provided" % (package, deppkg))
587 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
588 msger.warning ("[%s] Conflicts with [%s]" % (package, deppkg))
590 raise RepoError("Unresolved dependencies, transaction failed.")
592 def __initialize_transaction(self):
594 self.ts = rpm.TransactionSet(self.instroot)
595 # Set to not verify DSA signatures.
596 self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
598 def checkPkg(self, pkg):
600 if not os.path.exists(pkg):
602 ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
604 msger.warning("package %s is damaged: %s" % (os.path.basename(pkg), pkg))
608 def _add_prob_flags(self, *flags):
610 if flag not in self.probFilterFlags:
611 self.probFilterFlags.append(flag)
613 def get_proxy(self, repoinfo):
615 reponame = "%s" % repoinfo.name()
616 for repo in self.repos:
617 if repo.name == reponame:
624 repourl = str(repoinfo.baseUrls()[0])
625 return get_proxy_for(repourl)