print warning message for detecting rpm post script failed
[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         elif what == rpm.RPMCALLBACK_SCRIPT_ERROR:
192             if h is not None:
193                 try:
194                     hdr, rpmloc = h
195                 except:
196                     rpmloc = h
197
198                 m = re.match("(.*)-(\d+.*)-(\d+\.\d+)\.(.+)\.rpm", os.path.basename(rpmloc))
199                 if m:
200                     pkgname = m.group(1)
201                 else:
202                     pkgname = os.path.basename(rpmloc)
203
204                 msger.warning('(%s) Post script failed' % pkgname)
205
206 def readRpmHeader(ts, filename):
207     """ Read an rpm header. """
208
209     fd = os.open(filename, os.O_RDONLY)
210     h = ts.hdrFromFdno(fd)
211     os.close(fd)
212     return h
213
214 def splitFilename(filename):
215     """ Pass in a standard style rpm fullname
216
217         Return a name, version, release, epoch, arch, e.g.::
218             foo-1.0-1.i386.rpm returns foo, 1.0, 1, i386
219             1:bar-9-123a.ia64.rpm returns bar, 9, 123a, 1, ia64
220     """
221
222     if filename[-4:] == '.rpm':
223         filename = filename[:-4]
224
225     archIndex = filename.rfind('.')
226     arch = filename[archIndex+1:]
227
228     relIndex = filename[:archIndex].rfind('-')
229     rel = filename[relIndex+1:archIndex]
230
231     verIndex = filename[:relIndex].rfind('-')
232     ver = filename[verIndex+1:relIndex]
233
234     epochIndex = filename.find(':')
235     if epochIndex == -1:
236         epoch = ''
237     else:
238         epoch = filename[:epochIndex]
239
240     name = filename[epochIndex + 1:verIndex]
241     return name, ver, rel, epoch, arch
242
243 def getCanonX86Arch(arch):
244     #
245     if arch == "i586":
246         f = open("/proc/cpuinfo", "r")
247         lines = f.readlines()
248         f.close()
249         for line in lines:
250             if line.startswith("model name") and line.find("Geode(TM)") != -1:
251                 return "geode"
252         return arch
253     # only athlon vs i686 isn't handled with uname currently
254     if arch != "i686":
255         return arch
256
257     # if we're i686 and AuthenticAMD, then we should be an athlon
258     f = open("/proc/cpuinfo", "r")
259     lines = f.readlines()
260     f.close()
261     for line in lines:
262         if line.startswith("vendor") and line.find("AuthenticAMD") != -1:
263             return "athlon"
264         # i686 doesn't guarantee cmov, but we depend on it
265         elif line.startswith("flags") and line.find("cmov") == -1:
266             return "i586"
267
268     return arch
269
270 def getCanonX86_64Arch(arch):
271     if arch != "x86_64":
272         return arch
273
274     vendor = None
275     f = open("/proc/cpuinfo", "r")
276     lines = f.readlines()
277     f.close()
278     for line in lines:
279         if line.startswith("vendor_id"):
280             vendor = line.split(':')[1]
281             break
282     if vendor is None:
283         return arch
284
285     if vendor.find("Authentic AMD") != -1 or vendor.find("AuthenticAMD") != -1:
286         return "amd64"
287     if vendor.find("GenuineIntel") != -1:
288         return "ia32e"
289     return arch
290
291 def getCanonArch():
292     arch = os.uname()[4]
293
294     if (len(arch) == 4 and arch[0] == "i" and arch[2:4] == "86"):
295         return getCanonX86Arch(arch)
296
297     if arch == "x86_64":
298         return getCanonX86_64Arch(arch)
299
300     return arch
301
302 # Copy from libsatsolver:poolarch.c, with cleanup
303 archPolicies = {
304     "x86_64":       "x86_64:i686:i586:i486:i386",
305     "i686":         "i686:i586:i486:i386",
306     "i586":         "i586:i486:i386",
307     "ia64":         "ia64:i686:i586:i486:i386",
308     "aarch64":      "aarch64",
309     "armv7tnhl":    "armv7tnhl:armv7thl:armv7nhl:armv7hl",
310     "armv7thl":     "armv7thl:armv7hl",
311     "armv7nhl":     "armv7nhl:armv7hl",
312     "armv7hl":      "armv7hl",
313     "armv7l":       "armv7l:armv6l:armv5tejl:armv5tel:armv5l:armv4tl:armv4l:armv3l",
314     "armv6l":       "armv6l:armv5tejl:armv5tel:armv5l:armv4tl:armv4l:armv3l",
315     "armv5tejl":    "armv5tejl:armv5tel:armv5l:armv4tl:armv4l:armv3l",
316     "armv5tel":     "armv5tel:armv5l:armv4tl:armv4l:armv3l",
317     "armv5l":       "armv5l:armv4tl:armv4l:armv3l",
318     "mipsel":       "mipsel",
319 }
320
321 # dict mapping arch -> ( multicompat, best personality, biarch personality )
322 multilibArches = {
323     "x86_64":  ( "athlon", "x86_64", "athlon" ),
324 }
325
326 # from yumUtils.py
327 arches = {
328     # ia32
329     "athlon": "i686",
330     "i686": "i586",
331     "geode": "i586",
332     "i586": "i486",
333     "i486": "i386",
334     "i386": "noarch",
335
336     # amd64
337     "x86_64": "athlon",
338     "amd64": "x86_64",
339     "ia32e": "x86_64",
340
341     # arm
342     "armv7tnhl": "armv7nhl",
343     "armv7nhl": "armv7hl",
344     "armv7hl": "noarch",
345     "armv7l": "armv6l",
346     "armv6l": "armv5tejl",
347     "armv5tejl": "armv5tel",
348     "armv5tel": "noarch",
349
350     #itanium
351     "ia64": "noarch",
352
353     "mipsel": "mipsel",
354 }
355
356 def isMultiLibArch(arch=None):
357     """returns true if arch is a multilib arch, false if not"""
358     if arch is None:
359         arch = getCanonArch()
360
361     if not arches.has_key(arch): # or we could check if it is noarch
362         return False
363
364     if multilibArches.has_key(arch):
365         return True
366
367     if multilibArches.has_key(arches[arch]):
368         return True
369
370     return False
371
372 def getBaseArch():
373     myarch = getCanonArch()
374     if not arches.has_key(myarch):
375         return myarch
376
377     if isMultiLibArch(arch=myarch):
378         if multilibArches.has_key(myarch):
379             return myarch
380         else:
381             return arches[myarch]
382
383     if arches.has_key(myarch):
384         basearch = myarch
385         value = arches[basearch]
386         while value != 'noarch':
387             basearch = value
388             value = arches[basearch]
389
390         return basearch
391
392 def checkRpmIntegrity(bin_rpm, package):
393     return runner.quiet([bin_rpm, "-K", "--nosignature", package])
394
395 def checkSig(ts, package):
396     """ Takes a transaction set and a package, check it's sigs,
397         return 0 if they are all fine
398         return 1 if the gpg key can't be found
399         return 2 if the header is in someway damaged
400         return 3 if the key is not trusted
401         return 4 if the pkg is not gpg or pgp signed
402     """
403
404     value = 0
405     currentflags = ts.setVSFlags(0)
406     fdno = os.open(package, os.O_RDONLY)
407     try:
408         hdr = ts.hdrFromFdno(fdno)
409
410     except rpm.error, e:
411         if str(e) == "public key not availaiable":
412             value = 1
413         if str(e) == "public key not available":
414             value = 1
415         if str(e) == "public key not trusted":
416             value = 3
417         if str(e) == "error reading package header":
418             value = 2
419     else:
420         error, siginfo = getSigInfo(hdr)
421         if error == 101:
422             os.close(fdno)
423             del hdr
424             value = 4
425         else:
426             del hdr
427
428     try:
429         os.close(fdno)
430     except OSError:
431         pass
432
433     ts.setVSFlags(currentflags) # put things back like they were before
434     return value
435
436 def getSigInfo(hdr):
437     """ checks signature from an hdr hand back signature information and/or
438         an error code
439     """
440
441     import locale
442     locale.setlocale(locale.LC_ALL, 'C')
443
444     string = '%|DSAHEADER?{%{DSAHEADER:pgpsig}}:{%|RSAHEADER?{%{RSAHEADER:pgpsig}}:{%|SIGGPG?{%{SIGGPG:pgpsig}}:{%|SIGPGP?{%{SIGPGP:pgpsig}}:{(none)}|}|}|}|'
445     siginfo = hdr.sprintf(string)
446     if siginfo != '(none)':
447         error = 0
448         sigtype, sigdate, sigid = siginfo.split(',')
449     else:
450         error = 101
451         sigtype = 'MD5'
452         sigdate = 'None'
453         sigid = 'None'
454
455     infotuple = (sigtype, sigdate, sigid)
456     return error, infotuple
457