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=None, instroot=None):
111 if not self.instroot:
112 self.instroot = instroot
113 self._cleanupRpmdbLocks(self.instroot)
115 def whatObsolete(self, pkg):
116 query = zypp.PoolQuery()
117 query.addKind(zypp.ResKind.package)
118 query.addAttribute(zypp.SolvAttr.obsoletes, pkg)
119 query.setMatchExact()
120 for pi in query.queryResults(self.Z.pool()):
124 def _splitPkgString(self, pkg):
125 sp = pkg.rsplit(".",1)
130 sysarch = zypp.Arch(self.target_arch)
131 if not zypp.Arch(arch).compatible_with (sysarch):
136 def selectPackage(self, pkg):
137 """ Select a given package or package pattern, can be specified with name.arch or name* or *name """
139 self.__initialize_zypp()
141 def markPoolItem(obs, pi):
143 pi.status().setToBeInstalled (zypp.ResStatus.USER)
145 obs.status().setToBeInstalled (zypp.ResStatus.USER)
148 startx = pkg.startswith("*")
149 endx = pkg.endswith("*")
150 ispattern = startx or endx
151 name, arch = self._splitPkgString(pkg)
154 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)
166 q.addAttribute(zypp.SolvAttr.name,name)
169 q.addAttribute(zypp.SolvAttr.name,pkg)
171 for item in sorted(q.queryResults(self.Z.pool()), key=lambda item: str(item.edition()), reverse=True):
172 if item.name() in self.excpkgs.keys() and self.excpkgs[item.name()] == item.repoInfo().name():
174 if item.name() in self.incpkgs.keys() and self.incpkgs[item.name()] != item.repoInfo().name():
177 obspkg = self.whatObsolete(item.name())
179 if arch == str(item.arch()):
180 item.status().setToBeInstalled (zypp.ResStatus.USER)
182 markPoolItem(obspkg, item)
185 # Can't match using package name, then search from packge provides infomation
186 if found == False and not ispattern:
187 q.addAttribute(zypp.SolvAttr.provides, pkg)
188 q.addAttribute(zypp.SolvAttr.name,'')
189 for item in sorted(q.queryResults(self.Z.pool()), key=lambda item: str(item.edition()), reverse=True):
190 if item.name() in self.excpkgs.keys() and self.excpkgs[item.name()] == item.repoInfo().name():
192 if item.name() in self.incpkgs.keys() and self.incpkgs[item.name()] != item.repoInfo().name():
195 obspkg = self.whatObsolete(item.name())
196 markPoolItem(obspkg, item)
201 raise CreatorError("Unable to find package: %s" % (pkg,))
203 def inDeselectPackages(self, item):
204 """check if specified pacakges are in the list of inDeselectPackages"""
206 for pkg in self.to_deselect:
207 startx = pkg.startswith("*")
208 endx = pkg.endswith("*")
209 ispattern = startx or endx
210 pkgname, pkgarch = self._splitPkgString(pkg)
213 if name == pkgname and str(item.arch()) == pkgarch:
219 if startx and name.endswith(pkg[1:]):
221 if endx and name.startswith(pkg[:-1]):
225 def deselectPackage(self, pkg):
226 """collect packages should not be installed"""
227 self.to_deselect.append(pkg)
229 def selectGroup(self, grp, include = ksparser.GROUP_DEFAULT):
231 self.__initialize_zypp()
234 q.addKind(zypp.ResKind.pattern)
235 for item in q.queryResults(self.Z.pool()):
236 summary = "%s" % item.summary()
237 name = "%s" % item.name()
238 if name == grp or summary == grp:
240 item.status().setToBeInstalled (zypp.ResStatus.USER)
244 if include == ksparser.GROUP_REQUIRED:
245 map(lambda p: self.deselectPackage(p), grp.default_packages.keys())
248 raise CreatorError("Unable to find pattern: %s" % (grp,))
250 def addRepository(self, name, url = None, mirrorlist = None, proxy = None,
251 proxy_username = None, proxy_password = None,
252 inc = None, exc = None, ssl_verify = True, cost=None,
254 # TODO: Handle cost attribute for repos
255 if not self.repo_manager:
256 self.__initialize_repo_manager()
258 repo = RepositoryStub()
262 repo.proxy_username = proxy_username
263 repo.proxy_password = proxy_password
264 repo.ssl_verify = ssl_verify
265 repo.baseurl.append(url)
268 self.incpkgs[pkg] = name
271 self.excpkgs[pkg] = name
273 # check LICENSE files
274 if not rpmmisc.checkRepositoryEULA(name, repo):
275 msger.warning('skip repo:%s for failed EULA confirmation' % name)
279 repo.mirrorlist = mirrorlist
281 # Enable gpg check for verifying corrupt packages
284 repo.priority = priority
285 self.repos.append(repo)
288 repo_info = zypp.RepoInfo()
289 repo_info.setAlias(repo.name)
290 repo_info.setName(repo.name)
291 repo_info.setEnabled(repo.enabled)
292 repo_info.setAutorefresh(repo.autorefresh)
293 repo_info.setKeepPackages(repo.keeppackages)
294 baseurl = zypp.Url(repo.baseurl[0])
296 baseurl.setQueryParam("ssl_verify", "no")
298 (scheme, host, path, parm, query, frag) = urlparse.urlparse(proxy)
299 proxyinfo = host.split(":")
302 if len(proxyinfo) > 1:
304 if proxy.startswith("socks") and len(proxy.rsplit(':', 1)) == 2:
305 host = proxy.rsplit(':', 1)[0]
306 port = proxy.rsplit(':', 1)[1]
307 baseurl.setQueryParam ("proxy", host)
308 baseurl.setQueryParam ("proxyport", port)
309 repo_info.addBaseUrl(baseurl)
311 repo_info.setPriority(repo.priority)
312 self.repo_manager.addRepository(repo_info)
313 self.__build_repo_cache(name)
314 except RuntimeError, e:
315 raise CreatorError(str(e))
317 msger.verbose('repo: %s was added' % name)
320 def installHasFile(self, file):
323 def runInstall(self, checksize = 0):
324 os.environ["HOME"] = "/"
325 self.buildTransaction()
327 todo = zypp.GetResolvablesToInsDel(self.Z.pool())
328 installed_pkgs = todo._toInstall
330 for item in installed_pkgs:
331 if not zypp.isKindPattern(item) and not self.inDeselectPackages(item):
334 # record the total size of installed pkgs
335 pkgs_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
337 # check needed size before actually download and install
338 if checksize and pkgs_total_size > checksize:
339 raise CreatorError("Size of specified root partition in kickstart file is too small to install all selected packages.")
341 # record all pkg and the content
342 localpkgs = self.localpkgs.keys()
345 if pkg.name() in localpkgs:
346 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
347 pkg_long_name = "%s-%s-%s.%s.rpm" % (hdr['name'], hdr['version'], hdr['release'], hdr['arch'])
348 license = hdr['license']
350 pkg_long_name = "%s-%s.%s.rpm" % (pkg.name(), pkg.edition(), pkg.arch())
351 package = zypp.asKindPackage(pkg)
352 license = package.license()
353 self.__pkgs_content[pkg_long_name] = {} #TBD: to get file list
354 if license in self.__pkgs_license.keys():
355 self.__pkgs_license[license].append(pkg_long_name)
357 self.__pkgs_license[license] = [pkg_long_name]
359 total_count = len(dlpkgs)
361 localpkgs = self.localpkgs.keys()
362 msger.info("Checking packages cache and packages integrity ...")
364 """ Check if it is cached locally """
365 if po.name() in localpkgs:
368 local = self.getLocalPkgPath(po)
369 if os.path.exists(local):
370 if self.checkPkg(local) != 0:
374 download_count = total_count - cached_count
375 msger.info("%d packages to be installed, %d packages gotten from cache, %d packages to be downloaded" % (total_count, cached_count, download_count))
377 if download_count > 0:
378 msger.info("Downloading packages ...")
379 self.downloadPkgs(dlpkgs, download_count)
380 self.installPkgs(dlpkgs)
383 raise CreatorError("Unable to download from repo : %s" % (e,))
385 raise CreatorError("Unable to install: %s" % (e,))
387 def getAllContent(self):
388 return self.__pkgs_content
390 def getPkgsLicense(self):
391 return self.__pkgs_license
393 def __initialize_repo_manager(self):
394 if self.repo_manager:
397 """ Clean up repo metadata """
398 shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
399 shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
400 shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
402 zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
403 | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
404 | zypp.KeyRing.ACCEPT_UNKNOWNKEY
405 | zypp.KeyRing.TRUST_KEY_TEMPORARILY
407 self.repo_manager_options = zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
408 self.repo_manager_options.knownReposPath = zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
409 self.repo_manager_options.repoCachePath = zypp.Pathname(self.cachedir)
410 self.repo_manager_options.repoRawCachePath = zypp.Pathname(self.cachedir + "/raw")
411 self.repo_manager_options.repoSolvCachePath = zypp.Pathname(self.cachedir + "/solv")
412 self.repo_manager_options.repoPackagesCachePath = zypp.Pathname(self.cachedir + "/packages")
414 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
416 def __build_repo_cache(self, name):
417 repo = self.repo_manager.getRepositoryInfo(name)
418 if self.repo_manager.isCached(repo) or not repo.enabled():
420 self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
422 def __initialize_zypp(self):
426 zconfig = zypp.ZConfig_instance()
428 """ Set system architecture """
430 zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
432 msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
434 """ repoPackagesCachePath is corrected by this """
435 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
436 repos = self.repo_manager.knownRepositories()
438 if not repo.enabled():
440 self.repo_manager.loadFromCache(repo)
442 self.Z = zypp.ZYppFactory_instance().getZYpp()
443 self.Z.initializeTarget(zypp.Pathname(self.instroot))
444 self.Z.target().load()
447 def buildTransaction(self):
448 if not self.Z.resolver().resolvePool():
449 msger.warning("Problem count: %d" % len(self.Z.resolver().problems()))
450 for problem in self.Z.resolver().problems():
451 msger.warning("Problem: %s, %s" % (problem.description().decode("utf-8"), problem.details().decode("utf-8")))
453 def getLocalPkgPath(self, po):
454 repoinfo = po.repoInfo()
455 cacheroot = repoinfo.packagesPath()
456 location= zypp.asKindPackage(po).location()
457 rpmpath = str(location.filename())
458 pkgpath = "%s/%s" % (cacheroot, rpmpath)
461 def installLocal(self, pkg, po=None, updateonly=False):
463 self.__initialize_transaction()
464 solvfile = "%s/.solv" % (self.cachedir)
465 rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"), pkg])
467 f = open(solvfile, "w+")
470 warnmsg = self.repo_manager.loadSolvFile(solvfile , os.path.basename(pkg))
472 msger.warning(warnmsg)
475 msger.warning('Can not get %s solv data.' % pkg)
476 hdr = rpmmisc.readRpmHeader(self.ts, pkg)
477 arch = zypp.Arch(hdr['arch'])
478 sysarch = zypp.Arch(self.target_arch)
479 if arch.compatible_with (sysarch):
480 pkgname = hdr['name']
481 self.localpkgs[pkgname] = pkg
482 self.selectPackage(pkgname)
483 msger.info("Marking %s to be installed" % (pkg))
485 msger.warning ("Cannot add package %s to transaction. Not a compatible architecture: %s" % (pkg, hdr['arch']))
487 def downloadPkgs(self, package_objects, count):
488 localpkgs = self.localpkgs.keys()
489 progress_obj = rpmmisc.TextProgress(count)
490 for po in package_objects:
491 if po.name() in localpkgs:
493 filename = self.getLocalPkgPath(po)
494 if os.path.exists(filename):
495 if self.checkPkg(filename) == 0:
497 dirn = os.path.dirname(filename)
498 if not os.path.exists(dirn):
500 baseurl = str(po.repoInfo().baseUrls()[0])
501 index = baseurl.find("?")
503 baseurl = baseurl[:index]
504 proxy = self.get_proxy(po.repoInfo())
507 proxies = {str(proxy.split(":")[0]):str(proxy)}
509 location = zypp.asKindPackage(po).location()
510 location = str(location.filename())
511 if location.startswith("./"):
512 location = location[2:]
513 url = baseurl + "/%s" % location
515 filename = rpmmisc.myurlgrab(url, filename, proxies, progress_obj)
520 def installPkgs(self, package_objects):
522 self.__initialize_transaction()
526 for flag in self.probFilterFlags:
528 self.ts.setProbFilter(probfilter)
530 localpkgs = self.localpkgs.keys()
531 for po in package_objects:
533 if pkgname in localpkgs:
534 rpmpath = self.localpkgs[pkgname]
536 rpmpath = self.getLocalPkgPath(po)
537 if not os.path.exists(rpmpath):
538 """ Maybe it is a local repo """
539 baseurl = str(po.repoInfo().baseUrls()[0])
540 baseurl = baseurl.strip()
541 location = zypp.asKindPackage(po).location()
542 location = str(location.filename())
543 if baseurl.startswith("file:/"):
544 rpmpath = baseurl[5:] + "/%s" % (location)
545 if not os.path.exists(rpmpath):
546 raise RpmError("Error: %s doesn't exist" % rpmpath)
547 h = rpmmisc.readRpmHeader(self.ts, rpmpath)
548 self.ts.addInstall(h, rpmpath, 'u')
550 unresolved_dependencies = self.ts.check()
551 if not unresolved_dependencies:
553 cb = rpmmisc.RPMInstallCallback(self.ts)
554 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
555 msger.enable_logstderr(installlogfile)
556 errors = self.ts.run(cb.callback, '')
559 elif len(errors) == 0:
560 msger.warning('scriptlet or other non-fatal errors occurred during transaction.')
564 msger.error('Could not run transaction.')
565 msger.disable_logstderr()
570 for pkg, need, needflags, sense, key in unresolved_dependencies:
571 package = '-'.join(pkg)
572 if needflags == rpm.RPMSENSE_LESS:
573 deppkg = ' < '.join(need)
574 elif needflags == rpm.RPMSENSE_EQUAL:
575 deppkg = ' = '.join(need)
576 elif needflags == rpm.RPMSENSE_GREATER:
577 deppkg = ' > '.join(need)
579 deppkg = '-'.join(need)
581 if sense == rpm.RPMDEP_SENSE_REQUIRES:
582 msger.warning ("[%s] Requires [%s], which is not provided" % (package, deppkg))
583 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
584 msger.warning ("[%s] Conflicts with [%s]" % (package, deppkg))
586 raise RepoError("Unresolved dependencies, transaction failed.")
588 def __initialize_transaction(self):
590 self.ts = rpm.TransactionSet(self.instroot)
591 # Set to not verify DSA signatures.
592 self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
594 def checkPkg(self, pkg):
596 if not os.path.exists(pkg):
598 ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
600 msger.warning("package %s is damaged: %s" % (os.path.basename(pkg), pkg))
604 def _add_prob_flags(self, *flags):
606 if flag not in self.probFilterFlags:
607 self.probFilterFlags.append(flag)
609 def get_proxy(self, repoinfo):
611 reponame = "%s" % repoinfo.name()
612 for repo in self.repos:
613 if repo.name == reponame:
620 repourl = str(repoinfo.baseUrls()[0])
621 return get_proxy_for(repourl)