summaryrefslogtreecommitdiffstats
path: root/tools/pkgmgr_update.py
blob: 05d6457865e77f2f80fe9fb8f7665139ecb6d0de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#!/usr/bin/python

"""
    Program to update an existing bcfg2 Pkgmgr configuration file from a list
    of directories that contain RPMS.

    Only the epoch, version, release and simplefiles attributes are updated
    in existing entries.  All other entries and attributes are preserved.

    This is a total hack until a proper more generalised system for managing
    Pkgmgr configuation files is developed.
"""

__version__ = '0.1'

import datetime
import glob
import gzip
import optparse
import os
import rpm
import sys

# Compatibility imports
from Bcfg2.Bcfg2Py3k import urljoin

try:
    from lxml.etree import parse, tostring
except:
    from elementtree.ElementTree import parse, tostring

installOnlyPkgs = ['kernel',
                   'kernel-bigmem',
                   'kernel-enterprise',
                   'kernel-smp',
                   'kernel-modules',
                   'kernel-debug',
                   'kernel-unsupported',
                   'kernel-source',
                   'kernel-devel',
                   'kernel-default',
                   'kernel-largesmp-devel',
                   'kernel-largesmp',
                   'kernel-xen',
                   'gpg-pubkey']


def readRpmHeader(ts, filename):
    """
        Read an rpm header from an RPM file.
    """
    try:
        fd = os.open(filename, os.O_RDONLY)
    except:
        print("Failed to open RPM file %s" % filename)

    h = ts.hdrFromFdno(fd)
    os.close(fd)
    return h


def sortedDictValues(adict):
    """
        Sort a dictionary by its keys and return the items in sorted key order.
    """
    keys = list(adict.keys())
    keys.sort()
    return list(map(adict.get, keys))


def cmpRpmHeader(a, b):
    """
        cmp() implemetation suitable for use with sort.
    """
    n1 = str(a.get('name'))
    e1 = str(a.get('epoch'))
    v1 = str(a.get('version'))
    r1 = str(a.get('release'))
    n2 = str(b.get('name'))
    e2 = str(b.get('epoch'))
    v2 = str(b.get('version'))
    r2 = str(b.get('release'))

    return rpm.labelCompare((e1, v1, r1), (e2, v2, r2))


def loadRpms(dirs):
    """
       dirs is a list of directories to search for rpms.

       Builds a multilevel dictionary keyed by the package name and arch.
       Arch dictionary item is a list, one entry per package instance found.

       The list entries are dictionaries.  Keys are 'filename', 'mtime' 'name',
       'arch', 'epoch', 'version' and 'release'.

       e.g.

       packages = {
       'bcfg2' : { 'noarch' : [ {'filename':'bcfg2-0.9.2-0.0rc1.noarch.rpm', 'mtime':'',
                                 'name':'bcfg2', 'arch':'noarch', 'epoch':None, 'version':'0.9.2',
                                 'release':'0.0rc1'}
                                {'filename':'bcfg2-0.9.2-0.0rc5.noarch.rpm', 'mtime':'',
                                 'name':'bcfg2', 'arch':'noarch', 'epoch':None, 'version':'0.9.2',
                                 'release':'0.0rc5'}]},
       'bcfg2-server' { 'noarch' : [ {'filename':'bcfg2-server-0.9.2-0.0rc1.noarch.rpm', 'mtime':'',
                                      'name':'bcfg2-server', 'arch':'noarch', 'epoch':None,
                                      'version':'0.9.2', 'release':'0.0rc1'}
                                     {'filename':'bcfg2-server-0.9.2-0.0rc5.noarch.rpm', 'mtime':'',
                                      'name':"bcfg2-server', 'arch':'noarch', 'epoch':None,
                                      'version':'0.9.2', 'release':'0.0rc5'}]},
       }
    """
    packages = {}
    ts = rpm.TransactionSet()
    vsflags = 0
    vsflags |= rpm._RPMVSF_NODIGESTS
    vsflags |= rpm._RPMVSF_NOSIGNATURES
    ovsflags = ts.setVSFlags(vsflags)
    for dir in dirs:

        if options.verbose:
            print("Scanning directory: %s" % dir)

        for file in [files for files in os.listdir(dir)
                           if files.endswith('.rpm')]:

            filename = os.path.join(dir, file)

            # Get the mtime of the RPM file.
            file_mtime = datetime.date.fromtimestamp(os.stat(filename).st_mtime)

            # Get the RPM header
            header = readRpmHeader(ts, filename)

            # Get what we are interesting in out of the header.
            name = header[rpm.RPMTAG_NAME]
            epoch = header[rpm.RPMTAG_EPOCH]
            version = header[rpm.RPMTAG_VERSION]
            release = header[rpm.RPMTAG_RELEASE]
            subarch = header[rpm.RPMTAG_ARCH]

            if name not in installOnlyPkgs:
                packages.setdefault(name, {}).setdefault(subarch, []).append({'filename': file,
                                                                              'mtime': file_mtime,
                                                                              'name': name,
                                                                              'arch': subarch,
                                                                              'epoch': epoch,
                                                                              'version': version,
                                                                              'release': release})
            if options.verbose:
                sys.stdout.write('.')
                sys.stdout.flush()
        if options.verbose:
            sys.stdout.write('\n')

    return packages


class pkgmgr_URLopener(urllib.FancyURLopener):
    """
        Override default error handling so that we can see what the errors are.
    """
    def http_error_default(self, url, fp, errcode, errmsg, headers):
        """
            Override default error handling so that we can see what the errors are.
        """
        print("ERROR %s: Unable to retrieve %s" % (errcode, url))


def loadRepos(repolist):
    """
       repolist is a list of urls to yum repositories.

       Builds a multilevel dictionary keyed by the package name and arch.
       Arch dictionary item is a list, one entry per package instance found.

       The list entries are dictionaries.  Keys are 'filename', 'mtime' 'name',
       'arch', 'epoch', 'version' and 'release'.

       e.g.

       packages = {
       'bcfg2' : { 'noarch' : [ {'filename':'bcfg2-0.9.2-0.0rc1.noarch.rpm', 'mtime':'',
                                 'name':'bcfg2', 'arch':'noarch', 'epoch':None, 'version':'0.9.2',
                                 'release':'0.0rc1'}
                                {'filename':'bcfg2-0.9.2-0.0rc5.noarch.rpm', 'mtime':'',
                                 'name':'bcfg2', 'arch':'noarch', 'epoch':None, 'version':'0.9.2',
                                 'release':'0.0rc5'}]},
       'bcfg2-server' { 'noarch' : [ {'filename':'bcfg2-server-0.9.2-0.0rc1.noarch.rpm', 'mtime':'',
                                      'name':'bcfg2-server', 'arch':'noarch', 'epoch':None,
                                      'version':'0.9.2', 'release':'0.0rc1'}
                                     {'filename':'bcfg2-server-0.9.2-0.0rc5.noarch.rpm', 'mtime':'',
                                      'name':"bcfg2-server', 'arch':'noarch', 'epoch':None,
                                      'version':'0.9.2', 'release':'0.0rc5'}]},
       }

    """
    packages = {}
    for repo in repolist:
        url = urljoin(repo, './repodata/repomd.xml')

        try:
            opener = pkgmgr_URLopener()
            file, message = opener.retrieve(url)
        except:
            sys.exit()

        try:
            tree = parse(file)
        except IOError:
            print("ERROR: Unable to parse retrieved repomd.xml.")
            sys.exit()

        repomd = tree.getroot()
        for element in repomd:
            if element.tag.endswith('data') and element.attrib['type'] == 'primary':
                for property in element:
                    if property.tag.endswith('location'):
                        primaryhref = property.attrib['href']

        url = urljoin(repo, './' + primaryhref)

        if options.verbose:
            print("Loading : %s" % url)

        try:
            opener = pkgmgr_URLopener()
            file, message = opener.retrieve(url)
        except:
            sys.exit()

        try:
            repo_file = gzip.open(file)
            tree = parse(repo_file)
        except IOError:
            print("ERROR: Unable to parse retrieved file.")
            sys.exit()

        root = tree.getroot()
        for element in root:
            if element.tag.endswith('package'):
                for property in element:
                    if property.tag.endswith('name'):
                        name = property.text
                    elif property.tag.endswith('arch'):
                        subarch = property.text
                    elif property.tag.endswith('version'):
                        version = property.get('ver')
                        epoch = property.get('epoch')
                        release = property.get('rel')
                    elif property.tag.endswith('location'):
                        file = property.get('href')

                if name not in installOnlyPkgs:
                    packages.setdefault(name, {}).setdefault(subarch, []).append({'filename': file,
                                                                                  'name': name,
                                                                                  'arch': subarch,
                                                                                  'epoch': epoch,
                                                                                  'version': version,
                                                                                  'release': release})
                if options.verbose:
                    sys.stdout.write('.')
                    sys.stdout.flush()
        if options.verbose:
            sys.stdout.write('\n')

    return packages


def str_evra(instance):
    """
        Convert evra dict entries to a string.
    """
    if instance.get('epoch', '*') == '*' or instance.get('epoch', '*') == None:
        return '%s-%s.%s' % (instance.get('version', '*'), instance.get('release', '*'),
                             instance.get('arch', '*'))
    else:
        return '%s:%s-%s.%s' % (instance.get('epoch', '*'), instance.get('version', '*'),
                                instance.get('release', '*'), instance.get('arch', '*'))


def updatepkg(pkg):
    """
    """
    global package_dict
    name = pkg.get('name')
    if name not in installOnlyPkgs:
        for inst in [inst for inst in pkg if inst.tag == 'Instance']:
            arch = inst.get('arch')
            if name in package_dict:
                if arch in package_dict[name]:
                    package_dict[name][arch].sort(cmpRpmHeader)
                    latest = package_dict[name][arch][-1]
                    if cmpRpmHeader(inst, latest) == -1:
                        if options.verbose:
                            print("Found newer version of package %s" % name)
                            print("    Updating %s to %s" % (str_evra(inst),
                                                             str_evra(latest)))
                        if latest['epoch'] != None:
                            inst.attrib['epoch'] = str(latest['epoch'])
                        inst.attrib['version'] = latest['version']
                        inst.attrib['release'] = latest['release']
                        if inst.get('simplefile', False):
                            inst.attrib['simplefile'] = latest['filename']
                        if options.altconfigfile:
                            ignoretags = pkg.xpath(".//Ignore")
                            # if we find Ignore tags, then assume they're correct;
                            # otherwise, check the altconfigfile
                            if not ignoretags:
                                altpkgs = alttree.xpath(".//Package[@name='%s'][Ignore]" % name)
                                if (len(altpkgs) == 1):
                                    for ignoretag in altpkgs[0].xpath(".//Ignore"):
                                        if options.verbose:
                                            print("    Found Ignore tag in altconfigfile for package %s" % name)
                                        pkg.append(ignoretag)


def main():
    global package_dict
    global alttree
    if options.verbose:
        print("Loading Pkgmgr config file %s." % (options.configfile))

    tree = parse(options.configfile)
    config = tree.getroot()

    if options.altconfigfile:
        if options.verbose:
            print("Loading Pkgmgr alternate config file %s." %
                  (options.altconfigfile))

        alttree = parse(options.altconfigfile)

    if options.verbose:
        print("Loading package headers")

    if options.rpmdirs:
        package_dict = loadRpms(search_dirs)
    elif options.yumrepos:
        package_dict = loadRepos(repos)

    if options.verbose:
        print("Processing package headers")

    for pkg in config.getiterator('Package'):
        updatepkg(pkg)

    output.write(tostring(config))

if __name__ == "__main__":

    p = optparse.OptionParser()

    p.add_option('--configfile', '-c', action='store', \
                                   type='string', \
                                   help='Existing Pkgmgr configuration  file name.')
    p.add_option('--altconfigfile', '-a', action='store', \
                                   type='string', \
                                   help='''Alternate, existing Pkgmgr configuration file name to read
                                           Ignore tags from (used for upgrades).''')

    p.add_option('--rpmdirs', '-d', action='store',
                                   type='string', \
                                   help='''Comma separated list of directories to scan for RPMS.
                                           Wilcards are permitted.''')

    p.add_option('--outfile', '-o', action='store', \
                                   type='string', \
                                   help='Output file name or new Pkgrmgr file.')

    p.add_option('--verbose', '-v', action='store_true', \
                                    help='Enable verbose output.')

    p.add_option('--yumrepos', '-y', action='store',
                                   type='string', \
                                   help='''Comma separated list of YUM repository URLs to load.
                                           NOTE: Each URL must end in a '/' character.''')
    options, arguments = p.parse_args()

    if not options.configfile:
        print("An existing Pkgmgr configuration file must be specified with "
              "the -c option.")
        sys.exit()

    if not options.rpmdirs and not options.yumrepos:
        print("One of --rpmdirs and --yumrepos must be specified")
        sys.exit(1)

    # Set up list of directories to search
    if options.rpmdirs:
        search_dirs = []
        for d in options.rpmdirs.split(','):
            search_dirs += glob.glob(d)
        if options.verbose:
            print("The following directories will be scanned:")
            for d in search_dirs:
                print("    %s" % d)

    # Setup list of repos
    if options.yumrepos:
        repos = []
        for r in options.yumrepos.split(','):
            repos.append(r)
        if options.verbose:
            print("The following repositories will be scanned:")
            for d in repos:
                print("    %s" % d)

    if options.outfile:
        output = file(options.outfile, "w")
    else:
        output = sys.stdout

    package_dict = {}

    main()