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