mio.py 14.2 KB
Newer Older
Anders Blomdell's avatar
Anders Blomdell committed
1
2
#!/usr/bin/python

Anders Blomdell's avatar
Anders Blomdell committed
3
from __future__ import print_function
Anders Blomdell's avatar
Anders Blomdell committed
4
import mio.filecache
Anders Blomdell's avatar
Anders Blomdell committed
5
6
7
8
9
import mio.installer
import mio.log
import mio.transform
import mio.parser
import mio.repository
Anders Blomdell's avatar
Anders Blomdell committed
10
import mio.node
Anders Blomdell's avatar
Anders Blomdell committed
11
import argparse
Anders Blomdell's avatar
Anders Blomdell committed
12
import os
Anders Blomdell's avatar
Anders Blomdell committed
13
14
15
16
17
import os.path
import re
import sys
from mio.exception import *
from mio.log import log, MUTE, SILENT, NORMAL, VERBOSE
18
import locale
Anders Blomdell's avatar
Anders Blomdell committed
19

Anders Blomdell's avatar
Anders Blomdell committed
20
def parse_with_path(path, filename, repository=None):
Anders Blomdell's avatar
Anders Blomdell committed
21
22
    f = mio.filecache.loadfile(path, filename)
    tree = mio.parser.parse(f.filename, url=f.key)
Anders Blomdell's avatar
Anders Blomdell committed
23
    
24
    join = None
Anders Blomdell's avatar
Anders Blomdell committed
25
26
27
    if tree._tag == "comps":
        # Transform comps to canonical form
        tree = mio.transform.from_fedora(tree)
28
        join = mio.transform.join
Anders Blomdell's avatar
Anders Blomdell committed
29
        pass
Anders Blomdell's avatar
Anders Blomdell committed
30
31
32
    elif tree._tag == "hostinfo":
        # Transform hostinfo to canonical form
        tree = mio.transform.from_hostinfo(tree)
Anders Blomdell's avatar
Anders Blomdell committed
33
        pass
Anders Blomdell's avatar
Anders Blomdell committed
34
35
36
    elif tree._tag == "mio":
        # Transform mio tree to canonical form
        tree = mio.transform.from_mio(tree)
Anders Blomdell's avatar
Anders Blomdell committed
37
38
39
40
41
        pass
    if repository != None:
        repository.add(tree._group_, join=join)
        pass
    return tree
Anders Blomdell's avatar
Anders Blomdell committed
42

Anders Blomdell's avatar
Anders Blomdell committed
43
def parse(filename, repository=None):
Anders Blomdell's avatar
Anders Blomdell committed
44
    for p in options.path:
Anders Blomdell's avatar
Anders Blomdell committed
45
        try:
Anders Blomdell's avatar
Anders Blomdell committed
46
47
            tree = parse_with_path(p, filename, repository)
            return tree
Anders Blomdell's avatar
Anders Blomdell committed
48
49
        except IOError as e:
            print(e)
Anders Blomdell's avatar
Anders Blomdell committed
50
51
52
53
            raise
            pass
    raise Exception("Could not parse %s" % filename)

54
class FindAndParse:
Anders Blomdell's avatar
Anders Blomdell committed
55

56
57
58
59
60
    def __init__(self):
        self.tried = set()

    def parse_with_path(self, path, filename, builder, target):
        if not (path,filename) in self.tried:
Anders Blomdell's avatar
Anders Blomdell committed
61
            try:
62
63
64
                parse_with_path(path, filename, builder) 
                self.tried.add((path,filename))
                return True
Anders Blomdell's avatar
Anders Blomdell committed
65
            except IOError as e:
66
67
                self.tried.add((path,filename))
                pass
Anders Blomdell's avatar
Anders Blomdell committed
68
            except ValueError as e:
69
                pass
Anders Blomdell's avatar
Anders Blomdell committed
70
71
            except DuplicateGroupException as e:
                print(e)
72
                traceback.print_exc()
Anders Blomdell's avatar
Anders Blomdell committed
73
                print("Failed to locate: %s" % target)
74
75
                sys.exit(1)
                pass
Anders Blomdell's avatar
Anders Blomdell committed
76
            pass
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
        return False
            

    def __call__(self, target, builder, url=None):
        path = list(options.path)
        if url:
            for p in url.path:
                path.insert(0, os.path.dirname(p))
                
        OK = False
        for p in path:
            if target.startswith("/"):
                m = re.match("^/([^/]*)", target)
                OK |= self.parse_with_path(p, "%s.mio" % (m.group(1)), builder, target)
                pass
            elif target.startswith("@"):
                filename = "base/comps.xml"
                try:
                    # Try to locate group file via repomd.xml
                    f = mio.filecache.loadfile(p, '/repodata/repomd.xml')
                    tree = mio.parser.parse(f.filename)
                    for l in tree._data_._location_:
                        if l.type[1] == 'group':
                            OK |= self.parse_with_path(p, l.href[0], builder, target)
                            break
                        pass
                    pass
Anders Blomdell's avatar
Anders Blomdell committed
104
                except IOError as e:
105
106
107
108
109
110
111
                    continue
                pass
            else:
                OK |= self.parse_with_path(p, "hostinfo.xml", builder, target)
                pass
        
        if OK:
Anders Blomdell's avatar
Anders Blomdell committed
112
            return
113
114
115
116
117
118
        if options.noyum and target.startswith('@'):
            # Synthetic target
            tmp1 = mio.parser.Node("mio", 0)
            tmp2 =  mio.parser.Node("group", 0, { "name": target })
            tmp1._add(tmp2)
            builder.add(tmp1._group_)
Anders Blomdell's avatar
Anders Blomdell committed
119
            pass
120
        else:
Anders Blomdell's avatar
Anders Blomdell committed
121
            print("Failed to locate: %s" % target)
Anders Blomdell's avatar
Anders Blomdell committed
122
123

if __name__ == '__main__':
124
    locale.setlocale(locale.LC_TIME, 'C')
Anders Blomdell's avatar
Anders Blomdell committed
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
    optParser = argparse.ArgumentParser(usage="%(prog)s [options]")
    optParser.add_argument("--backup",
                           action="store",
                           metavar="DIR",
                           help="saved a backup of changed files in DIR")
    optParser.add_argument("--backup-suffix",
                           action="store",
                           metavar="SUFFIX",
                           help="append SUFFIX to backup files")
    optParser.add_argument("--dump",
                           action="store_true", default=False, 
                           help="when listing, dump XML tree")
    optParser.add_argument("--exclude-rpm",
                           action="append", default=[],
                           metavar="RPM",
                           help="exclude RPM")
    optParser.add_argument("--install",
                           action="append", default=[],
                           metavar="TARGET",
                           help="install TARGET")
    optParser.add_argument("-l","--list",
                           action="append", default=[],
                           metavar="XML",
                           help="list available targets in XML")
    optParser.add_argument("--list-rpms",
                           action="append", default=[],
                           metavar="TARGET",
                           help="list rpms needed for TARGET")
    optParser.add_argument("--noyum",
                           action="store_true",
                           help="don't run yum (rpms will not be installed)")
    optParser.add_argument("-p", "--path",
                           nargs='+',
                           action="append", default=[],
                           metavar="DIR",
                           help="search path for files")
    optParser.add_argument("--prefix",
                           action="store",
                           metavar="DIR",
                           help="prefix for installed files")
    optParser.add_argument("-q","--quiet",
                           action="count", default=0,
                           dest="quiet", 
                           help="decrease verbosity")
    optParser.add_argument("--reachable-files",
                           action="append", default=[],
                           metavar="XML",
                           help="list files reachable from XML")
    optParser.add_argument("--reachable-rpms",
                           action="append", default=[],
                           metavar="XML",
                           help="list RPMs reachable from XML")
    optParser.add_argument("--test",
                           action="append", default=[],
                           metavar="TARGET",
                           help="test TARGET")
Anders Blomdell's avatar
Anders Blomdell committed
181
    optParser.add_argument("--dependency-tree",
Anders Blomdell's avatar
Anders Blomdell committed
182
                           action="append", nargs='*', default=None,
Anders Blomdell's avatar
Anders Blomdell committed
183
184
                           metavar="TARGET",
                           help="print dependency tree for TARGET")
Anders Blomdell's avatar
Anders Blomdell committed
185
186
187
188
    optParser.add_argument("-v","--verbose",
                           action="count",
                           dest="verbose", default=0,
                           help="increase verbosity")
Anders Blomdell's avatar
Anders Blomdell committed
189
    
Anders Blomdell's avatar
Anders Blomdell committed
190
    options = optParser.parse_args(sys.argv[1:])
Anders Blomdell's avatar
Anders Blomdell committed
191
    options.path = [ tuple(p,) for p in options.path ]
Anders Blomdell's avatar
Anders Blomdell committed
192
193
    mio.log.set_verbosity(NORMAL + options.verbose - options.quiet)

194
    find_and_parse = FindAndParse()
Anders Blomdell's avatar
Anders Blomdell committed
195
196
    rules = mio.repository.Repository(find_and_parse)

Anders Blomdell's avatar
Anders Blomdell committed
197
    rpm_result = None
Anders Blomdell's avatar
Anders Blomdell committed
198
199
200

    if options.prefix:
        os.environ["MIO_PREFIX"] = options.prefix
Anders Blomdell's avatar
Anders Blomdell committed
201
    
Anders Blomdell's avatar
Anders Blomdell committed
202
203
204
205
206
207
    if options.list:
        # List all targets reachable from the given source files
        for url in options.list:
            parse(url, rules)

        error = {}
Anders Blomdell's avatar
Anders Blomdell committed
208
        print("Reachable targets:")
Anders Blomdell's avatar
Anders Blomdell committed
209
210
        for g in rules.get_all(error):
            if not options.dump:
Anders Blomdell's avatar
Anders Blomdell committed
211
                print("  ",g.name[0])
Anders Blomdell's avatar
Anders Blomdell committed
212
            else:
Anders Blomdell's avatar
Anders Blomdell committed
213
                print(g._xml(indent=1))
Anders Blomdell's avatar
Anders Blomdell committed
214
215

        for e in error:
Anders Blomdell's avatar
Anders Blomdell committed
216
            print("Unresolved group: '%s'" % e)
Anders Blomdell's avatar
Anders Blomdell committed
217
            for r in error[e]:
Anders Blomdell's avatar
Anders Blomdell committed
218
                print("  from: '%s' in %s:%s" % (r.name[0], r._url, r._line))
Anders Blomdell's avatar
Anders Blomdell committed
219

Anders Blomdell's avatar
Anders Blomdell committed
220
221
222
223
224
225
226
227
    if options.list_rpms:
        installer = mio.installer.Installer(rules)
        for g in options.list_rpms:
            installer.add_group(g)
            pass

        log(NORMAL, "# List rpms for %s" % options.list_rpms)
        for r in installer.list_rpms():
Anders Blomdell's avatar
Anders Blomdell committed
228
            print(r)
Anders Blomdell's avatar
Anders Blomdell committed
229
230
231
            pass
        pass
    
Anders Blomdell's avatar
Anders Blomdell committed
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
    if options.reachable_files:
        # List all files reachable from the given source files
        reachable_rules = mio.repository.Repository(find_and_parse,
                                                    lambda x:x.startswith('@'))
        for url in options.reachable_files:
            parse(url, reachable_rules)
            pass
        
        error = {}
        log(VERBOSE, "Reachable targets:")
        files = {}
        for g in reachable_rules.get_all(error):
            installer = mio.installer.Installer(reachable_rules)
            log(VERBOSE, "Scanning: %s" % g.name[0])
            installer.add_group(g.name[0])
            for f in installer.file:
                if f.decl.source[0] == "":
                    # Exists in target system, used to change protection
                    continue
                if mio.node.parse_boolean(f.decl.delete[0]):
                    # Might exists in target system, but should be deleted
                    continue
                source = f.decl.source[0] or f.decl.name[0]
                path = "%s%s" % (f.decl.files[0:],source)
                try:
                    files[path].append(f.name)
                except KeyError:
                    files[path] = [ f.name ]
                pass
            pass
        
        if not error:
Anders Blomdell's avatar
Anders Blomdell committed
264
            for k in sorted(files.keys()):
Anders Blomdell's avatar
Anders Blomdell committed
265
                print(k)
Anders Blomdell's avatar
Anders Blomdell committed
266
267
268
            pass
        else:
            for e in error:
Anders Blomdell's avatar
Anders Blomdell committed
269
                print("Unresolved group: '%s'" % e)
Anders Blomdell's avatar
Anders Blomdell committed
270
                for r in error[e]:
Anders Blomdell's avatar
Anders Blomdell committed
271
272
                    print("  from: '%s' in %s:%s" % (r.name[0],
                                                     r._url, r._line))
Anders Blomdell's avatar
Anders Blomdell committed
273
274
275
276
277
                    pass
                pass
            pass
        pass

Anders Blomdell's avatar
Anders Blomdell committed
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
    if options.reachable_rpms:
        # List all RPMs reachable from the given source files
        reachable_rules = mio.repository.Repository(find_and_parse,
                                                    lambda x:x.startswith('@'))
        for url in options.reachable_rpms:
            parse(url, reachable_rules)
            pass
        
        error = {}
        log(VERBOSE, "Reachable targets:")
        rpms = {}
        for g in reachable_rules.get_all(error):
            installer = mio.installer.Installer(reachable_rules)
            log(VERBOSE, "Scanning: %s" % g.name[0])
            installer.add_group(g.name[0])
            for r in installer.rpm:
                rpms[r.name] = r.name
                pass
            pass
        
        if not error:
Anders Blomdell's avatar
Anders Blomdell committed
299
            for k in sorted(rpms.keys()):
Anders Blomdell's avatar
Anders Blomdell committed
300
                print(k)
Anders Blomdell's avatar
Anders Blomdell committed
301
302
303
            pass
        else:
            for e in error:
Anders Blomdell's avatar
Anders Blomdell committed
304
                print("Unresolved group: '%s'" % e)
Anders Blomdell's avatar
Anders Blomdell committed
305
                for r in error[e]:
Anders Blomdell's avatar
Anders Blomdell committed
306
307
                    print("  from: '%s' in %s:%s" % (r.name[0],
                                                     r._url, r._line))
Anders Blomdell's avatar
Anders Blomdell committed
308
309
310
311
312
                    pass
                pass
            pass
        pass

Anders Blomdell's avatar
Anders Blomdell committed
313
    if options.dependency_tree != None:
Anders Blomdell's avatar
Anders Blomdell committed
314
        def dump_tree(name, indent=0):
315
316
317
318
319
320
321
322
323
324
325
            def command_or_script(cos, prefix=''):
                if cos.command[0] != None:
                    print("%s  [%s command] %s" % (
                        ('  '*indent, prefix, cos.command[0])))
                    pass
                pass
                if cos.script[0] != None:
                    print("%s  [%s script] %s" % (
                        ('  '*indent, prefix, cos.script[0])))
                    pass
                pass
Anders Blomdell's avatar
Anders Blomdell committed
326
327
            print('%s%s' % ('  '*indent, name))
            tree = rules.get(name)
328
329
            for p in tree._pre_:
                command_or_script(p, 'pre')
330
331
332
333
334
            if not options.noyum:
                for r in tree._rpm_:
                    print("%s[r] %s" % ('  '*(indent+1), r.name[0]))
                    pass
                pass
Anders Blomdell's avatar
Anders Blomdell committed
335
            for s in tree._symlink_:
Anders Blomdell's avatar
Anders Blomdell committed
336
337
338
                print('%s[s] %s -> %s' % ('  '*(indent+1),
                                          s.name[0],
                                          s.value[0]))
Anders Blomdell's avatar
Anders Blomdell committed
339
340
                pass
            for f in tree._file_:
341
342
343
                if f.delete[0] == 'yes' or f.source[0] == '':
                    continue
                src = os.path.normpath('%s/%s' % (f.files[0:],
Anders Blomdell's avatar
Anders Blomdell committed
344
345
                                                  f.source[0] or f.name[0]))
                print('%s[f] %s = %s' % ('  '*(indent+1), f.name[0], src))
Anders Blomdell's avatar
Anders Blomdell committed
346
                pass
347
348
            for p in tree._post_:
                command_or_script(p, 'post')
Anders Blomdell's avatar
Anders Blomdell committed
349
350
351
352
            for d in tree._dependency_:
                dump_tree(d.name[0], indent+1)
                pass
            pass
353
        todo = [i for l in options.dependency_tree for i in l] # Flatten list
Anders Blomdell's avatar
Anders Blomdell committed
354
355
356
357
        if len(todo) == 0:
            tree = parse('hostinfo.xml')
            todo = [ h.name[0] for h in tree._group_]
        for target in todo:
Anders Blomdell's avatar
Anders Blomdell committed
358
359
360
361
            dump_tree(target)
            pass
        pass

Anders Blomdell's avatar
Anders Blomdell committed
362
363
364
365
366
367
368
    if options.test:
        installer = mio.installer.Installer(rules)
        for g in options.test:
            installer.add_group(g)

        if not options.noyum:
            log(NORMAL, "Testing rpms")
Anders Blomdell's avatar
Anders Blomdell committed
369
370
            installer.test_rpms(options.path,
                                options.exclude_rpm)
Anders Blomdell's avatar
Anders Blomdell committed
371
 
Anders Blomdell's avatar
Anders Blomdell committed
372
        log(NORMAL, "Testing files")
Anders Blomdell's avatar
Anders Blomdell committed
373
374
        installer.test_groups(options.prefix,
                              (options.backup, options.backup_suffix))
Anders Blomdell's avatar
Anders Blomdell committed
375
376
377
378
379
380
381
382
        
    if options.install:
        installer = mio.installer.Installer(rules)
        for g in options.install:
            installer.add_group(g)

        if not options.noyum:
            log(NORMAL, "Installing rpms")
383
384
385
386
            try:
                (rpm_result, failed) = installer.install_rpms(
                    options.path, options.exclude_rpm)
                pass
Anders Blomdell's avatar
Anders Blomdell committed
387
            except Exception as e:
388
                log(MUTE, "Failed to install rpm's, rerun with '--noyum'")
389
                raise()
390
391
                exit(1)
                pass
Anders Blomdell's avatar
Anders Blomdell committed
392
        log(NORMAL, "Installing files")
Anders Blomdell's avatar
Anders Blomdell committed
393
394
        installer.install_groups(options.prefix,
                                 (options.backup, options.backup_suffix))
Anders Blomdell's avatar
Anders Blomdell committed
395

Anders Blomdell's avatar
Anders Blomdell committed
396
    if rpm_result:
Anders Blomdell's avatar
Anders Blomdell committed
397
        print("Yum failed with %d" % rpm_result)
Anders Blomdell's avatar
Anders Blomdell committed
398
        for r in failed:
Anders Blomdell's avatar
Anders Blomdell committed
399
            print("Failed to install %s" % r)
Anders Blomdell's avatar
Anders Blomdell committed
400
        exit(1)