mio.py 14.8 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 mio.analyze
Anders Blomdell's avatar
Anders Blomdell committed
12
import argparse
Anders Blomdell's avatar
Anders Blomdell committed
13
import os
Anders Blomdell's avatar
Anders Blomdell committed
14
15
16
17
18
import os.path
import re
import sys
from mio.exception import *
from mio.log import log, MUTE, SILENT, NORMAL, VERBOSE
19
import locale
Anders Blomdell's avatar
Anders Blomdell committed
20

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

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

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

57
58
59
60
61
    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
62
            try:
63
64
65
                parse_with_path(path, filename, builder) 
                self.tried.add((path,filename))
                return True
Anders Blomdell's avatar
Anders Blomdell committed
66
            except IOError as e:
67
68
                self.tried.add((path,filename))
                pass
Anders Blomdell's avatar
Anders Blomdell committed
69
            except ValueError as e:
70
                pass
Anders Blomdell's avatar
Anders Blomdell committed
71
72
            except DuplicateGroupException as e:
                print(e)
73
                traceback.print_exc()
Anders Blomdell's avatar
Anders Blomdell committed
74
                print("Failed to locate: %s" % target)
75
76
                sys.exit(1)
                pass
Anders Blomdell's avatar
Anders Blomdell committed
77
            pass
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
        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
105
                except IOError as e:
106
107
108
109
110
111
112
                    continue
                pass
            else:
                OK |= self.parse_with_path(p, "hostinfo.xml", builder, target)
                pass
        
        if OK:
Anders Blomdell's avatar
Anders Blomdell committed
113
            return
114
115
116
117
118
119
        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
120
            pass
121
        else:
Anders Blomdell's avatar
Anders Blomdell committed
122
            print("Failed to locate: %s" % target)
Anders Blomdell's avatar
Anders Blomdell committed
123
124

if __name__ == '__main__':
125
    locale.setlocale(locale.LC_TIME, 'C')
Anders Blomdell's avatar
Anders Blomdell committed
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
    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
182
    optParser.add_argument("--dependency-tree",
Anders Blomdell's avatar
Anders Blomdell committed
183
                           action="append", nargs='*', default=None,
Anders Blomdell's avatar
Anders Blomdell committed
184
185
                           metavar="TARGET",
                           help="print dependency tree for TARGET")
Anders Blomdell's avatar
Anders Blomdell committed
186
187
188
189
    optParser.add_argument("--dependency-check",
                           action="append", nargs='*', default=None,
                           metavar="TARGET",
                           help="check dependencies for TARGET")
Anders Blomdell's avatar
Anders Blomdell committed
190
191
192
193
    optParser.add_argument("-v","--verbose",
                           action="count",
                           dest="verbose", default=0,
                           help="increase verbosity")
Anders Blomdell's avatar
Anders Blomdell committed
194
    
Anders Blomdell's avatar
Anders Blomdell committed
195
    options = optParser.parse_args(sys.argv[1:])
Anders Blomdell's avatar
Anders Blomdell committed
196
    options.path = [ tuple(p,) for p in options.path ]
Anders Blomdell's avatar
Anders Blomdell committed
197
198
    mio.log.set_verbosity(NORMAL + options.verbose - options.quiet)

199
    find_and_parse = FindAndParse()
Anders Blomdell's avatar
Anders Blomdell committed
200
201
    rules = mio.repository.Repository(find_and_parse)

Anders Blomdell's avatar
Anders Blomdell committed
202
    rpm_result = None
Anders Blomdell's avatar
Anders Blomdell committed
203
204
205

    if options.prefix:
        os.environ["MIO_PREFIX"] = options.prefix
Anders Blomdell's avatar
Anders Blomdell committed
206
    
Anders Blomdell's avatar
Anders Blomdell committed
207
208
209
210
211
212
    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
213
        print("Reachable targets:")
Anders Blomdell's avatar
Anders Blomdell committed
214
215
        for g in rules.get_all(error):
            if not options.dump:
Anders Blomdell's avatar
Anders Blomdell committed
216
                print("  ",g.name[0])
Anders Blomdell's avatar
Anders Blomdell committed
217
            else:
Anders Blomdell's avatar
Anders Blomdell committed
218
                print(g._xml(indent=1))
Anders Blomdell's avatar
Anders Blomdell committed
219
220

        for e in error:
Anders Blomdell's avatar
Anders Blomdell committed
221
            print("Unresolved group: '%s'" % e)
Anders Blomdell's avatar
Anders Blomdell committed
222
            for r in error[e]:
Anders Blomdell's avatar
Anders Blomdell committed
223
                print("  from: '%s' in %s:%s" % (r.name[0], r._url, r._line))
Anders Blomdell's avatar
Anders Blomdell committed
224

Anders Blomdell's avatar
Anders Blomdell committed
225
226
227
228
229
230
231
232
    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
233
            print(r)
Anders Blomdell's avatar
Anders Blomdell committed
234
235
236
            pass
        pass
    
Anders Blomdell's avatar
Anders Blomdell committed
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
    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
269
            for k in sorted(files.keys()):
Anders Blomdell's avatar
Anders Blomdell committed
270
                print(k)
Anders Blomdell's avatar
Anders Blomdell committed
271
272
273
            pass
        else:
            for e in error:
Anders Blomdell's avatar
Anders Blomdell committed
274
                print("Unresolved group: '%s'" % e)
Anders Blomdell's avatar
Anders Blomdell committed
275
                for r in error[e]:
Anders Blomdell's avatar
Anders Blomdell committed
276
277
                    print("  from: '%s' in %s:%s" % (r.name[0],
                                                     r._url, r._line))
Anders Blomdell's avatar
Anders Blomdell committed
278
279
280
281
282
                    pass
                pass
            pass
        pass

Anders Blomdell's avatar
Anders Blomdell committed
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
    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
304
            for k in sorted(rpms.keys()):
Anders Blomdell's avatar
Anders Blomdell committed
305
                print(k)
Anders Blomdell's avatar
Anders Blomdell committed
306
307
308
            pass
        else:
            for e in error:
Anders Blomdell's avatar
Anders Blomdell committed
309
                print("Unresolved group: '%s'" % e)
Anders Blomdell's avatar
Anders Blomdell committed
310
                for r in error[e]:
Anders Blomdell's avatar
Anders Blomdell committed
311
312
                    print("  from: '%s' in %s:%s" % (r.name[0],
                                                     r._url, r._line))
Anders Blomdell's avatar
Anders Blomdell committed
313
314
315
316
317
                    pass
                pass
            pass
        pass

Anders Blomdell's avatar
Anders Blomdell committed
318
319
320
321
322
323
324
325
    if options.dependency_check != None:
        # Flatten list
        targets = [i for l in options.dependency_check for i in l ]
        if len(targets) == 0:
            tree = parse('hostinfo.xml')
            targets = [ h.name[0] for h in tree._group_]
        mio.analyze.dependency_check(rules, options, targets)

Anders Blomdell's avatar
Anders Blomdell committed
326
    if options.dependency_tree != None:
Anders Blomdell's avatar
Anders Blomdell committed
327
        def dump_tree(name, indent=0):
328
329
330
331
332
333
334
335
336
337
            def command_or_script(cos, prefix=''):
                if cos.command[0] != None:
                    print("%s  [%s command] %s" % (
                        ('  '*indent, prefix, cos.command[0])))
                    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
338
339
            print('%s%s' % ('  '*indent, name))
            tree = rules.get(name)
340
341
            for p in tree._pre_:
                command_or_script(p, 'pre')
Anders Blomdell's avatar
Anders Blomdell committed
342
                pass
343
344
345
346
347
            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
348
            for s in tree._symlink_:
Anders Blomdell's avatar
Anders Blomdell committed
349
350
351
                print('%s[s] %s -> %s' % ('  '*(indent+1),
                                          s.name[0],
                                          s.value[0]))
Anders Blomdell's avatar
Anders Blomdell committed
352
353
                pass
            for f in tree._file_:
354
355
356
                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
357
358
                                                  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
359
                pass
360
361
            for p in tree._post_:
                command_or_script(p, 'post')
Anders Blomdell's avatar
Anders Blomdell committed
362
363
364
365
            for d in tree._dependency_:
                dump_tree(d.name[0], indent+1)
                pass
            pass
366
        todo = [i for l in options.dependency_tree for i in l] # Flatten list
Anders Blomdell's avatar
Anders Blomdell committed
367
368
369
370
        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
371
372
373
374
            dump_tree(target)
            pass
        pass

Anders Blomdell's avatar
Anders Blomdell committed
375
376
377
378
379
380
381
    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
382
383
            installer.test_rpms(options.path,
                                options.exclude_rpm)
Anders Blomdell's avatar
Anders Blomdell committed
384
 
Anders Blomdell's avatar
Anders Blomdell committed
385
        log(NORMAL, "Testing files")
Anders Blomdell's avatar
Anders Blomdell committed
386
387
        installer.test_groups(options.prefix,
                              (options.backup, options.backup_suffix))
Anders Blomdell's avatar
Anders Blomdell committed
388
389
390
391
392
393
394
395
        
    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")
396
397
398
399
            try:
                (rpm_result, failed) = installer.install_rpms(
                    options.path, options.exclude_rpm)
                pass
Anders Blomdell's avatar
Anders Blomdell committed
400
            except Exception as e:
401
                log(MUTE, "Failed to install rpm's, rerun with '--noyum'")
402
                raise()
403
404
                exit(1)
                pass
Anders Blomdell's avatar
Anders Blomdell committed
405
        log(NORMAL, "Installing files")
Anders Blomdell's avatar
Anders Blomdell committed
406
407
        installer.install_groups(options.prefix,
                                 (options.backup, options.backup_suffix))
Anders Blomdell's avatar
Anders Blomdell committed
408

Anders Blomdell's avatar
Anders Blomdell committed
409
    if rpm_result:
Anders Blomdell's avatar
Anders Blomdell committed
410
        print("Yum failed with %d" % rpm_result)
Anders Blomdell's avatar
Anders Blomdell committed
411
        for r in failed:
Anders Blomdell's avatar
Anders Blomdell committed
412
            print("Failed to install %s" % r)
Anders Blomdell's avatar
Anders Blomdell committed
413
        exit(1)