extract rpm listed in attachment which not found in rootfs
[tools/mic.git] / plugins / backend / zypppkgmgr.py
1 #!/usr/bin/python -tt
2 #
3 # Copyright (c) 2010, 2011 Intel, Inc.
4 #
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
8 #
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
12 # for more details.
13 #
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.
17
18 import os
19 import shutil
20 import urlparse
21 import rpm
22
23 import zypp
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")
29
30 from mic import msger
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
36
37 class RepositoryStub:
38     def __init__(self):
39         self.name = None
40         self.baseurl = []
41         self.mirrorlist = None
42         self.proxy = None
43         self.proxy_username = None
44         self.proxy_password = None
45
46         self.enabled = True
47         self.autorefresh = True
48         self.keeppackages = True
49         self.priority = None
50
51 from mic.pluginbase import BackendPlugin
52 class Zypp(BackendPlugin):
53     name = 'zypp'
54
55     def __init__(self, target_arch, instroot, cachedir):
56         self.cachedir = cachedir
57         self.instroot  = instroot
58         self.target_arch = target_arch
59
60         self.__pkgs_license = {}
61         self.__pkgs_content = {}
62         self.repos = []
63         self.to_deselect = []
64         self.localpkgs = {}
65         self.repo_manager = None
66         self.repo_manager_options = None
67         self.Z = None
68         self.ts = None
69         self.ts_pre = None
70         self.incpkgs = {}
71         self.excpkgs = {}
72         self.pre_pkgs = []
73         self.probFilterFlags = [ rpm.RPMPROB_FILTER_OLDPACKAGE,
74                                  rpm.RPMPROB_FILTER_REPLACEPKG ]
75
76         self.has_prov_query = True
77
78     def doFileLogSetup(self, uid, logfile):
79         # don't do the file log for the livecd as it can lead to open fds
80         # being left and an inability to clean up after ourself
81         pass
82
83     def closeRpmDB(self):
84         pass
85
86     def close(self):
87         if self.ts:
88             self.ts.closeDB()
89             self.ts = None
90
91         if self.ts_pre:
92             self.ts_pre.closeDB()
93             self.ts = None
94
95         self.closeRpmDB()
96
97         if not os.path.exists("/etc/fedora-release") and \
98            not os.path.exists("/etc/meego-release"):
99             for i in range(3, os.sysconf("SC_OPEN_MAX")):
100                 try:
101                     os.close(i)
102                 except:
103                     pass
104
105     def __del__(self):
106         self.close()
107
108     def _cleanupRpmdbLocks(self, installroot):
109         # cleans up temporary files left by bdb so that differing
110         # versions of rpm don't cause problems
111         import glob
112         for f in glob.glob(installroot + "/var/lib/rpm/__db*"):
113             os.unlink(f)
114
115     def setup(self):
116         self._cleanupRpmdbLocks(self.instroot)
117
118     def whatObsolete(self, pkg):
119         query = zypp.PoolQuery()
120         query.addKind(zypp.ResKind.package)
121         query.addAttribute(zypp.SolvAttr.obsoletes, pkg)
122         query.setMatchExact()
123         for pi in query.queryResults(self.Z.pool()):
124             return pi
125         return None
126
127     def _splitPkgString(self, pkg):
128         sp = pkg.rsplit(".",1)
129         name = sp[0]
130         arch = None
131         if len(sp) == 2:
132             arch = sp[1]
133             sysarch = zypp.Arch(self.target_arch)
134             if not zypp.Arch(arch).compatible_with (sysarch):
135                 arch = None
136                 name = ".".join(sp)
137         return name, arch
138
139     def selectPackage(self, pkg):
140         """Select a given package or package pattern, can be specified
141         with name.arch or name* or *name
142         """
143
144         if not self.Z:
145             self.__initialize_zypp()
146
147         def markPoolItem(obs, pi):
148             if obs == None:
149                 pi.status().setToBeInstalled (zypp.ResStatus.USER)
150             else:
151                 obs.status().setToBeInstalled (zypp.ResStatus.USER)
152
153         def cmpEVR(ed1, ed2):
154             (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
155             (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
156             return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
157
158         found = False
159         startx = pkg.startswith("*")
160         endx = pkg.endswith("*")
161         ispattern = startx or endx
162         name, arch = self._splitPkgString(pkg)
163
164         q = zypp.PoolQuery()
165         q.addKind(zypp.ResKind.package)
166
167         if ispattern:
168             if startx and not endx:
169                 pattern = '%s$' % (pkg[1:])
170             if endx and not startx:
171                 pattern = '^%s' % (pkg[0:-1])
172             if endx and startx:
173                 pattern = '%s' % (pkg[1:-1])
174             q.setMatchRegex()
175             q.addAttribute(zypp.SolvAttr.name,pattern)
176
177         elif arch:
178             q.setMatchExact()
179             q.addAttribute(zypp.SolvAttr.name,name)
180
181         else:
182             q.setMatchExact()
183             q.addAttribute(zypp.SolvAttr.name,pkg)
184
185         for item in sorted(
186                         q.queryResults(self.Z.pool()),
187                         cmp=lambda x,y: cmpEVR(x.edition(), y.edition()),
188                         reverse=True):
189
190             if item.name() in self.excpkgs.keys() and \
191                self.excpkgs[item.name()] == item.repoInfo().name():
192                 continue
193             if item.name() in self.incpkgs.keys() and \
194                self.incpkgs[item.name()] != item.repoInfo().name():
195                 continue
196
197             found = True
198             obspkg = self.whatObsolete(item.name())
199             if arch:
200                 if arch == str(item.arch()):
201                     item.status().setToBeInstalled (zypp.ResStatus.USER)
202             else:
203                 markPoolItem(obspkg, item)
204             if not ispattern:
205                 break
206
207         # Can't match using package name, then search from packge
208         # provides infomation
209         if found == False and not ispattern:
210             q.addAttribute(zypp.SolvAttr.provides, pkg)
211             q.addAttribute(zypp.SolvAttr.name,'')
212
213             for item in sorted(
214                             q.queryResults(self.Z.pool()),
215                             cmp=lambda x,y: cmpEVR(x.edition(), y.edition()),
216                             reverse=True):
217                 if item.name() in self.excpkgs.keys() and \
218                    self.excpkgs[item.name()] == item.repoInfo().name():
219                     continue
220                 if item.name() in self.incpkgs.keys() and \
221                    self.incpkgs[item.name()] != item.repoInfo().name():
222                     continue
223
224                 found = True
225                 obspkg = self.whatObsolete(item.name())
226                 markPoolItem(obspkg, item)
227                 break
228
229         if found:
230             return None
231         else:
232             raise CreatorError("Unable to find package: %s" % (pkg,))
233
234     def inDeselectPackages(self, item):
235         """check if specified pacakges are in the list of inDeselectPackages
236         """
237
238         name = item.name()
239         for pkg in self.to_deselect:
240             startx = pkg.startswith("*")
241             endx = pkg.endswith("*")
242             ispattern = startx or endx
243             pkgname, pkgarch = self._splitPkgString(pkg)
244             if not ispattern:
245                 if pkgarch:
246                     if name == pkgname and str(item.arch()) == pkgarch:
247                         return True;
248                 else:
249                     if name == pkgname:
250                         return True;
251             else:
252                 if startx and name.endswith(pkg[1:]):
253                         return True;
254                 if endx and name.startswith(pkg[:-1]):
255                         return True;
256
257         return False;
258
259     def deselectPackage(self, pkg):
260         """collect packages should not be installed"""
261         self.to_deselect.append(pkg)
262
263     def selectGroup(self, grp, include = ksparser.GROUP_DEFAULT):
264         if not self.Z:
265             self.__initialize_zypp()
266         found = False
267         q=zypp.PoolQuery()
268         q.addKind(zypp.ResKind.pattern)
269         for item in q.queryResults(self.Z.pool()):
270             summary = "%s" % item.summary()
271             name = "%s" % item.name()
272             if name == grp or summary == grp:
273                 found = True
274                 item.status().setToBeInstalled (zypp.ResStatus.USER)
275                 break
276
277         if found:
278             if include == ksparser.GROUP_REQUIRED:
279                 map(
280                     lambda p: self.deselectPackage(p),
281                     grp.default_packages.keys())
282
283             return None
284         else:
285             raise CreatorError("Unable to find pattern: %s" % (grp,))
286
287     def addRepository(self, name,
288                             url = None,
289                             mirrorlist = None,
290                             proxy = None,
291                             proxy_username = None,
292                             proxy_password = None,
293                             inc = None,
294                             exc = None,
295                             ssl_verify = True,
296                             cost=None,
297                             priority=None):
298         # TODO: Handle cost attribute for repos
299
300         if not self.repo_manager:
301             self.__initialize_repo_manager()
302
303         if not proxy and url:
304             proxy = get_proxy_for(url)
305
306         repo = RepositoryStub()
307         repo.name = name
308         repo.id = name
309         repo.proxy = proxy
310         repo.proxy_username = proxy_username
311         repo.proxy_password = proxy_password
312         repo.ssl_verify = ssl_verify
313         repo.baseurl.append(url)
314         if inc:
315             for pkg in inc:
316                 self.incpkgs[pkg] = name
317         if exc:
318             for pkg in exc:
319                 self.excpkgs[pkg] = name
320
321         # check LICENSE files
322         if not rpmmisc.checkRepositoryEULA(name, repo):
323             msger.warning('skip repo:%s for failed EULA confirmation' % name)
324             return None
325
326         if mirrorlist:
327             repo.mirrorlist = mirrorlist
328
329         # Enable gpg check for verifying corrupt packages
330         repo.gpgcheck = 1
331         if priority:
332             repo.priority = priority
333         self.repos.append(repo)
334
335         try:
336             repo_info = zypp.RepoInfo()
337             repo_info.setAlias(repo.name)
338             repo_info.setName(repo.name)
339             repo_info.setEnabled(repo.enabled)
340             repo_info.setAutorefresh(repo.autorefresh)
341             repo_info.setKeepPackages(repo.keeppackages)
342             baseurl = zypp.Url(repo.baseurl[0])
343             if not ssl_verify:
344                 baseurl.setQueryParam("ssl_verify", "no")
345             if proxy:
346                 scheme, host, path, parm, query, frag = urlparse.urlparse(proxy)
347
348                 proxyinfo = host.split(":")
349                 host = proxyinfo[0]
350
351                 port = "80"
352                 if len(proxyinfo) > 1:
353                     port = proxyinfo[1]
354
355                 if proxy.startswith("socks") and len(proxy.rsplit(':', 1)) == 2:
356                     host = proxy.rsplit(':', 1)[0]
357                     port = proxy.rsplit(':', 1)[1]
358
359                 baseurl.setQueryParam ("proxy", host)
360                 baseurl.setQueryParam ("proxyport", port)
361
362             repo_info.addBaseUrl(baseurl)
363
364             if repo.priority:
365                 repo_info.setPriority(repo.priority)
366
367             self.repo_manager.addRepository(repo_info)
368
369             self.__build_repo_cache(name)
370
371         except RuntimeError, e:
372             raise CreatorError(str(e))
373
374         msger.verbose('repo: %s was added' % name)
375         return repo
376
377     def installHasFile(self, file):
378         return False
379
380     def preInstall(self, pkg):
381         self.pre_pkgs.append(pkg)
382
383     def runInstall(self, checksize = 0):
384         os.environ["HOME"] = "/"
385         self.buildTransaction()
386
387         todo = zypp.GetResolvablesToInsDel(self.Z.pool())
388         installed_pkgs = todo._toInstall
389         dlpkgs = []
390         for item in installed_pkgs:
391             if not zypp.isKindPattern(item) and \
392                not self.inDeselectPackages(item):
393                 dlpkgs.append(item)
394
395         # record all pkg and the content
396         localpkgs = self.localpkgs.keys()
397         for pkg in dlpkgs:
398             license = ''
399             if pkg.name() in localpkgs:
400                 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
401                 pkg_long_name = misc.RPM_FMT % {
402                                     'name': hdr['name'],
403                                     'arch': hdr['arch'],
404                                     'ver_rel': '%s-%s' % (hdr['version'],
405                                                           hdr['release']),
406                                 }
407                 license = hdr['license']
408
409             else:
410                 pkg_long_name = misc.RPM_FMT % {
411                                     'name': pkg.name(),
412                                     'arch': pkg.arch(),
413                                     'ver_rel': pkg.edition(),
414                                 }
415
416                 package = zypp.asKindPackage(pkg)
417                 license = package.license()
418
419             self.__pkgs_content[pkg_long_name] = {} #TBD: to get file list
420
421             if license in self.__pkgs_license.keys():
422                 self.__pkgs_license[license].append(pkg_long_name)
423             else:
424                 self.__pkgs_license[license] = [pkg_long_name]
425
426         total_count = len(dlpkgs)
427         cached_count = 0
428         download_total_size = sum(map(lambda x: int(x.downloadSize()), dlpkgs))
429         localpkgs = self.localpkgs.keys()
430
431         msger.info("Checking packages cache and packages integrity ...")
432         for po in dlpkgs:
433             # Check if it is cached locally
434             if po.name() in localpkgs:
435                 cached_count += 1
436             else:
437                 local = self.getLocalPkgPath(po)
438                 if os.path.exists(local):
439                     if self.checkPkg(local) != 0:
440                         os.unlink(local)
441                     else:
442                         download_total_size -= int(po.downloadSize())
443                         cached_count += 1
444         cache_avail_size = misc.get_filesystem_avail(self.cachedir)
445         if cache_avail_size < download_total_size:
446             raise CreatorError("No enough space used for downloading.")
447
448         # record the total size of installed pkgs
449         install_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
450         # check needed size before actually download and install
451
452         # FIXME: for multiple partitions for loop type, check fails
453         #        skip the check temporarily
454         #if checksize and install_total_size > checksize:
455         #    raise CreatorError("No enough space used for installing, "
456         #                       "please resize partition size in ks file")
457
458         download_count =  total_count - cached_count
459         msger.info("%d packages to be installed, "
460                    "%d packages gotten from cache, "
461                    "%d packages to be downloaded" \
462                    % (total_count, cached_count, download_count))
463
464         try:
465             if download_count > 0:
466                 msger.info("Downloading packages ...")
467             self.downloadPkgs(dlpkgs, download_count)
468
469             self.installPkgs(dlpkgs)
470
471         except (RepoError, RpmError):
472             raise
473         except Exception, e:
474             raise CreatorError("Package installation failed: %s" % (e,))
475
476     def getAllContent(self):
477         return self.__pkgs_content
478
479     def getPkgsLicense(self):
480         return self.__pkgs_license
481
482     def getFilelist(self, pkgname):
483         if not pkgname:
484             return None
485
486         if not self.ts:
487             self.__initialize_transaction()
488
489         mi = self.ts.dbMatch('name', pkgname)
490         for header in mi:
491             return header['FILENAMES']
492
493     def __initialize_repo_manager(self):
494         if self.repo_manager:
495             return
496
497         # Clean up repo metadata
498         shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
499         shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
500         shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
501
502         zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
503                                      | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
504                                      | zypp.KeyRing.ACCEPT_UNKNOWNKEY
505                                      | zypp.KeyRing.TRUST_KEY_TEMPORARILY
506                                      )
507
508         self.repo_manager_options = \
509                 zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
510
511         self.repo_manager_options.knownReposPath = \
512                 zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
513
514         self.repo_manager_options.repoCachePath = \
515                 zypp.Pathname(self.cachedir)
516
517         self.repo_manager_options.repoRawCachePath = \
518                 zypp.Pathname(self.cachedir + "/raw")
519
520         self.repo_manager_options.repoSolvCachePath = \
521                 zypp.Pathname(self.cachedir + "/solv")
522
523         self.repo_manager_options.repoPackagesCachePath = \
524                 zypp.Pathname(self.cachedir + "/packages")
525
526         self.repo_manager = zypp.RepoManager(self.repo_manager_options)
527
528     def __build_repo_cache(self, name):
529         repo = self.repo_manager.getRepositoryInfo(name)
530         if self.repo_manager.isCached(repo) or not repo.enabled():
531             return
532
533         msger.info('Refreshing repository: %s ...' % name)
534         self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
535
536     def __initialize_zypp(self):
537         if self.Z:
538             return
539
540         zconfig = zypp.ZConfig_instance()
541
542         # Set system architecture
543         if self.target_arch:
544             zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
545
546         msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
547
548         # repoPackagesCachePath is corrected by this
549         self.repo_manager = zypp.RepoManager(self.repo_manager_options)
550         repos = self.repo_manager.knownRepositories()
551         for repo in repos:
552             if not repo.enabled():
553                 continue
554             self.repo_manager.loadFromCache(repo)
555
556         self.Z = zypp.ZYppFactory_instance().getZYpp()
557         self.Z.initializeTarget(zypp.Pathname(self.instroot))
558         self.Z.target().load()
559
560     def buildTransaction(self):
561         if not self.Z.resolver().resolvePool():
562             probs = self.Z.resolver().problems()
563
564             for problem in probs:
565                 msger.warning("repo problem: %s, %s" \
566                               % (problem.description().decode("utf-8"),
567                                  problem.details().decode("utf-8")))
568
569             raise RepoError("found %d resolver problem, abort!" \
570                             % len(probs))
571
572     def getLocalPkgPath(self, po):
573         repoinfo = po.repoInfo()
574         cacheroot = repoinfo.packagesPath()
575         location= zypp.asKindPackage(po).location()
576         rpmpath = str(location.filename())
577         pkgpath = "%s/%s" % (cacheroot, os.path.basename(rpmpath))
578         return pkgpath
579
580     def installLocal(self, pkg, po=None, updateonly=False):
581         if not self.ts:
582             self.__initialize_transaction()
583
584         solvfile = "%s/.solv" % (self.cachedir)
585
586         rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"),
587                                   pkg])
588         if rc == 0:
589             f = open(solvfile, "w+")
590             f.write(out)
591             f.close()
592
593             warnmsg = self.repo_manager.loadSolvFile(solvfile,
594                                                      os.path.basename(pkg))
595             if warnmsg:
596                 msger.warning(warnmsg)
597
598             os.unlink(solvfile)
599         else:
600             msger.warning('Can not get %s solv data.' % pkg)
601
602         hdr = rpmmisc.readRpmHeader(self.ts, pkg)
603         arch = zypp.Arch(hdr['arch'])
604         sysarch = zypp.Arch(self.target_arch)
605
606         if arch.compatible_with (sysarch):
607             pkgname = hdr['name']
608             self.localpkgs[pkgname] = pkg
609             self.selectPackage(pkgname)
610             msger.info("Marking %s to be installed" % (pkg))
611
612         else:
613             msger.warning("Cannot add package %s to transaction. "
614                           "Not a compatible architecture: %s" \
615                           % (pkg, hdr['arch']))
616
617     def downloadPkgs(self, package_objects, count):
618         localpkgs = self.localpkgs.keys()
619         progress_obj = rpmmisc.TextProgress(count)
620
621         for po in package_objects:
622             if po.name() in localpkgs:
623                 continue
624
625             filename = self.getLocalPkgPath(po)
626             if os.path.exists(filename):
627                 if self.checkPkg(filename) == 0:
628                     continue
629
630             dirn = os.path.dirname(filename)
631             if not os.path.exists(dirn):
632                 os.makedirs(dirn)
633
634             baseurl = str(po.repoInfo().baseUrls()[0])
635             index = baseurl.find("?")
636             if index > -1:
637                 baseurl = baseurl[:index]
638
639             proxy = self.get_proxy(po.repoInfo())
640             proxies = {}
641             if proxy:
642                 proxies = {str(proxy.split(":")[0]):str(proxy)}
643
644             location = zypp.asKindPackage(po).location()
645             location = str(location.filename())
646             if location.startswith("./"):
647                 location = location[2:]
648
649             url = baseurl + "/%s" % location
650
651             try:
652                 filename = rpmmisc.myurlgrab(url,
653                                              filename,
654                                              proxies,
655                                              progress_obj)
656             except CreatorError:
657                 self.close()
658                 raise
659
660     def preinstallPkgs(self):
661         if not self.ts_pre:
662             self.__initialize_transaction()
663
664         self.ts_pre.order()
665         cb = rpmmisc.RPMInstallCallback(self.ts_pre)
666         cb.headmsg = "Preinstall"
667         installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
668
669         # start to catch stderr output from librpm
670         msger.enable_logstderr(installlogfile)
671
672         errors = self.ts_pre.run(cb.callback, '')
673         # stop catch
674         msger.disable_logstderr()
675         self.ts_pre.closeDB()
676         self.ts_pre = None
677
678         if errors is not None:
679             if len(errors) == 0:
680                 msger.warning('scriptlet or other non-fatal errors occurred '
681                               'during transaction.')
682
683             else:
684                 for e in errors:
685                     msger.warning(e[0])
686                 raise RepoError('Could not run transaction.')
687
688     def installPkgs(self, package_objects):
689         if not self.ts:
690             self.__initialize_transaction()
691
692         # Set filters
693         probfilter = 0
694         for flag in self.probFilterFlags:
695             probfilter |= flag
696         self.ts.setProbFilter(probfilter)
697         self.ts_pre.setProbFilter(probfilter)
698
699         localpkgs = self.localpkgs.keys()
700
701         for po in package_objects:
702             pkgname = po.name()
703             if pkgname in localpkgs:
704                 rpmpath = self.localpkgs[pkgname]
705             else:
706                 rpmpath = self.getLocalPkgPath(po)
707
708             if not os.path.exists(rpmpath):
709                 # Maybe it is a local repo
710                 baseurl = str(po.repoInfo().baseUrls()[0])
711                 baseurl = baseurl.strip()
712
713                 location = zypp.asKindPackage(po).location()
714                 location = str(location.filename())
715
716                 if baseurl.startswith("file:/"):
717                     rpmpath = baseurl[5:] + "/%s" % (location)
718
719             if not os.path.exists(rpmpath):
720                 raise RpmError("Error: %s doesn't exist" % rpmpath)
721
722             h = rpmmisc.readRpmHeader(self.ts, rpmpath)
723
724             if pkgname in self.pre_pkgs:
725                 msger.verbose("pre-install package added: %s" % pkgname)
726                 self.ts_pre.addInstall(h, rpmpath, 'u')
727
728             self.ts.addInstall(h, rpmpath, 'u')
729
730         unresolved_dependencies = self.ts.check()
731         if not unresolved_dependencies:
732             if self.pre_pkgs:
733                 self.preinstallPkgs()
734
735             self.ts.order()
736             cb = rpmmisc.RPMInstallCallback(self.ts)
737             installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
738
739             # start to catch stderr output from librpm
740             msger.enable_logstderr(installlogfile)
741
742             errors = self.ts.run(cb.callback, '')
743             # stop catch
744             msger.disable_logstderr()
745             self.ts.closeDB()
746             self.ts = None
747
748             if errors is not None:
749                 if len(errors) == 0:
750                     msger.warning('scriptlet or other non-fatal errors occurred '
751                                   'during transaction.')
752
753                 else:
754                     for e in errors:
755                         msger.warning(e[0])
756                     raise RepoError('Could not run transaction.')
757
758         else:
759             for pkg, need, needflags, sense, key in unresolved_dependencies:
760                 package = '-'.join(pkg)
761
762                 if needflags == rpm.RPMSENSE_LESS:
763                     deppkg = ' < '.join(need)
764                 elif needflags == rpm.RPMSENSE_EQUAL:
765                     deppkg = ' = '.join(need)
766                 elif needflags == rpm.RPMSENSE_GREATER:
767                     deppkg = ' > '.join(need)
768                 else:
769                     deppkg = '-'.join(need)
770
771                 if sense == rpm.RPMDEP_SENSE_REQUIRES:
772                     msger.warning("[%s] Requires [%s], which is not provided" \
773                                   % (package, deppkg))
774
775                 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
776                     msger.warning("[%s] Conflicts with [%s]" %(package,deppkg))
777
778             raise RepoError("Unresolved dependencies, transaction failed.")
779
780     def __initialize_transaction(self):
781         if not self.ts:
782             self.ts = rpm.TransactionSet(self.instroot)
783             # Set to not verify DSA signatures.
784             self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
785
786         if not self.ts_pre:
787             self.ts_pre = rpm.TransactionSet(self.instroot)
788             # Just unpack the files, don't run scripts
789             self.ts_pre.setFlags(rpm.RPMTRANS_FLAG_ALLFILES | rpm.RPMTRANS_FLAG_NOSCRIPTS)
790             # Set to not verify DSA signatures.
791             self.ts_pre.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
792
793     def checkPkg(self, pkg):
794         ret = 1
795         if not os.path.exists(pkg):
796             return ret
797         ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
798         if ret != 0:
799             msger.warning("package %s is damaged: %s" \
800                           % (os.path.basename(pkg), pkg))
801
802         return ret
803
804     def _add_prob_flags(self, *flags):
805         for flag in flags:
806            if flag not in self.probFilterFlags:
807                self.probFilterFlags.append(flag)
808
809     def get_proxy(self, repoinfo):
810         proxy = None
811         reponame = "%s" % repoinfo.name()
812         for repo in self.repos:
813             if repo.name == reponame:
814                 proxy = repo.proxy
815                 break
816
817         if proxy:
818             return proxy
819         else:
820             repourl = str(repoinfo.baseUrls()[0])
821             return get_proxy_for(repourl)
822
823     def package_url(self, pkg):
824
825         def cmpEVR(ed1, ed2):
826             (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
827             (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
828             return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
829
830         if not self.Z:
831             self.__initialize_zypp()
832
833         q = zypp.PoolQuery()
834         q.addKind(zypp.ResKind.package)
835         q.setMatchExact()
836         q.addAttribute(zypp.SolvAttr.name,pkg)
837         items = sorted(q.queryResults(self.Z.pool()),
838                        cmp=lambda x,y: cmpEVR(x.edition(), y.edition()),
839                        reverse=True)
840
841         if items:
842             baseurl = items[0].repoInfo().baseUrls()[0]
843             location = zypp.asKindPackage(items[0]).location()
844             return os.path.join(str(baseurl), str(location.filename()))
845
846         return None