fix zypp missing password when using username:passwd pattern url
[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
334         try:
335             repo_info = zypp.RepoInfo()
336             repo_info.setAlias(repo.name)
337             repo_info.setName(repo.name)
338             repo_info.setEnabled(repo.enabled)
339             repo_info.setAutorefresh(repo.autorefresh)
340             repo_info.setKeepPackages(repo.keeppackages)
341             baseurl = zypp.Url(repo.baseurl[0])
342             if not ssl_verify:
343                 baseurl.setQueryParam("ssl_verify", "no")
344             if proxy:
345                 scheme, host, path, parm, query, frag = urlparse.urlparse(proxy)
346
347                 proxyinfo = host.split(":")
348                 host = proxyinfo[0]
349
350                 port = "80"
351                 if len(proxyinfo) > 1:
352                     port = proxyinfo[1]
353
354                 if proxy.startswith("socks") and len(proxy.rsplit(':', 1)) == 2:
355                     host = proxy.rsplit(':', 1)[0]
356                     port = proxy.rsplit(':', 1)[1]
357
358                 baseurl.setQueryParam ("proxy", host)
359                 baseurl.setQueryParam ("proxyport", port)
360
361             repo.baseurl[0] = baseurl.asCompleteString()
362             self.repos.append(repo)
363
364             repo_info.addBaseUrl(baseurl)
365
366             if repo.priority:
367                 repo_info.setPriority(repo.priority)
368
369             self.repo_manager.addRepository(repo_info)
370
371             self.__build_repo_cache(name)
372
373         except RuntimeError, e:
374             raise CreatorError(str(e))
375
376         msger.verbose('repo: %s was added' % name)
377         return repo
378
379     def installHasFile(self, file):
380         return False
381
382     def preInstall(self, pkg):
383         self.pre_pkgs.append(pkg)
384
385     def runInstall(self, checksize = 0):
386         os.environ["HOME"] = "/"
387         self.buildTransaction()
388
389         todo = zypp.GetResolvablesToInsDel(self.Z.pool())
390         installed_pkgs = todo._toInstall
391         dlpkgs = []
392         for item in installed_pkgs:
393             if not zypp.isKindPattern(item) and \
394                not self.inDeselectPackages(item):
395                 dlpkgs.append(item)
396
397         # record all pkg and the content
398         localpkgs = self.localpkgs.keys()
399         for pkg in dlpkgs:
400             license = ''
401             if pkg.name() in localpkgs:
402                 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
403                 pkg_long_name = misc.RPM_FMT % {
404                                     'name': hdr['name'],
405                                     'arch': hdr['arch'],
406                                     'ver_rel': '%s-%s' % (hdr['version'],
407                                                           hdr['release']),
408                                 }
409                 license = hdr['license']
410
411             else:
412                 pkg_long_name = misc.RPM_FMT % {
413                                     'name': pkg.name(),
414                                     'arch': pkg.arch(),
415                                     'ver_rel': pkg.edition(),
416                                 }
417
418                 package = zypp.asKindPackage(pkg)
419                 license = package.license()
420
421             self.__pkgs_content[pkg_long_name] = {} #TBD: to get file list
422
423             if license in self.__pkgs_license.keys():
424                 self.__pkgs_license[license].append(pkg_long_name)
425             else:
426                 self.__pkgs_license[license] = [pkg_long_name]
427
428         total_count = len(dlpkgs)
429         cached_count = 0
430         download_total_size = sum(map(lambda x: int(x.downloadSize()), dlpkgs))
431         localpkgs = self.localpkgs.keys()
432
433         msger.info("Checking packages cache and packages integrity ...")
434         for po in dlpkgs:
435             # Check if it is cached locally
436             if po.name() in localpkgs:
437                 cached_count += 1
438             else:
439                 local = self.getLocalPkgPath(po)
440                 if os.path.exists(local):
441                     if self.checkPkg(local) != 0:
442                         os.unlink(local)
443                     else:
444                         download_total_size -= int(po.downloadSize())
445                         cached_count += 1
446         cache_avail_size = misc.get_filesystem_avail(self.cachedir)
447         if cache_avail_size < download_total_size:
448             raise CreatorError("No enough space used for downloading.")
449
450         # record the total size of installed pkgs
451         install_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
452         # check needed size before actually download and install
453
454         # FIXME: for multiple partitions for loop type, check fails
455         #        skip the check temporarily
456         #if checksize and install_total_size > checksize:
457         #    raise CreatorError("No enough space used for installing, "
458         #                       "please resize partition size in ks file")
459
460         download_count =  total_count - cached_count
461         msger.info("%d packages to be installed, "
462                    "%d packages gotten from cache, "
463                    "%d packages to be downloaded" \
464                    % (total_count, cached_count, download_count))
465
466         try:
467             if download_count > 0:
468                 msger.info("Downloading packages ...")
469             self.downloadPkgs(dlpkgs, download_count)
470
471             self.installPkgs(dlpkgs)
472
473         except (RepoError, RpmError):
474             raise
475         except Exception, e:
476             raise CreatorError("Package installation failed: %s" % (e,))
477
478     def getAllContent(self):
479         return self.__pkgs_content
480
481     def getPkgsLicense(self):
482         return self.__pkgs_license
483
484     def getFilelist(self, pkgname):
485         if not pkgname:
486             return None
487
488         if not self.ts:
489             self.__initialize_transaction()
490
491         mi = self.ts.dbMatch('name', pkgname)
492         for header in mi:
493             return header['FILENAMES']
494
495     def __initialize_repo_manager(self):
496         if self.repo_manager:
497             return
498
499         # Clean up repo metadata
500         shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
501         shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
502         shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
503
504         zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
505                                      | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
506                                      | zypp.KeyRing.ACCEPT_UNKNOWNKEY
507                                      | zypp.KeyRing.TRUST_KEY_TEMPORARILY
508                                      )
509
510         self.repo_manager_options = \
511                 zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
512
513         self.repo_manager_options.knownReposPath = \
514                 zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
515
516         self.repo_manager_options.repoCachePath = \
517                 zypp.Pathname(self.cachedir)
518
519         self.repo_manager_options.repoRawCachePath = \
520                 zypp.Pathname(self.cachedir + "/raw")
521
522         self.repo_manager_options.repoSolvCachePath = \
523                 zypp.Pathname(self.cachedir + "/solv")
524
525         self.repo_manager_options.repoPackagesCachePath = \
526                 zypp.Pathname(self.cachedir + "/packages")
527
528         self.repo_manager = zypp.RepoManager(self.repo_manager_options)
529
530     def __build_repo_cache(self, name):
531         repo = self.repo_manager.getRepositoryInfo(name)
532         if self.repo_manager.isCached(repo) or not repo.enabled():
533             return
534
535         msger.info('Refreshing repository: %s ...' % name)
536         self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
537
538     def __initialize_zypp(self):
539         if self.Z:
540             return
541
542         zconfig = zypp.ZConfig_instance()
543
544         # Set system architecture
545         if self.target_arch:
546             zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
547
548         msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
549
550         # repoPackagesCachePath is corrected by this
551         self.repo_manager = zypp.RepoManager(self.repo_manager_options)
552         repos = self.repo_manager.knownRepositories()
553         for repo in repos:
554             if not repo.enabled():
555                 continue
556             self.repo_manager.loadFromCache(repo)
557
558         self.Z = zypp.ZYppFactory_instance().getZYpp()
559         self.Z.initializeTarget(zypp.Pathname(self.instroot))
560         self.Z.target().load()
561
562     def buildTransaction(self):
563         if not self.Z.resolver().resolvePool():
564             probs = self.Z.resolver().problems()
565
566             for problem in probs:
567                 msger.warning("repo problem: %s, %s" \
568                               % (problem.description().decode("utf-8"),
569                                  problem.details().decode("utf-8")))
570
571             raise RepoError("found %d resolver problem, abort!" \
572                             % len(probs))
573
574     def getLocalPkgPath(self, po):
575         repoinfo = po.repoInfo()
576         cacheroot = repoinfo.packagesPath()
577         location= zypp.asKindPackage(po).location()
578         rpmpath = str(location.filename())
579         pkgpath = "%s/%s" % (cacheroot, os.path.basename(rpmpath))
580         return pkgpath
581
582     def installLocal(self, pkg, po=None, updateonly=False):
583         if not self.ts:
584             self.__initialize_transaction()
585
586         solvfile = "%s/.solv" % (self.cachedir)
587
588         rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"),
589                                   pkg])
590         if rc == 0:
591             f = open(solvfile, "w+")
592             f.write(out)
593             f.close()
594
595             warnmsg = self.repo_manager.loadSolvFile(solvfile,
596                                                      os.path.basename(pkg))
597             if warnmsg:
598                 msger.warning(warnmsg)
599
600             os.unlink(solvfile)
601         else:
602             msger.warning('Can not get %s solv data.' % pkg)
603
604         hdr = rpmmisc.readRpmHeader(self.ts, pkg)
605         arch = zypp.Arch(hdr['arch'])
606         sysarch = zypp.Arch(self.target_arch)
607
608         if arch.compatible_with (sysarch):
609             pkgname = hdr['name']
610             self.localpkgs[pkgname] = pkg
611             self.selectPackage(pkgname)
612             msger.info("Marking %s to be installed" % (pkg))
613
614         else:
615             msger.warning("Cannot add package %s to transaction. "
616                           "Not a compatible architecture: %s" \
617                           % (pkg, hdr['arch']))
618
619     def downloadPkgs(self, package_objects, count):
620         localpkgs = self.localpkgs.keys()
621         progress_obj = rpmmisc.TextProgress(count)
622
623         for po in package_objects:
624             if po.name() in localpkgs:
625                 continue
626
627             filename = self.getLocalPkgPath(po)
628             if os.path.exists(filename):
629                 if self.checkPkg(filename) == 0:
630                     continue
631
632             dirn = os.path.dirname(filename)
633             if not os.path.exists(dirn):
634                 os.makedirs(dirn)
635
636             name = str(po.repoInfo().name())
637             repo = filter(lambda r: r.name == name, self.repos)[0]
638             baseurl = repo.baseurl[0]
639             index = baseurl.find("?")
640             if index > -1:
641                 baseurl = baseurl[:index]
642
643             proxy = self.get_proxy(po.repoInfo())
644             proxies = {}
645             if proxy:
646                 proxies = {str(proxy.split(":")[0]):str(proxy)}
647
648             location = zypp.asKindPackage(po).location()
649             location = str(location.filename())
650             if location.startswith("./"):
651                 location = location[2:]
652
653             url = baseurl + "/%s" % location
654
655             try:
656                 filename = rpmmisc.myurlgrab(url,
657                                              filename,
658                                              proxies,
659                                              progress_obj)
660             except CreatorError:
661                 self.close()
662                 raise
663
664     def preinstallPkgs(self):
665         if not self.ts_pre:
666             self.__initialize_transaction()
667
668         self.ts_pre.order()
669         cb = rpmmisc.RPMInstallCallback(self.ts_pre)
670         cb.headmsg = "Preinstall"
671         installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
672
673         # start to catch stderr output from librpm
674         msger.enable_logstderr(installlogfile)
675
676         errors = self.ts_pre.run(cb.callback, '')
677         # stop catch
678         msger.disable_logstderr()
679         self.ts_pre.closeDB()
680         self.ts_pre = None
681
682         if errors is not None:
683             if len(errors) == 0:
684                 msger.warning('scriptlet or other non-fatal errors occurred '
685                               'during transaction.')
686
687             else:
688                 for e in errors:
689                     msger.warning(e[0])
690                 raise RepoError('Could not run transaction.')
691
692     def installPkgs(self, package_objects):
693         if not self.ts:
694             self.__initialize_transaction()
695
696         # Set filters
697         probfilter = 0
698         for flag in self.probFilterFlags:
699             probfilter |= flag
700         self.ts.setProbFilter(probfilter)
701         self.ts_pre.setProbFilter(probfilter)
702
703         localpkgs = self.localpkgs.keys()
704
705         for po in package_objects:
706             pkgname = po.name()
707             if pkgname in localpkgs:
708                 rpmpath = self.localpkgs[pkgname]
709             else:
710                 rpmpath = self.getLocalPkgPath(po)
711
712             if not os.path.exists(rpmpath):
713                 # Maybe it is a local repo
714                 baseurl = str(po.repoInfo().baseUrls()[0])
715                 baseurl = baseurl.strip()
716
717                 location = zypp.asKindPackage(po).location()
718                 location = str(location.filename())
719
720                 if baseurl.startswith("file:/"):
721                     rpmpath = baseurl[5:] + "/%s" % (location)
722
723             if not os.path.exists(rpmpath):
724                 raise RpmError("Error: %s doesn't exist" % rpmpath)
725
726             h = rpmmisc.readRpmHeader(self.ts, rpmpath)
727
728             if pkgname in self.pre_pkgs:
729                 msger.verbose("pre-install package added: %s" % pkgname)
730                 self.ts_pre.addInstall(h, rpmpath, 'u')
731
732             self.ts.addInstall(h, rpmpath, 'u')
733
734         unresolved_dependencies = self.ts.check()
735         if not unresolved_dependencies:
736             if self.pre_pkgs:
737                 self.preinstallPkgs()
738
739             self.ts.order()
740             cb = rpmmisc.RPMInstallCallback(self.ts)
741             installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
742
743             # start to catch stderr output from librpm
744             msger.enable_logstderr(installlogfile)
745
746             errors = self.ts.run(cb.callback, '')
747             # stop catch
748             msger.disable_logstderr()
749             self.ts.closeDB()
750             self.ts = None
751
752             if errors is not None:
753                 if len(errors) == 0:
754                     msger.warning('scriptlet or other non-fatal errors occurred '
755                                   'during transaction.')
756
757                 else:
758                     for e in errors:
759                         msger.warning(e[0])
760                     raise RepoError('Could not run transaction.')
761
762         else:
763             for pkg, need, needflags, sense, key in unresolved_dependencies:
764                 package = '-'.join(pkg)
765
766                 if needflags == rpm.RPMSENSE_LESS:
767                     deppkg = ' < '.join(need)
768                 elif needflags == rpm.RPMSENSE_EQUAL:
769                     deppkg = ' = '.join(need)
770                 elif needflags == rpm.RPMSENSE_GREATER:
771                     deppkg = ' > '.join(need)
772                 else:
773                     deppkg = '-'.join(need)
774
775                 if sense == rpm.RPMDEP_SENSE_REQUIRES:
776                     msger.warning("[%s] Requires [%s], which is not provided" \
777                                   % (package, deppkg))
778
779                 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
780                     msger.warning("[%s] Conflicts with [%s]" %(package,deppkg))
781
782             raise RepoError("Unresolved dependencies, transaction failed.")
783
784     def __initialize_transaction(self):
785         if not self.ts:
786             self.ts = rpm.TransactionSet(self.instroot)
787             # Set to not verify DSA signatures.
788             self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
789
790         if not self.ts_pre:
791             self.ts_pre = rpm.TransactionSet(self.instroot)
792             # Just unpack the files, don't run scripts
793             self.ts_pre.setFlags(rpm.RPMTRANS_FLAG_ALLFILES | rpm.RPMTRANS_FLAG_NOSCRIPTS)
794             # Set to not verify DSA signatures.
795             self.ts_pre.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
796
797     def checkPkg(self, pkg):
798         ret = 1
799         if not os.path.exists(pkg):
800             return ret
801         ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
802         if ret != 0:
803             msger.warning("package %s is damaged: %s" \
804                           % (os.path.basename(pkg), pkg))
805
806         return ret
807
808     def _add_prob_flags(self, *flags):
809         for flag in flags:
810            if flag not in self.probFilterFlags:
811                self.probFilterFlags.append(flag)
812
813     def get_proxy(self, repoinfo):
814         proxy = None
815         reponame = "%s" % repoinfo.name()
816         for repo in self.repos:
817             if repo.name == reponame:
818                 proxy = repo.proxy
819                 break
820
821         if proxy:
822             return proxy
823         else:
824             repourl = str(repoinfo.baseUrls()[0])
825             return get_proxy_for(repourl)
826
827     def package_url(self, pkg):
828
829         def cmpEVR(ed1, ed2):
830             (e1, v1, r1) = map(str, [ed1.epoch(), ed1.version(), ed1.release()])
831             (e2, v2, r2) = map(str, [ed2.epoch(), ed2.version(), ed2.release()])
832             return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))
833
834         if not self.Z:
835             self.__initialize_zypp()
836
837         q = zypp.PoolQuery()
838         q.addKind(zypp.ResKind.package)
839         q.setMatchExact()
840         q.addAttribute(zypp.SolvAttr.name,pkg)
841         items = sorted(q.queryResults(self.Z.pool()),
842                        cmp=lambda x,y: cmpEVR(x.edition(), y.edition()),
843                        reverse=True)
844
845         if items:
846             baseurl = items[0].repoInfo().baseUrls()[0]
847             location = zypp.asKindPackage(items[0]).location()
848             return os.path.join(str(baseurl), str(location.filename()))
849
850         return None