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 all pkg and the content
335 localpkgs = self.localpkgs.keys()
338 if pkg.name() in localpkgs:
339 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
340 pkg_long_name = "%s-%s-%s.%s.rpm" % (hdr['name'], hdr['version'], hdr['release'], hdr['arch'])
341 license = hdr['license']
343 pkg_long_name = "%s-%s.%s.rpm" % (pkg.name(), pkg.edition(), pkg.arch())
344 package = zypp.asKindPackage(pkg)
345 license = package.license()
346 self.__pkgs_content[pkg_long_name] = {} #TBD: to get file list
347 if license in self.__pkgs_license.keys():
348 self.__pkgs_license[license].append(pkg_long_name)
350 self.__pkgs_license[license] = [pkg_long_name]
352 total_count = len(dlpkgs)
354 download_total_size = 0L
355 localpkgs = self.localpkgs.keys()
356 msger.info("Checking packages cache and packages integrity ...")
358 """ Check if it is cached locally """
359 if po.name() in localpkgs:
362 local = self.getLocalPkgPath(po)
363 if os.path.exists(local):
364 if self.checkPkg(local) != 0:
365 download_total_size += po.downloadSize()
370 # record the total size of installed pkgs
371 install_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
372 # check needed size before actually download and install
373 if checksize and download_total_size + install_total_size > checksize:
374 raise CreatorError("No enough space used for downloading and installing")
376 download_count = total_count - cached_count
377 msger.info("%d packages to be installed, %d packages gotten from cache, %d packages to be downloaded" % (total_count, cached_count, download_count))
379 if download_count > 0:
380 msger.info("Downloading packages ...")
381 self.downloadPkgs(dlpkgs, download_count)
382 self.installPkgs(dlpkgs)
385 raise CreatorError("Unable to download from repo : %s" % (e,))
387 raise CreatorError("Unable to install: %s" % (e,))
389 def getAllContent(self):
390 return self.__pkgs_content
392 def getPkgsLicense(self):
393 return self.__pkgs_license
395 def __initialize_repo_manager(self):
396 if self.repo_manager:
399 """ Clean up repo metadata """
400 shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
401 shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
402 shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
404 zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
405 | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
406 | zypp.KeyRing.ACCEPT_UNKNOWNKEY
407 | zypp.KeyRing.TRUST_KEY_TEMPORARILY
409 self.repo_manager_options = zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
410 self.repo_manager_options.knownReposPath = zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
411 self.repo_manager_options.repoCachePath = zypp.Pathname(self.cachedir)
412 self.repo_manager_options.repoRawCachePath = zypp.Pathname(self.cachedir + "/raw")
413 self.repo_manager_options.repoSolvCachePath = zypp.Pathname(self.cachedir + "/solv")
414 self.repo_manager_options.repoPackagesCachePath = zypp.Pathname(self.cachedir + "/packages")
416 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
418 def __build_repo_cache(self, name):
419 repo = self.repo_manager.getRepositoryInfo(name)
420 if self.repo_manager.isCached(repo) or not repo.enabled():
422 self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
424 def __initialize_zypp(self):
428 zconfig = zypp.ZConfig_instance()
430 """ Set system architecture """
432 zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
434 msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
436 """ repoPackagesCachePath is corrected by this """
437 self.repo_manager = zypp.RepoManager(self.repo_manager_options)
438 repos = self.repo_manager.knownRepositories()
440 if not repo.enabled():
442 self.repo_manager.loadFromCache(repo)
444 self.Z = zypp.ZYppFactory_instance().getZYpp()
445 self.Z.initializeTarget(zypp.Pathname(self.instroot))
446 self.Z.target().load()
449 def buildTransaction(self):
450 if not self.Z.resolver().resolvePool():
451 msger.warning("Problem count: %d" % len(self.Z.resolver().problems()))
452 for problem in self.Z.resolver().problems():
453 msger.warning("Problem: %s, %s" % (problem.description().decode("utf-8"), problem.details().decode("utf-8")))
455 def getLocalPkgPath(self, po):
456 repoinfo = po.repoInfo()
457 cacheroot = repoinfo.packagesPath()
458 location= zypp.asKindPackage(po).location()
459 rpmpath = str(location.filename())
460 pkgpath = "%s/%s" % (cacheroot, rpmpath)
463 def installLocal(self, pkg, po=None, updateonly=False):
465 self.__initialize_transaction()
466 solvfile = "%s/.solv" % (self.cachedir)
467 rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"), pkg])
469 f = open(solvfile, "w+")
472 warnmsg = self.repo_manager.loadSolvFile(solvfile , os.path.basename(pkg))
474 msger.warning(warnmsg)
477 msger.warning('Can not get %s solv data.' % pkg)
478 hdr = rpmmisc.readRpmHeader(self.ts, pkg)
479 arch = zypp.Arch(hdr['arch'])
480 sysarch = zypp.Arch(self.target_arch)
481 if arch.compatible_with (sysarch):
482 pkgname = hdr['name']
483 self.localpkgs[pkgname] = pkg
484 self.selectPackage(pkgname)
485 msger.info("Marking %s to be installed" % (pkg))
487 msger.warning ("Cannot add package %s to transaction. Not a compatible architecture: %s" % (pkg, hdr['arch']))
489 def downloadPkgs(self, package_objects, count):
490 localpkgs = self.localpkgs.keys()
491 progress_obj = rpmmisc.TextProgress(count)
492 for po in package_objects:
493 if po.name() in localpkgs:
495 filename = self.getLocalPkgPath(po)
496 if os.path.exists(filename):
497 if self.checkPkg(filename) == 0:
499 dirn = os.path.dirname(filename)
500 if not os.path.exists(dirn):
502 baseurl = str(po.repoInfo().baseUrls()[0])
503 index = baseurl.find("?")
505 baseurl = baseurl[:index]
506 proxy = self.get_proxy(po.repoInfo())
509 proxies = {str(proxy.split(":")[0]):str(proxy)}
511 location = zypp.asKindPackage(po).location()
512 location = str(location.filename())
513 if location.startswith("./"):
514 location = location[2:]
515 url = baseurl + "/%s" % location
517 filename = rpmmisc.myurlgrab(url, filename, proxies, progress_obj)
522 def installPkgs(self, package_objects):
524 self.__initialize_transaction()
528 for flag in self.probFilterFlags:
530 self.ts.setProbFilter(probfilter)
532 localpkgs = self.localpkgs.keys()
533 for po in package_objects:
535 if pkgname in localpkgs:
536 rpmpath = self.localpkgs[pkgname]
538 rpmpath = self.getLocalPkgPath(po)
539 if not os.path.exists(rpmpath):
540 """ Maybe it is a local repo """
541 baseurl = str(po.repoInfo().baseUrls()[0])
542 baseurl = baseurl.strip()
543 location = zypp.asKindPackage(po).location()
544 location = str(location.filename())
545 if baseurl.startswith("file:/"):
546 rpmpath = baseurl[5:] + "/%s" % (location)
547 if not os.path.exists(rpmpath):
548 raise RpmError("Error: %s doesn't exist" % rpmpath)
549 h = rpmmisc.readRpmHeader(self.ts, rpmpath)
550 self.ts.addInstall(h, rpmpath, 'u')
552 unresolved_dependencies = self.ts.check()
553 if not unresolved_dependencies:
555 cb = rpmmisc.RPMInstallCallback(self.ts)
556 installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
557 msger.enable_logstderr(installlogfile)
558 errors = self.ts.run(cb.callback, '')
561 elif len(errors) == 0:
562 msger.warning('scriptlet or other non-fatal errors occurred during transaction.')
566 msger.error('Could not run transaction.')
567 msger.disable_logstderr()
572 for pkg, need, needflags, sense, key in unresolved_dependencies:
573 package = '-'.join(pkg)
574 if needflags == rpm.RPMSENSE_LESS:
575 deppkg = ' < '.join(need)
576 elif needflags == rpm.RPMSENSE_EQUAL:
577 deppkg = ' = '.join(need)
578 elif needflags == rpm.RPMSENSE_GREATER:
579 deppkg = ' > '.join(need)
581 deppkg = '-'.join(need)
583 if sense == rpm.RPMDEP_SENSE_REQUIRES:
584 msger.warning ("[%s] Requires [%s], which is not provided" % (package, deppkg))
585 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
586 msger.warning ("[%s] Conflicts with [%s]" % (package, deppkg))
588 raise RepoError("Unresolved dependencies, transaction failed.")
590 def __initialize_transaction(self):
592 self.ts = rpm.TransactionSet(self.instroot)
593 # Set to not verify DSA signatures.
594 self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
596 def checkPkg(self, pkg):
598 if not os.path.exists(pkg):
600 ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
602 msger.warning("package %s is damaged: %s" % (os.path.basename(pkg), pkg))
606 def _add_prob_flags(self, *flags):
608 if flag not in self.probFilterFlags:
609 self.probFilterFlags.append(flag)
611 def get_proxy(self, repoinfo):
613 reponame = "%s" % repoinfo.name()
614 for repo in self.repos:
615 if repo.name == reponame:
622 repourl = str(repoinfo.baseUrls()[0])
623 return get_proxy_for(repourl)