new feature: runtime support and bootstrap runtime
[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 from mic.utils import runner, fs_related
23
24 import zypp
25 if not hasattr(zypp, 'PoolQuery') or not hasattr(zypp.RepoManager, 'loadSolvFile'):
26     raise ImportError("python-zypp in host system cannot support PoolQuery or loadSolvFile interface, "
27                       "please update it to enhanced version which can be found in repo.meego.com/tools")
28
29 from mic import msger
30 from mic.kickstart import ksparser
31 from mic.utils import rpmmisc
32 from mic.utils.proxy import get_proxy_for
33 from mic.utils.errors import CreatorError
34 from mic.imager.baseimager import BaseImageCreator
35
36 class RepositoryStub:
37     def __init__(self):
38         self.name = None
39         self.baseurl = []
40         self.mirrorlist = None
41         self.proxy = None
42         self.proxy_username = None
43         self.proxy_password = None
44
45         self.enabled = True
46         self.autorefresh = True
47         self.keeppackages = True
48         self.priority = None
49
50 class RepoError(CreatorError):
51     pass
52
53 class RpmError(CreatorError):
54     pass
55
56 from mic.pluginbase import BackendPlugin
57 class Zypp(BackendPlugin):
58     name = 'zypp'
59
60     def __init__(self, target_arch, instroot, cachedir):
61         self.cachedir = cachedir
62         self.instroot  = instroot
63         self.target_arch = target_arch
64
65         self.__pkgs_license = {}
66         self.__pkgs_content = {}
67         self.repos = []
68         self.to_deselect = []
69         self.localpkgs = {}
70         self.repo_manager = None
71         self.repo_manager_options = None
72         self.Z = None
73         self.ts = None
74         self.probFilterFlags = []
75         self.incpkgs = {}
76         self.excpkgs = {}
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         self.closeRpmDB()
90         if not os.path.exists("/etc/fedora-release") and not os.path.exists("/etc/meego-release"):
91             for i in range(3, os.sysconf("SC_OPEN_MAX")):
92                 try:
93                     os.close(i)
94                 except:
95                     pass
96         if self.ts:
97             self.ts.closeDB()
98             self.ts = None
99
100     def __del__(self):
101         self.close()
102
103     def _cleanupRpmdbLocks(self, installroot):
104         # cleans up temporary files left by bdb so that differing
105         # versions of rpm don't cause problems
106         import glob
107         for f in glob.glob(installroot + "/var/lib/rpm/__db*"):
108             os.unlink(f)
109
110     def setup(self, confpath=None, instroot=None):
111         if not self.instroot:
112             self.instroot = instroot
113         self._cleanupRpmdbLocks(self.instroot)
114
115     def whatObsolete(self, pkg):
116         query = zypp.PoolQuery()
117         query.addKind(zypp.ResKind.package)
118         query.addAttribute(zypp.SolvAttr.obsoletes, pkg)
119         query.setMatchExact()
120         for pi in query.queryResults(self.Z.pool()):
121             return pi
122         return None
123
124     def _splitPkgString(self, pkg):
125         sp = pkg.rsplit(".",1)
126         name = sp[0]
127         arch = None
128         if len(sp) == 2:
129             arch = sp[1]
130             sysarch = zypp.Arch(self.target_arch)
131             if not zypp.Arch(arch).compatible_with (sysarch):
132                 arch = None
133                 name = ".".join(sp)
134         return name, arch
135
136     def selectPackage(self, pkg):
137         """ Select a given package or package pattern, can be specified with name.arch or name* or *name """
138         if not self.Z:
139             self.__initialize_zypp()
140
141         def markPoolItem(obs, pi):
142             if obs == None:
143                 pi.status().setToBeInstalled (zypp.ResStatus.USER)
144             else:
145                 obs.status().setToBeInstalled (zypp.ResStatus.USER)
146
147         found = False
148         startx = pkg.startswith("*")
149         endx = pkg.endswith("*")
150         ispattern = startx or endx
151         name, arch = self._splitPkgString(pkg)
152
153         q = zypp.PoolQuery()
154         q.addKind(zypp.ResKind.package)
155         if ispattern:
156             if startx and not endx:
157                 pattern = '%s$' % (pkg[1:])
158             if endx and not startx:
159                 pattern = '^%s' % (pkg[0:-1])
160             if endx and startx:
161                 pattern = '%s' % (pkg[1:-1])
162             q.setMatchRegex()
163             q.addAttribute(zypp.SolvAttr.name,pattern)
164         elif arch:
165             q.setMatchExact()
166             q.addAttribute(zypp.SolvAttr.name,name)
167         else:
168             q.setMatchExact()
169             q.addAttribute(zypp.SolvAttr.name,pkg)
170
171         for item in sorted(q.queryResults(self.Z.pool()), key=lambda item: str(item.edition()), reverse=True):
172             if item.name() in self.excpkgs.keys() and self.excpkgs[item.name()] == item.repoInfo().name():
173                 continue
174             if item.name() in self.incpkgs.keys() and self.incpkgs[item.name()] != item.repoInfo().name():
175                 continue
176             found = True
177             obspkg = self.whatObsolete(item.name())
178             if arch:
179                 if arch == str(item.arch()):
180                     item.status().setToBeInstalled (zypp.ResStatus.USER)
181             else:
182                 markPoolItem(obspkg, item)
183             if not ispattern:
184                 break
185         # Can't match using package name, then search from packge provides infomation
186         if found == False and not ispattern:
187             q.addAttribute(zypp.SolvAttr.provides, pkg)
188             q.addAttribute(zypp.SolvAttr.name,'')
189             for item in sorted(q.queryResults(self.Z.pool()), key=lambda item: str(item.edition()), reverse=True):
190                 if item.name() in self.excpkgs.keys() and self.excpkgs[item.name()] == item.repoInfo().name():
191                     continue
192                 if item.name() in self.incpkgs.keys() and self.incpkgs[item.name()] != item.repoInfo().name():
193                     continue
194                 found = True
195                 obspkg = self.whatObsolete(item.name())
196                 markPoolItem(obspkg, item)
197                 break
198         if found:
199             return None
200         else:
201             raise CreatorError("Unable to find package: %s" % (pkg,))
202
203     def inDeselectPackages(self, item):
204         """check if specified pacakges are in the list of inDeselectPackages"""
205         name = item.name()
206         for pkg in self.to_deselect:
207             startx = pkg.startswith("*")
208             endx = pkg.endswith("*")
209             ispattern = startx or endx
210             pkgname, pkgarch = self._splitPkgString(pkg)
211             if not ispattern:
212                 if pkgarch:
213                     if name == pkgname and str(item.arch()) == pkgarch:
214                         return True;
215                 else:
216                     if name == pkgname:
217                         return True;
218             else:
219                 if startx and name.endswith(pkg[1:]):
220                         return True;
221                 if endx and name.startswith(pkg[:-1]):
222                         return True;
223         return False;
224
225     def deselectPackage(self, pkg):
226         """collect packages should not be installed"""
227         self.to_deselect.append(pkg)
228
229     def selectGroup(self, grp, include = ksparser.GROUP_DEFAULT):
230         if not self.Z:
231             self.__initialize_zypp()
232         found = False
233         q=zypp.PoolQuery()
234         q.addKind(zypp.ResKind.pattern)
235         for item in q.queryResults(self.Z.pool()):
236             summary = "%s" % item.summary()
237             name = "%s" % item.name()
238             if name == grp or summary == grp:
239                 found = True
240                 item.status().setToBeInstalled (zypp.ResStatus.USER)
241                 break
242
243         if found:
244             if include == ksparser.GROUP_REQUIRED:
245                 map(lambda p: self.deselectPackage(p), grp.default_packages.keys())
246             return None
247         else:
248             raise CreatorError("Unable to find pattern: %s" % (grp,))
249
250     def addRepository(self, name, url = None, mirrorlist = None, proxy = None,
251                       proxy_username = None, proxy_password = None,
252                       inc = None, exc = None, ssl_verify = True, cost=None,
253                       priority=None):
254         # TODO: Handle cost attribute for repos
255         if not self.repo_manager:
256             self.__initialize_repo_manager()
257
258         repo = RepositoryStub()
259         repo.name = name
260         repo.id = name
261         repo.proxy = proxy
262         repo.proxy_username = proxy_username
263         repo.proxy_password = proxy_password
264         repo.ssl_verify = ssl_verify
265         repo.baseurl.append(url)
266         if inc:
267             for pkg in inc:
268                 self.incpkgs[pkg] = name
269         if exc:
270             for pkg in exc:
271                 self.excpkgs[pkg] = name
272
273         # check LICENSE files
274         if not rpmmisc.checkRepositoryEULA(name, repo):
275             msger.warning('skip repo:%s for failed EULA confirmation' % name)
276             return None
277
278         if mirrorlist:
279             repo.mirrorlist = mirrorlist
280
281         # Enable gpg check for verifying corrupt packages
282         repo.gpgcheck = 1
283         if priority:
284             repo.priority = priority
285         self.repos.append(repo)
286
287         try:
288             repo_info = zypp.RepoInfo()
289             repo_info.setAlias(repo.name)
290             repo_info.setName(repo.name)
291             repo_info.setEnabled(repo.enabled)
292             repo_info.setAutorefresh(repo.autorefresh)
293             repo_info.setKeepPackages(repo.keeppackages)
294             baseurl = zypp.Url(repo.baseurl[0])
295             if not ssl_verify:
296                 baseurl.setQueryParam("ssl_verify", "no")
297             if proxy:
298                 (scheme, host, path, parm, query, frag) = urlparse.urlparse(proxy)
299                 proxyinfo = host.split(":")
300                 host = proxyinfo[0]
301                 port = "80"
302                 if len(proxyinfo) > 1:
303                     port = proxyinfo[1]
304                 if proxy.startswith("socks") and len(proxy.rsplit(':', 1)) == 2:
305                     host = proxy.rsplit(':', 1)[0]
306                     port = proxy.rsplit(':', 1)[1]
307                 baseurl.setQueryParam ("proxy", host)
308                 baseurl.setQueryParam ("proxyport", port)
309             repo_info.addBaseUrl(baseurl)
310             if repo.priority:
311                 repo_info.setPriority(repo.priority)
312             self.repo_manager.addRepository(repo_info)
313             self.__build_repo_cache(name)
314         except RuntimeError, e:
315             raise CreatorError(str(e))
316
317         msger.verbose('repo: %s was added' % name)
318         return repo
319
320     def installHasFile(self, file):
321         return False
322
323     def runInstall(self, checksize = 0):
324         os.environ["HOME"] = "/"
325         self.buildTransaction()
326
327         todo = zypp.GetResolvablesToInsDel(self.Z.pool())
328         installed_pkgs = todo._toInstall
329         dlpkgs = []
330         for item in installed_pkgs:
331             if not zypp.isKindPattern(item) and not self.inDeselectPackages(item):
332                 dlpkgs.append(item)
333
334         # record the total size of installed pkgs
335         pkgs_total_size = sum(map(lambda x: int(x.installSize()), dlpkgs))
336
337         # check needed size before actually download and install
338         if checksize and pkgs_total_size > checksize:
339             raise CreatorError("Size of specified root partition in kickstart file is too small to install all selected packages.")
340
341         # record all pkg and the content
342         localpkgs = self.localpkgs.keys()
343         for pkg in dlpkgs:
344             license = ''
345             if pkg.name() in localpkgs:
346                 hdr = rpmmisc.readRpmHeader(self.ts, self.localpkgs[pkg.name()])
347                 pkg_long_name = "%s-%s-%s.%s.rpm" % (hdr['name'], hdr['version'], hdr['release'], hdr['arch'])
348                 license = hdr['license']
349             else:
350                 pkg_long_name = "%s-%s.%s.rpm" % (pkg.name(), pkg.edition(), pkg.arch())
351                 package = zypp.asKindPackage(pkg)
352                 license = package.license()
353             self.__pkgs_content[pkg_long_name] = {} #TBD: to get file list
354             if license in self.__pkgs_license.keys():
355                 self.__pkgs_license[license].append(pkg_long_name)
356             else:
357                 self.__pkgs_license[license] = [pkg_long_name]
358
359         total_count = len(dlpkgs)
360         cached_count = 0
361         localpkgs = self.localpkgs.keys()
362         msger.info("Checking packages cache and packages integrity ...")
363         for po in dlpkgs:
364             """ Check if it is cached locally """
365             if po.name() in localpkgs:
366                 cached_count += 1
367             else:
368                 local = self.getLocalPkgPath(po)
369                 if os.path.exists(local):
370                     if self.checkPkg(local) != 0:
371                         os.unlink(local)
372                     else:
373                         cached_count += 1
374         download_count =  total_count - cached_count
375         msger.info("%d packages to be installed, %d packages gotten from cache, %d packages to be downloaded" % (total_count, cached_count, download_count))
376         try:
377             if download_count > 0:
378                 msger.info("Downloading packages ...")
379             self.downloadPkgs(dlpkgs, download_count)
380             self.installPkgs(dlpkgs)
381
382         except RepoError, e:
383             raise CreatorError("Unable to download from repo : %s" % (e,))
384         except RpmError, e:
385             raise CreatorError("Unable to install: %s" % (e,))
386
387     def getAllContent(self):
388         return self.__pkgs_content
389
390     def getPkgsLicense(self):
391         return self.__pkgs_license
392
393     def __initialize_repo_manager(self):
394         if self.repo_manager:
395             return
396
397         """ Clean up repo metadata """
398         shutil.rmtree(self.cachedir + "/etc", ignore_errors = True)
399         shutil.rmtree(self.cachedir + "/solv", ignore_errors = True)
400         shutil.rmtree(self.cachedir + "/raw", ignore_errors = True)
401
402         zypp.KeyRing.setDefaultAccept( zypp.KeyRing.ACCEPT_UNSIGNED_FILE
403                                      | zypp.KeyRing.ACCEPT_VERIFICATION_FAILED
404                                      | zypp.KeyRing.ACCEPT_UNKNOWNKEY
405                                      | zypp.KeyRing.TRUST_KEY_TEMPORARILY
406                                      )
407         self.repo_manager_options = zypp.RepoManagerOptions(zypp.Pathname(self.instroot))
408         self.repo_manager_options.knownReposPath = zypp.Pathname(self.cachedir + "/etc/zypp/repos.d")
409         self.repo_manager_options.repoCachePath = zypp.Pathname(self.cachedir)
410         self.repo_manager_options.repoRawCachePath = zypp.Pathname(self.cachedir + "/raw")
411         self.repo_manager_options.repoSolvCachePath = zypp.Pathname(self.cachedir + "/solv")
412         self.repo_manager_options.repoPackagesCachePath = zypp.Pathname(self.cachedir + "/packages")
413
414         self.repo_manager = zypp.RepoManager(self.repo_manager_options)
415
416     def __build_repo_cache(self, name):
417         repo = self.repo_manager.getRepositoryInfo(name)
418         if self.repo_manager.isCached(repo) or not repo.enabled():
419             return
420         self.repo_manager.buildCache(repo, zypp.RepoManager.BuildIfNeeded)
421
422     def __initialize_zypp(self):
423         if self.Z:
424             return
425
426         zconfig = zypp.ZConfig_instance()
427
428         """ Set system architecture """
429         if self.target_arch:
430             zconfig.setSystemArchitecture(zypp.Arch(self.target_arch))
431
432         msger.info("zypp architecture is <%s>" % zconfig.systemArchitecture())
433
434         """ repoPackagesCachePath is corrected by this """
435         self.repo_manager = zypp.RepoManager(self.repo_manager_options)
436         repos = self.repo_manager.knownRepositories()
437         for repo in repos:
438             if not repo.enabled():
439                 continue
440             self.repo_manager.loadFromCache(repo)
441
442         self.Z = zypp.ZYppFactory_instance().getZYpp()
443         self.Z.initializeTarget(zypp.Pathname(self.instroot))
444         self.Z.target().load()
445
446
447     def buildTransaction(self):
448         if not self.Z.resolver().resolvePool():
449             msger.warning("Problem count: %d" % len(self.Z.resolver().problems()))
450             for problem in self.Z.resolver().problems():
451                 msger.warning("Problem: %s, %s" % (problem.description().decode("utf-8"), problem.details().decode("utf-8")))
452
453     def getLocalPkgPath(self, po):
454         repoinfo = po.repoInfo()
455         cacheroot = repoinfo.packagesPath()
456         location= zypp.asKindPackage(po).location()
457         rpmpath = str(location.filename())
458         pkgpath = "%s/%s" % (cacheroot, rpmpath)
459         return pkgpath
460
461     def installLocal(self, pkg, po=None, updateonly=False):
462         if not self.ts:
463             self.__initialize_transaction()
464         solvfile = "%s/.solv" % (self.cachedir)
465         rc, out = runner.runtool([fs_related.find_binary_path("rpms2solv"), pkg])
466         if rc == 0:
467             f = open(solvfile, "w+")
468             f.write(out)
469             f.close()
470             warnmsg = self.repo_manager.loadSolvFile(solvfile , os.path.basename(pkg))
471             if warnmsg:
472                 msger.warning(warnmsg)
473             os.unlink(solvfile)
474         else:
475             msger.warning('Can not get %s solv data.' % pkg)
476         hdr = rpmmisc.readRpmHeader(self.ts, pkg)
477         arch = zypp.Arch(hdr['arch'])
478         sysarch = zypp.Arch(self.target_arch)
479         if arch.compatible_with (sysarch):
480             pkgname = hdr['name']
481             self.localpkgs[pkgname] = pkg
482             self.selectPackage(pkgname)
483             msger.info("Marking %s to be installed" % (pkg))
484         else:
485             msger.warning ("Cannot add package %s to transaction. Not a compatible architecture: %s" % (pkg, hdr['arch']))
486
487     def downloadPkgs(self, package_objects, count):
488         localpkgs = self.localpkgs.keys()
489         progress_obj = rpmmisc.TextProgress(count)
490         for po in package_objects:
491             if po.name() in localpkgs:
492                 continue
493             filename = self.getLocalPkgPath(po)
494             if os.path.exists(filename):
495                 if self.checkPkg(filename) == 0:
496                     continue
497             dirn = os.path.dirname(filename)
498             if not os.path.exists(dirn):
499                 os.makedirs(dirn)
500             baseurl = str(po.repoInfo().baseUrls()[0])
501             index = baseurl.find("?")
502             if index > -1:
503                 baseurl = baseurl[:index]
504             proxy = self.get_proxy(po.repoInfo())
505             proxies = {}
506             if proxy:
507                 proxies = {str(proxy.split(":")[0]):str(proxy)}
508
509             location = zypp.asKindPackage(po).location()
510             location = str(location.filename())
511             if location.startswith("./"):
512                 location = location[2:]
513             url = baseurl + "/%s" % location
514             try:
515                 filename = rpmmisc.myurlgrab(url, filename, proxies, progress_obj)
516             except CreatorError:
517                 self.close()
518                 raise
519
520     def installPkgs(self, package_objects):
521         if not self.ts:
522             self.__initialize_transaction()
523
524         """ Set filters """
525         probfilter = 0
526         for flag in self.probFilterFlags:
527             probfilter |= flag
528         self.ts.setProbFilter(probfilter)
529
530         localpkgs = self.localpkgs.keys()
531         for po in package_objects:
532             pkgname = po.name()
533             if pkgname in localpkgs:
534                 rpmpath = self.localpkgs[pkgname]
535             else:
536                 rpmpath = self.getLocalPkgPath(po)
537             if not os.path.exists(rpmpath):
538                 """ Maybe it is a local repo """
539                 baseurl = str(po.repoInfo().baseUrls()[0])
540                 baseurl = baseurl.strip()
541                 location = zypp.asKindPackage(po).location()
542                 location = str(location.filename())
543                 if baseurl.startswith("file:/"):
544                     rpmpath = baseurl[5:] + "/%s" % (location)
545             if not os.path.exists(rpmpath):
546                 raise RpmError("Error: %s doesn't exist" % rpmpath)
547             h = rpmmisc.readRpmHeader(self.ts, rpmpath)
548             self.ts.addInstall(h, rpmpath, 'u')
549
550         unresolved_dependencies = self.ts.check()
551         if not unresolved_dependencies:
552             self.ts.order()
553             cb = rpmmisc.RPMInstallCallback(self.ts)
554             installlogfile = "%s/__catched_stderr.buf" % (self.instroot)
555             msger.enable_logstderr(installlogfile)
556             errors = self.ts.run(cb.callback, '')
557             if errors is None:
558                 pass
559             elif len(errors) == 0:
560                 msger.warning('scriptlet or other non-fatal errors occurred during transaction.')
561             else:
562                 for e in errors:
563                     msger.warning(e[0])
564                 msger.error('Could not run transaction.')
565             msger.disable_logstderr()
566
567             self.ts.closeDB()
568             self.ts = None
569         else:
570             for pkg, need, needflags, sense, key in unresolved_dependencies:
571                 package = '-'.join(pkg)
572                 if needflags == rpm.RPMSENSE_LESS:
573                     deppkg = ' < '.join(need)
574                 elif needflags == rpm.RPMSENSE_EQUAL:
575                     deppkg = ' = '.join(need)
576                 elif needflags == rpm.RPMSENSE_GREATER:
577                     deppkg = ' > '.join(need)
578                 else:
579                     deppkg = '-'.join(need)
580
581                 if sense == rpm.RPMDEP_SENSE_REQUIRES:
582                     msger.warning ("[%s] Requires [%s], which is not provided" % (package, deppkg))
583                 elif sense == rpm.RPMDEP_SENSE_CONFLICTS:
584                     msger.warning ("[%s] Conflicts with [%s]" % (package, deppkg))
585
586             raise RepoError("Unresolved dependencies, transaction failed.")
587
588     def __initialize_transaction(self):
589         if not self.ts:
590             self.ts = rpm.TransactionSet(self.instroot)
591             # Set to not verify DSA signatures.
592             self.ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES|rpm._RPMVSF_NODIGESTS)
593
594     def checkPkg(self, pkg):
595         ret = 1
596         if not os.path.exists(pkg):
597             return ret
598         ret = rpmmisc.checkRpmIntegrity('rpm', pkg)
599         if ret != 0:
600             msger.warning("package %s is damaged: %s" % (os.path.basename(pkg), pkg))
601
602         return ret
603
604     def _add_prob_flags(self, *flags):
605         for flag in flags:
606            if flag not in self.probFilterFlags:
607                self.probFilterFlags.append(flag)
608
609     def get_proxy(self, repoinfo):
610         proxy = None
611         reponame = "%s" % repoinfo.name()
612         for repo in self.repos:
613             if repo.name == reponame:
614                 proxy = repo.proxy
615                 break
616
617         if proxy:
618             return proxy
619         else:
620             repourl = str(repoinfo.baseUrls()[0])
621             return get_proxy_for(repourl)