- added timestamp-based JSON caching of configuration for faster loading
[invirt/packages/invirt-base.git] / files / usr / sbin / invirt-getconf
1 #!/usr/bin/env python
2
3 """
4 invirt-getconf [-f FILE] KEY prints the configuration the option named KEY from
5 the invirt configuration file FILE.  Keys are dot-separated paths into the YAML
6 configuration tree.  List indexes (0-based) are also treated as path
7 components.
8
9 (Due to this path language, certain restrictions are placed on the keys used in
10 the YAML configuration, e.g. they cannot contain dots.)
11
12 Examples:
13
14   invirt-getconf db.uri
15   invirt-getconf authn.0.type
16 """
17
18 from invirt.config import load
19 from sys import argv, exit, stderr
20 from optparse import OptionParser
21
22 class invirt_exception(Exception): pass
23
24 def main(argv):
25     try:
26         parser = OptionParser(usage = '%prog [options] key',
27                 description = __doc__.strip().split('\n\n')[0])
28         parser.add_option('-s', '--src',
29                 default = '/etc/invirt/master.yaml',
30                 help = 'the source YAML configuration file to read from')
31         parser.add_option('-c', '--cache',
32                 default = '/var/lib/invirt/invirt.json',
33                 help = 'path to the JSON cache')
34         parser.add_option('-r', '--refresh',
35                 action = 'store_true',
36                 help = 'force the cache to be regenerated')
37         opts, args = parser.parse_args()
38
39         try: [key] = args
40         except: raise invirt_exception(__doc__.strip())
41
42         conf = load(opts.src, opts.cache, opts.refresh)
43         components = key.split('.')
44         for i, component in enumerate(components):
45             progress = '.'.join(components[:i])
46             if type(conf) not in [dict, list]:
47                 raise invirt_exception(
48                         '%s: node has no children (atomic datum)' % progress)
49             if type(conf) == list:
50                 try: component = int(component)
51                 except: raise invirt_exception(
52                         '%s: node a list; integer path component required, '
53                         'but got "%s"' % (progress, component))
54             try: conf = conf[component]
55             except KeyError: raise invirt_exception(
56                     '%s: key "%s" not found' % (progress, component))
57             except IndexError: raise invirt_exception(
58                     '%s: index %s out of range' % (progress, component))
59         print conf
60     except (invirt_exception, OSError), ex:
61         print >> stderr, ex
62         return 1
63
64 if __name__ == '__main__':
65     exit(main(argv))
66
67 # vim:et:sw=4:ts=4