f2e558500c97012ba3d703e89ef0410493986694
[tools/mic.git] / mic / utils / rpmmisc.py
1 #!/usr/bin/python -tt
2 #
3 # Copyright (c) 2008, 2009, 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 sys
20 import re
21 import rpm
22
23 from mic import msger
24 from mic.utils.errors import CreatorError
25 from mic.utils.proxy import get_proxy_for
26 from mic.utils import runner
27
28
29 class RPMInstallCallback:
30     """ Command line callback class for callbacks from the RPM library.
31     """
32
33     def __init__(self, ts, output=1):
34         self.output = output
35         self.callbackfilehandles = {}
36         self.total_actions = 0
37         self.total_installed = 0
38         self.total_installing = 0
39         self.installed_pkg_names = []
40         self.total_removed = 0
41         self.mark = "+"
42         self.marks = 40
43         self.lastmsg = None
44         self.tsInfo = None # this needs to be set for anything else to work
45         self.ts = ts
46         self.filelog = False
47         self.logString = []
48         self.headmsg = "Installing"
49
50     def _dopkgtup(self, hdr):
51         tmpepoch = hdr['epoch']
52         if tmpepoch is None: epoch = '0'
53         else: epoch = str(tmpepoch)
54
55         return (hdr['name'], hdr['arch'], epoch, hdr['version'], hdr['release'])
56
57     def _makeHandle(self, hdr):
58         handle = '%s:%s.%s-%s-%s' % (hdr['epoch'], hdr['name'], hdr['version'],
59           hdr['release'], hdr['arch'])
60
61         return handle
62
63     def _localprint(self, msg):
64         if self.output:
65             msger.info(msg)
66
67     def _makefmt(self, percent, progress = True):
68         l = len(str(self.total_actions))
69         size = "%s.%s" % (l, l)
70         fmt_done = "[%" + size + "s/%" + size + "s]"
71         done = fmt_done % (self.total_installing,
72                            self.total_actions)
73         marks = self.marks - (2 * l)
74         width = "%s.%s" % (marks, marks)
75         fmt_bar = "%-" + width + "s"
76         if progress:
77             bar = fmt_bar % (self.mark * int(marks * (percent / 100.0)), )
78             fmt = "%-10.10s: %-50.50s " + bar + " " + done
79         else:
80             bar = fmt_bar % (self.mark * marks, )
81             fmt = "%-10.10s: %-50.50s "  + bar + " " + done
82         return fmt
83
84     def _logPkgString(self, hdr):
85         """return nice representation of the package for the log"""
86         (n,a,e,v,r) = self._dopkgtup(hdr)
87         if e == '0':
88             pkg = '%s.%s %s-%s' % (n, a, v, r)
89         else:
90             pkg = '%s.%s %s:%s-%s' % (n, a, e, v, r)
91
92         return pkg
93
94     def callback(self, what, bytes, total, h, user):
95         if what == rpm.RPMCALLBACK_TRANS_START:
96             if bytes == 6:
97                 self.total_actions = total
98
99         elif what == rpm.RPMCALLBACK_TRANS_PROGRESS:
100             pass
101
102         elif what == rpm.RPMCALLBACK_TRANS_STOP:
103             pass
104
105         elif what == rpm.RPMCALLBACK_INST_OPEN_FILE:
106             self.lastmsg = None
107             hdr = None
108             if h is not None:
109                 try:
110                     hdr, rpmloc = h
111                 except:
112                     rpmloc = h
113                     hdr = readRpmHeader(self.ts, h)
114
115                 handle = self._makeHandle(hdr)
116                 fd = os.open(rpmloc, os.O_RDONLY)
117                 self.callbackfilehandles[handle]=fd
118                 if hdr['name'] not in self.installed_pkg_names:
119                     self.installed_pkg_names.append(hdr['name'])
120                     self.total_installed += 1
121                 return fd
122             else:
123                 self._localprint("No header - huh?")
124
125         elif what == rpm.RPMCALLBACK_INST_CLOSE_FILE:
126             hdr = None
127             if h is not None:
128                 try:
129                     hdr, rpmloc = h
130                 except:
131                     rpmloc = h
132                     hdr = readRpmHeader(self.ts, h)
133
134                 handle = self._makeHandle(hdr)
135                 os.close(self.callbackfilehandles[handle])
136                 fd = 0
137
138                 # log stuff
139                 #pkgtup = self._dopkgtup(hdr)
140                 self.logString.append(self._logPkgString(hdr))
141
142         elif what == rpm.RPMCALLBACK_INST_START:
143             self.total_installing += 1
144
145         elif what == rpm.RPMCALLBACK_UNINST_STOP:
146             pass
147
148         elif what == rpm.RPMCALLBACK_INST_PROGRESS:
149             if h is not None:
150                 percent = (self.total_installed*100L)/self.total_actions
151                 if total > 0:
152                     try:
153                         hdr, rpmloc = h
154                     except:
155                         rpmloc = h
156
157                     m = re.match("(.*)-(\d+.*)-(\d+\.\d+)\.(.+)\.rpm", os.path.basename(rpmloc))
158                     if m:
159                         pkgname = m.group(1)
160                     else:
161                         pkgname = os.path.basename(rpmloc)
162                 if self.output:
163                     fmt = self._makefmt(percent)
164                     msg = fmt % (self.headmsg, pkgname)
165                     if msg != self.lastmsg:
166                         self.lastmsg = msg
167
168                         msger.info(msg)
169
170                         if self.total_installed == self.total_actions:
171                             msger.raw('')
172                             msger.verbose('\n'.join(self.logString))
173
174         elif what == rpm.RPMCALLBACK_UNINST_START:
175             pass
176
177         elif what == rpm.RPMCALLBACK_UNINST_PROGRESS:
178             pass
179
180         elif what == rpm.RPMCALLBACK_UNINST_STOP:
181             self.total_removed += 1
182
183         elif what == rpm.RPMCALLBACK_REPACKAGE_START:
184             pass
185
186         elif what == rpm.RPMCALLBACK_REPACKAGE_STOP:
187             pass
188
189         elif what == rpm.RPMCALLBACK_REPACKAGE_PROGRESS:
190             pass
191
192 def readRpmHeader(ts, filename):
193     """ Read an rpm header. """
194
195     fd = os.open(filename, os.O_RDONLY)
196     h = ts.hdrFromFdno(fd)
197     os.close(fd)
198     return h
199
200 def splitFilename(filename):
201     """ Pass in a standard style rpm fullname
202
203         Return a name, version, release, epoch, arch, e.g.::
204             foo-1.0-1.i386.rpm returns foo, 1.0, 1, i386
205             1:bar-9-123a.ia64.rpm returns bar, 9, 123a, 1, ia64
206     """
207
208     if filename[-4:] == '.rpm':
209         filename = filename[:-4]
210
211     archIndex = filename.rfind('.')
212     arch = filename[archIndex+1:]
213
214     relIndex = filename[:archIndex].rfind('-')
215     rel = filename[relIndex+1:archIndex]
216
217     verIndex = filename[:relIndex].rfind('-')
218     ver = filename[verIndex+1:relIndex]
219
220     epochIndex = filename.find(':')
221     if epochIndex == -1:
222         epoch = ''
223     else:
224         epoch = filename[:epochIndex]
225
226     name = filename[epochIndex + 1:verIndex]
227     return name, ver, rel, epoch, arch
228
229 def getCanonX86Arch(arch):
230     #
231     if arch == "i586":
232         f = open("/proc/cpuinfo", "r")
233         lines = f.readlines()
234         f.close()
235         for line in lines:
236             if line.startswith("model name") and line.find("Geode(TM)") != -1:
237                 return "geode"
238         return arch
239     # only athlon vs i686 isn't handled with uname currently
240     if arch != "i686":
241         return arch
242
243     # if we're i686 and AuthenticAMD, then we should be an athlon
244     f = open("/proc/cpuinfo", "r")
245     lines = f.readlines()
246     f.close()
247     for line in lines:
248         if line.startswith("vendor") and line.find("AuthenticAMD") != -1:
249             return "athlon"
250         # i686 doesn't guarantee cmov, but we depend on it
251         elif line.startswith("flags") and line.find("cmov") == -1:
252             return "i586"
253
254     return arch
255
256 def getCanonX86_64Arch(arch):
257     if arch != "x86_64":
258         return arch
259
260     vendor = None
261     f = open("/proc/cpuinfo", "r")
262     lines = f.readlines()
263     f.close()
264     for line in lines:
265         if line.startswith("vendor_id"):
266             vendor = line.split(':')[1]
267             break
268     if vendor is None:
269         return arch
270
271     if vendor.find("Authentic AMD") != -1 or vendor.find("AuthenticAMD") != -1:
272         return "amd64"
273     if vendor.find("GenuineIntel") != -1:
274         return "ia32e"
275     return arch
276
277 def getCanonArch():
278     arch = os.uname()[4]
279
280     if (len(arch) == 4 and arch[0] == "i" and arch[2:4] == "86"):
281         return getCanonX86Arch(arch)
282
283     if arch == "x86_64":
284         return getCanonX86_64Arch(arch)
285
286     return arch
287
288 # Copy from libsatsolver:poolarch.c, with cleanup
289 archPolicies = {
290     "x86_64":       "x86_64:i686:i586:i486:i386",
291     "i686":         "i686:i586:i486:i386",
292     "i586":         "i586:i486:i386",
293     "ia64":         "ia64:i686:i586:i486:i386",
294     "aarch64":      "aarch64",
295     "armv7tnhl":    "armv7tnhl:armv7thl:armv7nhl:armv7hl",
296     "armv7thl":     "armv7thl:armv7hl",
297     "armv7nhl":     "armv7nhl:armv7hl",
298     "armv7hl":      "armv7hl",
299     "armv7l":       "armv7l:armv6l:armv5tejl:armv5tel:armv5l:armv4tl:armv4l:armv3l",
300     "armv6l":       "armv6l:armv5tejl:armv5tel:armv5l:armv4tl:armv4l:armv3l",
301     "armv5tejl":    "armv5tejl:armv5tel:armv5l:armv4tl:armv4l:armv3l",
302     "armv5tel":     "armv5tel:armv5l:armv4tl:armv4l:armv3l",
303     "armv5l":       "armv5l:armv4tl:armv4l:armv3l",
304     "mipsel":       "mipsel",
305 }
306
307 # dict mapping arch -> ( multicompat, best personality, biarch personality )
308 multilibArches = {
309     "x86_64":  ( "athlon", "x86_64", "athlon" ),
310 }
311
312 # from yumUtils.py
313 arches = {
314     # ia32
315     "athlon": "i686",
316     "i686": "i586",
317     "geode": "i586",
318     "i586": "i486",
319     "i486": "i386",
320     "i386": "noarch",
321
322     # amd64
323     "x86_64": "athlon",
324     "amd64": "x86_64",
325     "ia32e": "x86_64",
326
327     # arm
328     "armv7tnhl": "armv7nhl",
329     "armv7nhl": "armv7hl",
330     "armv7hl": "noarch",
331     "armv7l": "armv6l",
332     "armv6l": "armv5tejl",
333     "armv5tejl": "armv5tel",
334     "armv5tel": "noarch",
335
336     #itanium
337     "ia64": "noarch",
338
339     "mipsel": "mipsel",
340 }
341
342 def isMultiLibArch(arch=None):
343     """returns true if arch is a multilib arch, false if not"""
344     if arch is None:
345         arch = getCanonArch()
346
347     if not arches.has_key(arch): # or we could check if it is noarch
348         return False
349
350     if multilibArches.has_key(arch):
351         return True
352
353     if multilibArches.has_key(arches[arch]):
354         return True
355
356     return False
357
358 def getBaseArch():
359     myarch = getCanonArch()
360     if not arches.has_key(myarch):
361         return myarch
362
363     if isMultiLibArch(arch=myarch):
364         if multilibArches.has_key(myarch):
365             return myarch
366         else:
367             return arches[myarch]
368
369     if arches.has_key(myarch):
370         basearch = myarch
371         value = arches[basearch]
372         while value != 'noarch':
373             basearch = value
374             value = arches[basearch]
375
376         return basearch
377
378 def checkRpmIntegrity(bin_rpm, package):
379     return runner.quiet([bin_rpm, "-K", "--nosignature", package])
380
381 def checkSig(ts, package):
382     """ Takes a transaction set and a package, check it's sigs,
383         return 0 if they are all fine
384         return 1 if the gpg key can't be found
385         return 2 if the header is in someway damaged
386         return 3 if the key is not trusted
387         return 4 if the pkg is not gpg or pgp signed
388     """
389
390     value = 0
391     currentflags = ts.setVSFlags(0)
392     fdno = os.open(package, os.O_RDONLY)
393     try:
394         hdr = ts.hdrFromFdno(fdno)
395
396     except rpm.error, e:
397         if str(e) == "public key not availaiable":
398             value = 1
399         if str(e) == "public key not available":
400             value = 1
401         if str(e) == "public key not trusted":
402             value = 3
403         if str(e) == "error reading package header":
404             value = 2
405     else:
406         error, siginfo = getSigInfo(hdr)
407         if error == 101:
408             os.close(fdno)
409             del hdr
410             value = 4
411         else:
412             del hdr
413
414     try:
415         os.close(fdno)
416     except OSError:
417         pass
418
419     ts.setVSFlags(currentflags) # put things back like they were before
420     return value
421
422 def getSigInfo(hdr):
423     """ checks signature from an hdr hand back signature information and/or
424         an error code
425     """
426
427     import locale
428     locale.setlocale(locale.LC_ALL, 'C')
429
430     string = '%|DSAHEADER?{%{DSAHEADER:pgpsig}}:{%|RSAHEADER?{%{RSAHEADER:pgpsig}}:{%|SIGGPG?{%{SIGGPG:pgpsig}}:{%|SIGPGP?{%{SIGPGP:pgpsig}}:{(none)}|}|}|}|'
431     siginfo = hdr.sprintf(string)
432     if siginfo != '(none)':
433         error = 0
434         sigtype, sigdate, sigid = siginfo.split(',')
435     else:
436         error = 101
437         sigtype = 'MD5'
438         sigdate = 'None'
439         sigid = 'None'
440
441     infotuple = (sigtype, sigdate, sigid)
442     return error, infotuple
443